<template>
    <div>
        <el-dialog title="选择题设置" :visible.sync="dialogVisibleChoice" :append-to-body="true" width="800px"
            :before-close="handleClose" class="dialog_diy">
            <div v-if="dialogVisibleChoice">
                <div class="a_addBox">
                    <div style="font-size: 16px; color: #c7c7c7">
                        请输入题目内容
                        <!-- <el-button type="primary" size="small" @click="pasteOption" style="margin-left:10px">智能粘贴</el-button> -->
                    </div>
                    <div class="a_add_box" v-for="(item1, index1) in testJson.testCount" :key="index1">
                        <div class="a_add_checkType">
                            <span :class="{ active: testJson.testJson[index1].type == '1' }"
                                @click="checkTestType('1', testJson.testJson[index1])">单选题</span>
                            <span :class="{ active: testJson.testJson[index1].type == '2' }"
                                @click="checkTestType('2', testJson.testJson[index1])">多选题</span>
                        </div>
                        <div class="a_add_head">
                            <div class="timuUpImg">
                                <div>
                                    {{ index1 + 1 + "、" }}
                                    <el-input class="a_add_head_input" v-model="testJson.testJson[index1].teststitle"
                                        placeholder="请输入题目...">
                                    </el-input>
                                </div>
                                <div class="xzUpImg" @click.stop="addImg($event)">
                                    <img src="../../../assets/icon/xzUpImg.png" alt="" />
                                    <input type="file" accept="image/*" style="display: none"
                                        @change="beforeUploadTiMu($event, index1)" />
                                </div>
                            </div>
                            <div class="a_add_head_div">
                                <el-button type="primary" size="small" @click="addTestList()">添加</el-button>
                                <el-button type="primary" size="small" @click="deleteTestList(index1)"
                                    v-if="testJson.testCount != 1">删除
                                </el-button>
                            </div>
                        </div>
                        <div class="timuImgBox" v-if="testJson.testJson[index1].timuList &&
                            testJson.testJson[index1].timuList.length
                            ">
                            <div v-for="(timg, tIndex) in testJson.testJson[index1].timuList" :key="tIndex" class="timuImg"
                                @click.stop="previewImg(timg.src)">
                                <img :src="timg.src" alt="" />
                                <div class="deleteWord" @click.stop="deleteM(index1, tIndex)">
                                    <img src="../../../assets/icon/delete.png" alt="" />
                                </div>
                            </div>
                        </div>
                        <div class="a_add_body">
                            <div class="a_add_input a_add_input_choice">
                                <el-radio-group v-model="testJson.testJson[index1].answer"
                                    v-if="testJson.testJson[index1].type == 1">
                                    <div class="radioBox">
                                        <el-radio v-for="(item2, checkIndex) in testJson.testJson[index1]
                                            .testItem" :key="checkIndex" :label="checkIndex">
                                            <div style="margin-right: 10px">
                                                选项{{ checkIndex + 1 }}
                                            </div>
                                            <div style="margin-right: 10px; width: 300px" v-if="testJson.testJson[index1].checkList[checkIndex] &&
                                                testJson.testJson[index1].checkList[checkIndex]
                                                    .imgType &&
                                                testJson.testJson[index1].checkList[checkIndex]
                                                    .imgType == 1
                                                ">
                                                <div class="inImg" @click.stop="previewImg(
                                                    testJson.testJson[index1].checkList[checkIndex]
                                                        .src
                                                )
                                                    ">
                                                    <el-image :src="testJson.testJson[index1].checkList[checkIndex]
                                                        .src
                                                        " lazy />
                                                </div>
                                            </div>

                                            <el-input v-else v-model="testJson.testJson[index1].checkList[checkIndex]
                                                " placeholder="请输入选项..."
                                                style="width: 300px; margin-right: 10px"></el-input>
                                            <div class="xzUpImg" @click.stop="addImg($event)">
                                                <img src="../../../assets/icon/xzUpImg.png" alt="" />
                                                <input type="file" accept="image/*" style="display: none"
                                                    @change="beforeUploadTi($event, index1, checkIndex)" />
                                            </div>
                                        </el-radio>
                                    </div>
                                </el-radio-group>
                                <el-checkbox-group v-model="testJson.testJson[index1].answer"
                                    v-if="testJson.testJson[index1].type == '2'">
                                    <div class="radioBox">
                                        <el-checkbox v-for="(item2, checkIndex1) in testJson.testJson[index1]
                                            .testItem" :key="checkIndex1" :label="checkIndex1">
                                            <div style="margin-right: 10px">
                                                选项{{ checkIndex1 + 1 }}
                                            </div>
                                            <div style="margin-right: 10px; width: 300px" v-if="testJson.testJson[index1].checkList[checkIndex1] &&
                                                testJson.testJson[index1].checkList[checkIndex1]
                                                    .imgType &&
                                                testJson.testJson[index1].checkList[checkIndex1]
                                                    .imgType == 1
                                                ">
                                                <div class="inImg" @click.stop="previewImg(
                                                    testJson.testJson[index1].checkList[checkIndex1]
                                                        .src
                                                )
                                                    ">
                                                    <el-image :src="testJson.testJson[index1].checkList[checkIndex1]
                                                        .src
                                                        " lazy />
                                                </div>
                                            </div>

                                            <el-input v-else v-model="testJson.testJson[index1].checkList[checkIndex1]
                                                " placeholder="请输入选项..."
                                                style="width: 300px; margin-right: 10px"></el-input>
                                            <div class="xzUpImg" @click.stop="addImg($event)">
                                                <img src="../../../assets/icon/xzUpImg.png" alt="" />
                                                <input type="file" accept="image/*" style="display: none"
                                                    @change="beforeUploadTi($event, index1, checkIndex1)" />
                                            </div>
                                        </el-checkbox>
                                    </div>
                                </el-checkbox-group>
                            </div>
                            <div class="a_add_body_div" style="margin-bottom: 3px">
                                <el-button type="primary" size="small"
                                    @click="addTcheckList(testJson.testJson[index1])">添加</el-button>
                                <el-button type="primary" size="small" @click="deleteTcheckList(testJson.testJson[index1])"
                                    v-if="testJson.testJson[index1].testItem != 1">删除
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="addTest">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    props: {
        dialogVisibleChoice: {
            type: Boolean,
            default: false
        },
        json: {
            type: Object
        }
    },
    data() {
        return {
            testJson: {

            }
        }
    },
    watch: {
        dialogVisibleChoice(newValue, oldValue) {
            this.testJson = JSON.parse(JSON.stringify(this.json));
        }
    },
    methods: {
        handleClose(done) {
            this.close()
            done()
        },
        close() {
            this.$emit("update:dialogVisibleChoice", false)
        },
        addImg(e) {
            var el = e.currentTarget;
            el.getElementsByTagName("input")[0].click();
            e.target.value = "";
        },
        previewImg(url) {
            this.$hevueImgPreview(url);
        },
        //自动获取剪贴板
        pasteOption() {
            let iframe = top.document.querySelectorAll("#AIChat iframe")[0]
            if (!iframe) {
                this.$message.error("请使用AI共创生成题目")
                return;
            }
            let copyData = iframe.contentWindow.copyData
            if (!copyData || !copyData.selectData.length) {
                this.$message.error("请使用AI共创生成题目")
                return;
            }
            let selectData = copyData.selectData;
            for (var i = 0; i < selectData.length; i++) {
                let answer = 0
                switch (selectData[i].answer[0]) {
                    case 'A':
                        answer = 0
                        break;
                    case 'B':
                        answer = 1
                        break;
                    case 'C':
                        answer = 2
                        break;
                    case 'D':
                        answer = 3
                        break;
                    case 'E':
                        answer = 4
                        break;
                    default:
                        break;
                }
                this.testJson.testJson.push({
                    teststitle: selectData[i].subject,
                    testItem: selectData[i].options.length,
                    checkList: selectData[i].options,
                    timuList: [],
                    answer: answer,
                    type: "1",
                });
                this.testJson.testCount++;
            }
            var isTestJson = JSON.parse(JSON.stringify(this.testJson));
            isTestJson.testJson = this.testJson.testJson.filter((el) => {
                var elc = el.checkList.filter((element) => {
                    return element != "";
                });
                return (
                    (el.teststitle != "" || el.timuList.length > 0) && elc.length != 0
                );
            });
            isTestJson.testCount = isTestJson.testJson.length;
            this.testJson = isTestJson
            this.$forceUpdate();
        },
        //切换选择题类型
        checkTestType(type, json) {
            json.type = type;
            if(json.type == '2'){
                json.answer = [];
            }else{
                json.answer = ""
            }
        },
        //添加选择题图片
        beforeUploadTiMu(event, i) {
            const loading = this.openLoading();
            var file = event.target.files[0];
            var credentials = {
                accessKeyId: "AKIATLPEDU37QV5CHLMH",
                secretAccessKey: "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",
            }; //秘钥形式的登录上传
            window.AWS.config.update(credentials);
            window.AWS.config.region = "cn-northwest-1"; //设置区域

            var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
            var _this = this;

            if (file) {
                var params = {
                    Key:
                        file.name.split(".")[0] +
                        new Date().getTime() +
                        "." +
                        file.name.split(".")[file.name.split(".").length - 1],
                    ContentType: file.type,
                    Body: file,
                    "Access-Control-Allow-Credentials": "*",
                    ACL: "public-read",
                }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
                var options = {
                    partSize: 2048 * 1024 * 1024,
                    queueSize: 2,
                    leavePartsOnError: true,
                };
                bucket
                    .upload(params, options)
                    .on("httpUploadProgress", function (evt) {
                        //这里可以写进度条
                        // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
                    })
                    .send(function (err, data) {
                        loading.close();
                        if (err) {
                            _this.$message.error("上传失败");
                        } else {
                            if (_this.testJson.testJson[i].timuList) {
                                _this.testJson.testJson[i].timuList.push({
                                    src: data.Location,
                                });
                            } else {
                                _this.testJson.testJson[i].timuList = [];
                                _this.testJson.testJson[i].timuList.push({
                                    src: data.Location,
                                });
                            }
                            _this.$forceUpdate();
                        }
                    });
            }
        },
        //添加选择题题目图片
        beforeUploadTi(event, i, j) {
            const loading = this.openLoading();
            var file = event.target.files[0];
            var credentials = {
                accessKeyId: "AKIATLPEDU37QV5CHLMH",
                secretAccessKey: "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",
            }; //秘钥形式的登录上传
            window.AWS.config.update(credentials);
            window.AWS.config.region = "cn-northwest-1"; //设置区域

            var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
            var _this = this;

            if (file) {
                var params = {
                    Key:
                        file.name.split(".")[0] +
                        new Date().getTime() +
                        "." +
                        file.name.split(".")[file.name.split(".").length - 1],
                    ContentType: file.type,
                    Body: file,
                    "Access-Control-Allow-Credentials": "*",
                    ACL: "public-read",
                }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
                var options = {
                    partSize: 2048 * 1024 * 1024,
                    queueSize: 2,
                    leavePartsOnError: true,
                };
                bucket
                    .upload(params, options)
                    .on("httpUploadProgress", function (evt) {
                        //这里可以写进度条
                        // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
                    })
                    .send(function (err, data) {
                        loading.close();
                        if (err) {
                            _this.$message.error("上传失败");
                        } else {
                            _this.testJson.testJson[i].checkList[j] = {};
                            _this.testJson.testJson[i].checkList[j].src = data.Location;
                            _this.testJson.testJson[i].checkList[j].imgType = 1;
                            _this.$forceUpdate();
                        }
                    });
            }
        },
        //添加题目
        addTestList() {
            this.testJson.testJson.push({
                teststitle: "",
                testItem: 1,
                checkList: [],
                timuList: [],
                answer: "",
                type: "1",
            });
            this.testJson.testCount++;
        },
        //删除题目
        deleteTestList(index) {
            this.testJson.testJson.splice(index, 1);
            this.testJson.testCount--;
        },
        //删除题目图片
        deleteM(i, j) {
            this.testJson.testJson[i].timuList.splice(j, 1);
        },
        //添加选项
        addTcheckList(json) {
            json.checkList.length++;
            json.testItem++;
        },
        //删除选项    
        deleteTcheckList(json) {
            if(json.type == '1' && json.answer == (json.checkList.length-1)){
                json.answer = ""
            }else if(json.type == '2' && json.answer.indexOf(json.checkList.length-1) != -1){
                json.answer.splice(json.checkList.length-1,1)
            }
            json.checkList.length--;
            json.testItem--;
        },
        //添加选择题
        addTest() {
            var aj = this.testJson.testJson;
            var b = 1;
            for (var i = 0; i < aj.length; i++) {
                if (aj[i].teststitle === "" && aj[i].timuList.length == 0) {
                    var a = 1;
                    for (let index = 0; index < aj[i].testItem; index++) {
                        const element = aj[i].checkList[index]
                            ? aj[i].checkList[index]
                            : "";
                        if (element != "") {
                            b++;
                            this.$message.error(`请将题目${i+1}填写完整。`);
                            return;
                        } else {
                            a++;
                        }
                    }
                    if (b == 1) {
                        this.$message.error("至少填写一个问题");
                        return;
                    }
                } else if (aj[i].teststitle != "" || aj[i].timuList.length > 0) {
                    for (let index = 0; index < aj[i].testItem; index++) {
                        const element = aj[i].checkList[index]
                            ? aj[i].checkList[index]
                            : "";
                        var index = 0;
                        for (var z = 0; z < aj[i].checkList.length; z++) {
                            var checkC = aj[i].checkList[z] ? aj[i].checkList[z] : "";
                            if (checkC != "") {
                                index++;
                            } else {
                                this.$message.error(`题目${i+1}选项不能为空！`);
                                return;
                            }
                        }
                        b++;
                        if (index < 2) {
                            this.$message.error("填写了的题目，选项至少要有两项！");
                            return;
                        }
                        if (
                            (aj[i].type == "2" && !aj[i].answer.length) ||
                            (aj[i].type == "1" && aj[i].answer !== 0 && !aj[i].answer)
                        ) {
                            this.$message.error("有题目未选择答案请选择答案");
                            return;
                        }
                    }
                }
            }
            var isTestJson = JSON.parse(JSON.stringify(this.testJson));
            isTestJson.testJson = this.testJson.testJson.filter((el) => {
                var elc = el.checkList.filter((element) => {
                    return element != "";
                });
                return (
                    (el.teststitle != "" || el.timuList.length > 0) && elc.length != 0
                );
            });
            isTestJson.testCount = isTestJson.testJson.length;

            this.$emit("add",45,isTestJson)
        },
    },
    mounted() {
        this.testJson = JSON.parse(JSON.stringify(this.json));
    },
}
</script>

<style scoped>
.dialog_diy>>>.el-dialog__header {
    background: #3c3c3c !important;
    padding: 15px 20px;
}

.dialog_diy>>>.el-dialog__title {
    color: #fff;
}

.dialog_diy>>>.el-dialog__headerbtn {
    top: 19px;
}

.dialog_diy>>>.el-dialog__headerbtn .el-dialog__close {
    color: #fff;
}

.dialog_diy>>>.el-dialog__headerbtn .el-dialog__close:hover {
    color: #fff;
}

.dialog_diy>>>.el-dialog__body,
.dialog_diy>>>.el-dialog__footer {
    background: #fafafa;
}

.a_addBox {
    margin: 10px 0;
    background: #fff;
    padding: 15px;
    max-height: 600px;
    overflow: auto;
}

.a_add_box {
    border-bottom: 2px solid #eee;
    padding-bottom: 25px;
}

.a_add_head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 10px 0 0 0;
    font-size: 18px;
}

.a_add_checkType {
    margin-top: 10px;
    display: flex;
    font-size: 16px;
    align-items: center;
}

.a_add_checkType span {
    box-sizing: border-box;
    padding: 0 0 5px 0;
    cursor: pointer;
}

.a_add_checkType span+span {
    margin-left: 10px;
}

.a_add_checkType .active {
    border-bottom: 2px solid #409eff;
    color: #409eff;
}

.a_add_head .a_add_head_input {
    width: 300px;
}

.a_add_head .a_add_head_div {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.a_add_body {
    display: flex;
    /* align-items: center; */
    align-items: flex-end;
}

.a_add_input {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.a_add_input_choice {
    flex-direction: column;
    margin-right: 10px;
}

.a_add_input_choice>>>.el-radio {
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    margin: 30px 0 0 0;
}

.a_add_input_choice>>>.el-checkbox {
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    margin: 30px 0 0 0;
}

.xzUpImg {
    width: 25px;
    height: 25px;
    cursor: pointer;
}

.xzUpImg>img {
    width: 100%;
    height: 100%;
}

.timuUpImg {
    display: flex;
    flex-direction: row;
    align-items: center;
}

.timuUpImg>div:nth-child(1) {
    margin-right: 10px;
}

.timuImgBox {
    margin: 10px 0;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    align-items: flex-start;
}

.timuImg {
    width: 100px;
    margin: 5px 0;
    cursor: pointer;
    position: relative;
}

.timuImg:hover .deleteWord {
    display: block;
}

.deleteWord {
    width: 25px;
    height: 25px;
    position: absolute;
    right: -5px;
    top: -5px;
    cursor: pointer;
    display: none;
}

.timuImg>img,
.deleteWord>img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.radioBox>div {
    margin: 10px 0 0 10px;
}

.radioBox>>>.el-radio__input,
.radioBox>>>.el-checkbox__inner {
    margin-left: 10px;
}

.radioBox>>>.el-radio__label,
.radioBox>>>.el-checkbox__label {
    display: flex;
    align-items: center;
}

.inImg {
    width: 50px;
}

.inImg>img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
</style>