<template>
    <div class="pb_content" style="background: #F0F2F5;" v-loading="loading">
        <div class="pb_content_body" style="position: relative; margin: 0">
            <div class="right">
                <div class="courseTop">
                    <div class="stepsNav">
                        <el-breadcrumb separator-class="el-icon-arrow-right">
                            <el-breadcrumb-item :to="{
                                path:
                                    '/test?userid=' +
                                    userid +
                                    '&oid=' +
                                    oid +
                                    '&org=' +
                                    org +
                                    '&role=' +
                                    role,
                            }">表单管理</el-breadcrumb-item>
                            <el-breadcrumb-item>
                                <span style="color: rgb(15, 126, 255)">新建表单</span>
                            </el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>
                    <div class="r_pub_button_retrun" @click="retrunCourse">返回</div>
                </div>
                <div class="step_box" :style="{ width: steps == 2 && '100%' }">
                    <setInfo v-if="steps == 1 && !loading" :oid="oid" :org="org" :steps.sync="steps" :title.sync="title"
                        :testType.sync="testType" :see.sync="see" :cJson.sync="cJson" :typeid.sync="typeid"
                        :brief.sync="brief" :juri.sync="juri" :overDate.sync="overDate" :juriList.sync="juriList" :typeInfo.sync="typeInfo">
                    </setInfo>
                    <editInfo v-if="steps == 2 && !loading" :oid="oid" :org="org" :steps.sync="steps"
                        :title.sync="title" :cJson.sync="cJson" @save="save" @publish="publish"></editInfo>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import setInfo from './setInfo/index.vue'
import editInfo from './edit/index.vue'
export default {
    components: {
        setInfo, editInfo
    },
    data() {
        return {
            userid: this.$route.query.userid,
            oid: this.$route.query.oid,
            org: this.$route.query.org,
            role: this.$route.query.role,
            cid: this.$route.query.cid,
            steps: 1,
            title: "",
            testType: [],
            see: false,
            cJson: [],
            loading: false,
            look: "",
            typeid: "",
            brief: "",
            juri: '0',
            overDate: "",
            juriList: [],
            typeInfo: [],
        }
    },
    watch: {
        steps(newValue, oldValue) {
            if (!this.title) {
                this.$message.error("请补充填写课程名称");
                this.steps = 1
                return;
            }
            // else if(!this.juriList.length){
            //     this.$message.error("请选择权限")
            //     this.steps = 1
            //     return
            // } 
            if (this.cid) {
                this.updateWork(this.look)
            } else {
                this.addWork();
            }
        }
    },
    methods: {
        retrunCourse() {
            this
                .$confirm("是否保存已编辑内容？", "提示", {
                    confirmButtonText: "保存",
                    cancelButtonText: "不保存",
                    distinguishCancelAndClose: true,
                    type: "warning",
                })
                .then(() => {
                    if (this.cid == "" || this.cid == undefined) {
                        if (this.title == "") {
                            this.$message.error("请补充填写课程名称");
                            return;
                        } else {
                            this.addWork(5);
                        }
                        // else if(!this.juriList.length){
                        //     this.$message.error("请选择权限")
                        //     return
                        // }
                    } else {
                        if (this.title == "") {
                            this.$message.error("请补充填写课程名称");
                            return;
                        } else {
                            this.updateWork(5);
                        }
                        // else if(!this.juriList.length){
                        //     this.$message.error("请选择权限")
                        //     return
                        // }
                    }
                })
                .catch((v) => {
                    console.log(v)
                    if (v == "cancel") {
                        this.goTo(
                            "/test?userid=" +
                            this.userid +
                            "&oid=" +
                            this.oid +
                            "&org=" +
                            this.org +
                            "&role=" +
                            this.role
                        );
                    }
                });
        },
        goTo(path) {
            this.$router.push(path);
        },
        addWork(look) {
            let j3 = []
            if(this.typeInfo.length){
                this.typeInfo.forEach(e => {
                    j3.push(e.value)
                })
            }
            let params = [
                {
                    uid: this.userid,
                    title: this.title,
                    brief: this.brief,
                    cover: "",
                    evaId: "",
                    astudent: this.juri,
                    see: this.see == true ? 1 : 0,
                    chapters: JSON.stringify(this.cJson),
                    template: "",
                    courseType: JSON.stringify(this.testType),
                    ateacher: "",
                    inviteCode: "",
                    typeid: this.typeid ? this.typeid : '',
                    overtime: this.overDate ? this.formatTime(this.overDate) : '',
                    j2: this.juriList.length ? this.juriList.join(",") : '',
                    j3: j3.length ? j3.join(",") : '',
                },
            ];
            this.ajax
                .post(this.$store.state.api + "addTestCourse3", params)
                .then((res) => {
                    this.cid = res.data.courseId;
                    if (look == 5) {
                        this.$message.success("保存成功")
                        this.goTo(
                            "/test?userid=" +
                            this.userid +
                            "&oid=" +
                            this.oid +
                            "&org=" +
                            this.org +
                            "&role=" +
                            this.role
                        );
                    }
                    setTimeout(() => {
                        this.getData(2);
                    }, 1000);
                })
                .catch((err) => {
                    this.$message.error("网络不佳");
                    console.error(err);
                });
        },
        formatTime(timestamp) {
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        },
        updateWork(look) {
            let j3 = []
            if(this.typeInfo.length){
                this.typeInfo.forEach(e => {
                    j3.push(e.value)
                })
            }
            let params = [
                {
                    cid: this.cid,
                    title: this.title,
                    brief: this.brief,
                    cover: "",
                    evaId: "",
                    astudent: this.juri,
                    see: this.see == true ? 1 : 0,
                    chapters: JSON.stringify(this.cJson),
                    uid: this.userid,
                    courseType: JSON.stringify(this.testType),
                    ateacher: "",
                    inviteCode: "",
                    look: look == 3 ? 2 : look == 4 ? this.look : look == 5 ? this.look : look,
                    typeid: this.typeid ? this.typeid : '',
                    overtime: this.overDate ? this.formatTime(this.overDate) : '',
                    j2: this.juriList.length ? this.juriList.join(",") : '',
                    j3: j3.length ? j3.join(",") : '',
                },
            ];
            this.ajax
                .post(this.$store.state.api + "updateTestCourse3", params)
                .then((res) => {
                    if (look == 3) {
                        this.$message.success("发布成功")
                        this.goTo(
                            "/test?userid=" +
                            this.userid +
                            "&oid=" +
                            this.oid +
                            "&org=" +
                            this.org +
                            "&role=" +
                            this.role
                        );
                    } else if (look == 4) {
                        this.$message.success("保存成功")
                    } else if (look == 1 || look == 2) {
                        // this.$message.success("保存成功")
                    } else if (look == 5) {
                        this.$message.success("保存成功")
                        this.goTo(
                            "/test?userid=" +
                            this.userid +
                            "&oid=" +
                            this.oid +
                            "&org=" +
                            this.org +
                            "&role=" +
                            this.role
                        );
                    }
                    setTimeout(() => {
                        this.getData(2);
                    }, 1000);
                })
                .catch((err) => {
                    this.$message.error("网络不佳");
                    console.error(err);
                });
        },
        getData(type) {
            if (this.cid == "" || this.cid == undefined) {
                console.log("这是新增课程");
            } else {
                if (type != 2) {
                    this.loading = true
                }
                let params = {
                    cid: this.cid,
                };
                this.ajax
                    .get(this.$store.state.api + "getTestCourseDetail", params)
                    .then((res) => {
                        this.cJson = JSON.parse(res.data[0][0].chapters);
                        this.title = res.data[0][0].title;
                        this.juri = res.data[0][0].juri ? res.data[0][0].juri : '0';
                        this.overDate = res.data[0][0].overTime ? res.data[0][0].overTime : '';
                        this.juriList = res.data[0][0].juri2 ? res.data[0][0].juri2.split(',') : [];
                        let juri3 = res.data[0][0].juri3 ? res.data[0][0].juri3.split(',') : [];
                        if(juri3.length > 0){
                            this.typeInfo.forEach(e =>{
                                let array2 = []
                                for (var i = 0; i < e.child.length; i++) {
                                    array2.push(e.child[i].id)
                                }
                                e.value = this.arrayToArray(juri3, array2)[0]
                            })
                        }
                        this.see = res.data[0][0].open == 1 ? true : false;

                        this.typeid = res.data[0][0].typeid;
                        this.brief = res.data[0][0].brief;
                        this.testType = [];
                        for (var i = 0; i < res.data[1].length; i++) {
                            this.testType.push(res.data[1][i].typeid);
                        }
                        console.log(this.testType);
                        this.look = res.data[0][0].look
                        this.$forceUpdate()
                        if (type != 2) {
                            this.loading = false
                        }
                    })
                    .catch((err) => {
                        console.error(err);
                    });
            }
        },
        save(look) {
            this.updateWork(look == 4 ? look : this.look)
        },
        publish() {
            this.updateWork(3)
        },
        //获取分类类名
        getTypeInfo() {
            this.loading = true
            let params = {
                oid: this.oid
            };
            this.ajax
                .get(this.$store.state.api + "selectPerInfoAllTea", params)
                .then((res) => {
                    this.typeInfo = res.data[0];
                    let typeInfo = res.data[1];
                    this.typeInfo.forEach((e) => {
                        e.child = [];
                        e.value = '';
                        typeInfo.forEach((i) => {
                            if (e.id == i.parentid) {
                                e.child.push({ id: i.id, name: i.name })
                            }
                        })
                    })
                    this.loading = false
                    console.log(this.typeInfo, "typeInfo");
                    this.getData();
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        arrayToArray(arrayo, arrayt) {
            let array1 = arrayo;
            let array2 = arrayt;

            let commonElements = [];

            for (let i = 0; i < array1.length; i++) {
                for (let j = 0; j < array2.length; j++) {
                if (array1[i] === array2[j]) {
                    commonElements.push(array1[i]);
                }
                }
            }
            return commonElements;
        },
    },
    mounted() {
        this.getTypeInfo();
    },
}
</script>

<style scoped>
.pb_content {
    height: 100% !important;
    /* margin: 0 20px 0 20px; */
}

.pb_content_body {
    width: 100% !important;
    height: 100%;
}

.right {
    height: 100%;
    width: 100%;
    display: flex;
    overflow: hidden;
    flex-direction: column;
}

.basic_box {
    margin: 0 auto;
    position: relative;
    padding: 0 20px 0 20px;
}

.courseTop {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: calc(100% - 40px);
    margin: 0 auto;
    padding: 10px 0;
}

.stepsNav {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
}

.step_box {
    width: calc(100% - 40px);
    margin: 0 auto;
    height: calc(100% - 38px);
}
</style>