<script setup lang="ts">
    import { ref, onMounted, watch } from "vue";
    import { getClassInfos, getCourseList, getCurriculumList, getKnowledgeList, getDefectsList, getTaskDetail, saveTaskInfo } from "../../api/techer/taskEditor";
    import { useRoute } from "vue-router"
    import router from '../../router/index'
    import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
    import { Back } from "@element-plus/icons-vue";

    const currStep = ref(0);
    const classInfos = ref([]);
    const curriculumList = ref([]);
    const courseInfos = ref(0);
    const loadingTable = ref(false);
    const knowledgeList = ref([]);
    const normalDefectsList = ref([]);
    const otherDefectsList = ref([]);
    const deffectsCheckeds: any = ref({});
    const durationStudyMins: any = ref({});
    const taskId:any = ref(null);
    const linkId:any=ref(null);
    const form = ref({
        id: "",
        name:"",
        classId: null,
        curriculumId:null,
        courseId: "",
        mustPipDefectIds:[],
        optionChapters:[],
    });
    const getCourseChecked = () => {
        let ary:any = courseInfos.value;
        //let rslt: any = [];
        for (let i = 0, len = ary.length; i < len; i++) {
            if (ary[i].checked) {
                //rslt.push(ary[i].id);
                return ary[i].id;
            }
        }
        return "";
    }
    const getOptionChapters = () => {
        let rslt: any = [];
        for (let k in durationStudyMins.value) {
            let val = durationStudyMins.value[k];
            rslt.push({
                chapterId: k,
                durationStudyMin:val
            });
        }
        return rslt;
    }
    const getMustPipDefectIds = () => {
       
        let rslt: any = [];
        for (let k in deffectsCheckeds.value) {
            if (deffectsCheckeds.value[k]) {
                rslt.push(k);
            }
        }
        return rslt;
    }
    const saveTask = () => {
        form.value.courseId = getCourseChecked();
        form.value.optionChapters = getOptionChapters();
        form.value.mustPipDefectIds = getMustPipDefectIds();
        if (form.value.classId == null) {
            ElMessage({
                showClose: true,
                message: '尚未选择班级',
                type: 'warning',
            })
            return;
        }
        if (form.value.courseId == null ||(form.value.courseId.toString()).length<1) {
            ElMessage({
                showClose: true,
                message: '尚未选择需要发布的课程',
                type: 'warning',
            })
            return;
        }
        form.value.id = taskId.value;
       
        saveTaskInfo(form.value).then((e: any) => {
            if (e.data.code == 0) {
                ElMessage({
                    showClose: true,
                    message: "保存成功",
                    type: 'success',
                });

            } else {
                ElMessage({
                    showClose: true,
                    message: '保存失败：' + e.msg || "系统发生异常",
                    type: 'warning',
                });
            }
        });
    }
    const preStep = () => {
        currStep.value--;
    }
    const nextStep = () => {
        if (currStep.value == 0) {
            if (form.value.classId == null || form.value.classId.toString().length<1) {
                ElMessage({
                    showClose: true,
                    message: '尚未选择班级',
                    type: 'warning',
                })
                return;
            }
            // form.course = getCourseChecked();
            if (form.value.courseId==null||form.value.courseId.toString().length < 1) {
                ElMessage({
                    showClose: true,
                    message: '尚未选择需要发布的课程',
                    type: 'warning',
                })
                return;
            }
        }
        currStep.value++;
        
    }
    /**设置选中的课程 */
    const changeCheckCourse = (id:any,e:any) => {
        let ary2:any = courseInfos.value;
        form.value.courseId = "";
        for (let i = 0, len = ary2.length; i < len; i++) {
            let item = ary2[i];
            let id2 = item.id;
            if (id2 == id) {
                item.checked = e.target.checked;
                form.value.courseId = id;
            } else {
                item.checked = false;
            }
        }
        ///设置选中后根据课程的id获取知识点
      
    }
    /**初始化设置选中项 */
    const setCourseChecked = (id:any) => {
        let ary2:any = courseInfos.value;
        for (let i = 0, len = ary2.length; i < len; i++) {
            let id2 = ary2[i].id;
            if (id2 == id) {
                ary2[i].checked = true;
            } else {
                ary2[i].checked = false;
            }
        }
    }
    /** */
    const getImage = (url:any) => {
        if (url == null)
            return null;
        if (url.indexOf("http") == 0) {
            return `url(${url})`;
        }
        let obj = new URL(`../../${url}`, import.meta.url).href;
        let rslt = `url(${obj})`;
       
        return rslt;
    }
   

    /**点击设置缺陷的选择 */
    const changeCheckDeffects = (id: any, e: any, type: any) => {
        deffectsCheckeds.value[id] = e.target.checked;
    }
    /**获取编辑的数据 */
    const getEditorForm = () => {
        if (taskId.value != null && taskId.value.toString().length > 0) {
            getTaskDetail(taskId.value).then((e: any) => {
                if (e.data.code == 0) {
                    form.value = e.data.data;
                    setCourseChecked(form.value.courseId);
                    if (form.value.mustPipDefectIds != null) {
                        for (let i = 0, len = form.value.mustPipDefectIds.length; i < len; i++) {
                            let item = form.value.mustPipDefectIds[i];
                            deffectsCheckeds.value[item] = true;
                          
                        }
                    }
                    console.log(form.value);
                    if (form.value.optionChapters != null) {
                        for (let i = 0, len = form.value.optionChapters.length; i < len; i++) {
                            let item = form.value.optionChapters[i];
                            durationStudyMins.value[item.chapterId]=item.durationStudyMin;
                        }
                    }
                }
            });
        }
    }
    const back2Task = () => {
       if(linkId.value!=null){
            router.push({
                path: "/TaskMng/"+linkId.value,
            });
       }else{
            router.push({
                path: "/TaskMng",
            });
       }
     
    }
    const setDurationStudyMinInfo = (data:any) => {
        for (let i = 0, len = data.length; i < len; i++) {
            let item = data[i];
            let id = item.id;
            durationStudyMins.value[id] = durationStudyMins.value[id] || item.durationStudyMin;
            if (item.children != null) {
                setDurationStudyMinInfo(item.children);
            }
        }
    }
    watch(() => form.value.courseId, (n, o) => {
        
        //// 根据选中的课程获取章节的列表
        getKnowledgeList(n).then((e: any) => {
            if (e.data.code == 0) {
                //for (let i = 0, len = e.data.data==null?0: e.data.data.length; i < len; i++) {
                //    let id = e.data.data[i].id;
                //    durationStudyMins.value[id] = durationStudyMins.value[id] || e.data.data[i].durationStudyMin;
                //}
                setDurationStudyMinInfo(e.data.data);
                console.log(durationStudyMins.value);
                knowledgeList.value = e.data.data;
            }
        });

        /////根据选中的课程获取缺陷的列表
        getDefectsList(n).then((e: any) => {
        
            let aryN:any = [];
            let aryO:any = [];
            let list = e.data.data.list;
            for (let i = 0, len = list.length; i < len; i++) {
                let item = list[i];
                if (item.type == 1) {
                    aryN.push(item);
                } else {
                    aryO.push(item);
                }
                deffectsCheckeds.value[item.id] = deffectsCheckeds.value[item.id]|| false;
            }
            normalDefectsList.value = aryN;
            otherDefectsList.value = aryO;
        });

    });
    watch(() => form.value.classId, (n, o) => {
       
       
        getCurriculumList(n).then((e: any) => {
           // form.value.curriculumId = null;
            let list = e.data.data.list;
            curriculumList.value = list;
            if (form.value.curriculumId != null) {
             
                if (!list.find((e: any) => {
         
                    return e.id == form.value.curriculumId;
                })) {
                  
                    form.value.curriculumId = null;
                }
            }
        });
    });
    onMounted(() => {
        const route = useRoute();
        console.log(route);
        if (route.params.taskId != null&&route.params.taskId.toString().length>0) {
            taskId.value = route.params.taskId;
        }
        if(route.query.linkId!=null){
            linkId.value=route.query.linkId;
        }
        getClassInfos().then((e: any) => {
            classInfos.value = e.data.data.list;
            
        });
        
        ////课程列表先获取后再与内容绑定
        getCourseList().then((e: any) => {
            if (e.data.code == 0) {
                let list = e.data.data.list;
                courseInfos.value = list;
                getEditorForm();
                setCourseChecked(form.value.courseId);
            }
        });
    });
</script>
<template>
    <div class="task-editor-wrapper">
        <div class="task-editor-steps-wrapper">
            <div class="task-back" @click="back2Task">
                <!--<el-icon style="margin-right:1rem; border-radius:10px; border:1px solid #000;"><Back /></el-icon>-->
                <el-button circle  :icon="Back"></el-button>
                <div style="margin-left:0.5rem;">返回任务</div>
            </div>
            <el-steps direction="vertical" :active="currStep" finish-status="success">
                <el-step title="基础设置" />
                <el-step title="知识点编辑" />
                <el-step title="管道缺陷" />
            </el-steps>
            <div class="task-step-opts">
                <el-button v-if="currStep>0" type="default" @click="preStep()">上一步</el-button>
                <el-button v-if="currStep<2" type="default" @click="nextStep()">下一步</el-button>
                <el-button v-if="currStep==2" type="primary" @click="saveTask()">保存</el-button>
            </div>
        </div>
        <div class="task-editor-panel">
            <div v-show="currStep==0" class="base-setting setting-info">
                <h3>任务名称</h3>
                <el-input v-model="form.name" style="width:300px;" />
                <h3>班级选择</h3>
                <el-select style="width:300px;" v-model="form.classId">
                    <el-option v-for="item in classInfos" :key="item.id" :label="item.majorName" :value="item.id"></el-option>
                </el-select>
                <h3>课程选择</h3>
                <el-select style="width:300px;" v-model="form.curriculumId">
                    <el-option v-for="item in curriculumList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <h3>项目选择</h3>
                <div class="course-selector">
                    <div class="course-selector-item" v-for="item in courseInfos" :style="{backgroundImage:getImage(item.imageUrl)}">
                        <input class="checkCourse" type="checkbox" :checked="item.checked" @change="changeCheckCourse(item.id,$event)" />
                        <div class="course-title">{{item.name}}</div>
                    </div>
                </div>

            </div>
            <div v-show="currStep==1" class="knowledge-setting setting-info">
                <el-table row-key="id" :data="knowledgeList"
                          v-loading="loadingTable"
                          style="width: 100%" height="100%" 
                          highlight-current-row>
                    <el-table-column prop="name" label="知识点名称" />
                    <el-table-column prop="durationStudyMin" label="知识点停留时长" >
                        <template  #default="scope">
                            <el-input-number v-model="durationStudyMins[scope.row.id]"
                                             :min="0"
                                             :max="1000"
                                             controls-position="right"
                                             size="default"
                                             />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="currStep==2" class="defects-setting setting-info">
                <div class="defects-title">常见缺陷</div>
                <div class="defects-body">
                    <div class="defects-block" v-for="(item,i) in normalDefectsList">
                        <div class="defects-item-title-wrap">
                            <div class="defects-item-title">{{(i+1)+'、'+item.name}}</div>
                            <input class="defects-item-check" :checked="deffectsCheckeds[item.id]" type="checkbox" @change="changeCheckDeffects(item.id,$event,1)"/>
                        </div>
                        <div class="defects-image-wrap">
                            <img v-if="item.imageUrls!=null" class="defects-image" :src="item.imageUrls[0]"/>
                            <img v-if="item.imageUrls!=null&&item.imageUrls[1]!=null" class="defects-image" :src="item.imageUrls[1]"/>
                        </div>
                    </div>
                </div>
                <div class="defects-title">其他缺陷</div>
                <div class="defects-body">
                    <div class="defects-block" v-for="(item,i) in otherDefectsList">
                        <div class="defects-item-title-wrap">
                            <div class="defects-item-title">{{(i+1)+'、'+item.name}}</div>
                            <input class="defects-item-check" :checked="deffectsCheckeds[item.id]" type="checkbox" @change="changeCheckDeffects(item.id,$event,2)"/>
                        </div>
                        <div class="defects-image-wrap">
                            <img v-if="item.imageUrls!=null" class="defects-image" :src="item.imageUrls[0]" />
                            <img v-if="tem.imageUrls!=null&&item.imageUrls[1]!=null" class="defects-image" :src="item.imageUrls[1]" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<style scoped>
    .task-editor-wrapper {
        margin: 1rem;
        margin-bottom: 1rem;
        height: calc(100% - 2rem);
        width: calc(100% - 2rem);
        background: #fff;
        display: grid;
        grid-template-columns: 15rem 1fr;
        grid-column-gap: 1rem;
        box-sizing: border-box;
        color: rgb(117,117,117);
    }
    .task-editor-steps-wrapper {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        padding: 0 0 2rem 0;
      
    }
    .task-back {
        height:6rem;
        width:100%;
        box-sizing:border-box;
        padding:1rem 1rem 2rem 1rem;
        display:flex;
        align-items:center;
        justify-content:start;
        cursor:pointer;
    }
    .task-editor-panel {
        height: 100%;
        overflow: hidden;
    }
    .task-step-opts {
        height: 10rem;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .setting-info {
        height:100%;
        width:100%;
        box-sizing:border-box;
        overflow:hidden;
        padding:2rem 0;
    }
    .base-setting {
        display: grid;
        grid-template-rows:3rem 3rem 3rem 3rem 3rem 3rem 3rem calc(100% - 9rem);
        align-items:center;
        padding:0 0.5rem;
    }
    .course-selector {
        display: flex;
        flex-wrap: wrap;
        gap: 2rem;
        height:100%;
    }
    .course-selector-item {
        height:15rem;
        width:15rem;
        color:#fff;
        box-shadow:rgba(0,0,0,0.3) 0px 0px 3px;
        border-radius:3px;
        justify-content:space-between;
        flex-flow:column;
        overflow:hidden;
        display:flex;
        background-repeat:no-repeat;
        background-size:100% auto;
        background-position:center;

    }
    .course-title {
      /*  height: 2rem;*/
        width:100%;
        background: var(--el-color-primary);
        color:#fff;
        display:flex;
        align-items:center;
        box-sizing:border-box;
        padding:0 0.5rem;
        justify-content:center;
    }
    .checkCourse {
        height:2rem;
        width:2rem;
        border-radius:0;
        align-self:end;
        margin:1rem 1rem 0 0;
    }
    .knowledge-setting {
        overflow-y: auto;
        padding: 2rem 2rem 2rem 0;
    }
    .defects-setting {
        padding:2rem 2rem 2rem 0;
        display:grid;
        height:100%;
        width:100%;
        grid-template-rows:3rem 1fr 3rem 1fr;
        align-items:center;
    }
    .defects-title {
        font-weight: bold;
        background: #F5F7FA;
        color: #1D2129;
        height:3rem;
        line-height:3rem;
        font-size:1.2rem;
        padding:0 1rem;
    }
    .defects-body {
        display: flex;
        flex-flow: wrap;
        overflow: hidden;
        overflow-y: auto;
        grid-gap: 2rem;
        height:100%;
        width:100%;
        box-sizing:border-box;
        padding:2rem 0;
    }
    .defects-block {
        width: 18rem;
        height: 12rem;
        box-shadow: rgba(0,0,0,0.1) 0px 0px 2px;
        border: 1px solid #E5E6EB;
        border-radius:3px;
        display:grid;
        grid-template-rows:3rem 1fr;
    }
    .defects-item-title-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 1rem;
        border-bottom: 1px solid #E5E6EB;
    }
    .defects-item-title {
        font-weight:bold;
        font-size:1.1rem;
    }
    .defects-item-check {
        height:1.5rem;
        width:1.5rem;
    }
    .defects-image-wrap {
        padding:1rem;
        display:grid;
        grid-template-columns:1fr 1fr;
        grid-gap:1rem;
    }
    .defects-image {
        background:#ccc;
        height:100%;
        width:100%;
        overflow:hidden;
    }
</style>