<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"></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:"",
        }
    },
    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 if(!this.juriList.length){
                            this.$message.error("请选择权限")
                            return
                        }else {
                            this.addWork(5);
                        }
                    } else {
                        if (this.title == "") {
                            this.$message.error("请补充填写课程名称");
                            return;
                        }else if(!this.juriList.length){
                            this.$message.error("请选择权限")
                            return
                        }else {
                            this.updateWork(5);
                        }
                    }
                })
                .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 params = [
                {
                    uid: this.userid,
                    title: this.title.replace(/%/g, "%25"),
                    brief: this.brief.replace(/%/g, "%25"),
                    cover: "",
                    evaId: "",
                    astudent: this.juri,
                    see: this.see == true ? 1 : 0,
                    chapters: JSON.stringify(this.cJson).replaceAll(/%/g, "%25"),
                    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(",") : ''
                },
            ];
            this.ajax
                .post(this.$store.state.api + "addTestCourse", 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 params = [
                {
                    cid: this.cid,
                    title: this.title.replace(/%/g, "%25"),
                    brief: this.brief.replace(/%/g, "%25"),
                    cover: "",
                    evaId: "",
                    astudent: this.juri,
                    see: this.see == true ? 1 : 0,
                    chapters: JSON.stringify(this.cJson).replaceAll(/%/g, "%25"),
                    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(",") : ''
                },
            ];
            this.ajax
                .post(this.$store.state.api + "updateTestCourse", 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(',') : [];
                        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)
        },
    },
    mounted () {
        this.getData();
    },
}
</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>