<script setup lang="ts">
// import { format } from 'date-fns/format';
// import { format as myFormat } from 'date-fns/format';
// import { format } from 'date-fns';
import { format } from "date-fns";

import CpmdHeader from '@/components/CpmdHeader.vue';

import { onMounted, onUnmounted, ref } from 'vue'
import { Check } from '@element-plus/icons-vue'
import { number } from 'echarts';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { getScaleApi, queryScaleDetailApi, saveScaleApi } from '@/api/plan';
import { userInfoStore } from '@/stores'
//调用子组件的ref
// 加一个锁表示不能重复点击
const isLock = ref<boolean>(false)
import { isHaveManage } from '@/utils/test'
import { userPlanApi, userPlanDetailApi } from '@/api/home';
import { id } from 'element-plus/es/locales.mjs';
const userInfo = userInfoStore()
const router = useRouter()
const route = useRoute()
//持久化设置 菜单状态
// import { menuStatusStore } from '@/stores'
// const menuStatus = menuStatusStore();
// menuStatus.saveActiveIndex('3')

//当前量表是否已经提交
const isCompleted = ref<boolean>(false)

const planObj = ref<any>({})

const flag = ref<string>('')
const flagName = ref<string>('')
const planId = ref<string>('')
const planName = ref<string>('')
const startTime = ref<string>('')
const num = ref<string>('')
const isComplate = ref<string>('')

//测试全部数字
const planAllNum = ref<number>(0);
//测试已完成的 
const planIsComplateNum = ref<number>(0);
//测试未完成的
const planNoComplateNum = ref<number>(0);

//获取到的题目数组
const scaleList = ref<any>([
    // {
    //     id: '',
    //     questionNo: '1',
    //     serialNo: '',
    //     content: '我发现我自己被一些琐碎的事情弄得很不开心',
    //     checkItems: '非常符合；大部分符合；小部分符合；完全不符合',
    //     questionType: '0',
    //     questionParam: '',
    //     weight: '',
    //     score: '',
    //     scoreDirection: '',

    //     flag: '',
    //     isCheck: '',
    //     answerList: [{ name: '' }]

    // }
])
//当前题的对象




//刚进页面时第几题
const topicIndex = ref<number>(1)

//存储--方法的
//有三个储存数组分别储存

//抑郁自评量表
//抑郁自评量表flag是"20210617020516"
const listDepressed = ref<any>([])
//知觉压力问卷
//知觉压力量表flag是"20210913093250"
const listStress = ref<any>([])
//焦虑自评量表
//焦虑自评量表flag是"20210617000853"
const listAnxiety = ref<any>([])


//下一题的方法
const nextTopic = () => {
    //当前选项的flag //是多少题
    //判断当前索引下的数组中是否有isCheck为空
    //先判断这个是不是
    if (scaleList.value[topicIndex.value - 1].isCheck == '') {
        ElMessage({
            message: '请选择当前题目',
            type: "warning",
        })
        return
    }
    //已经选择的话---需要拿到当前对象---判断flag是另外三个的flag吗
    //如果是--则判断是否在数组里边--如果不在则存储
    //将抑郁自评量表的数据存储进数组
    if (scaleList.value[topicIndex.value - 1].flag == '20210617020516' && !listDepressed.value.includes(scaleList.value[topicIndex.value - 1].id)) {
        listDepressed.value.push(scaleList.value[topicIndex.value - 1].id)
        //判断抑郁压力数组的长度是20 调用保存接口
        //循环到数组 当前中所有flag 等于抑郁自评量表的数组--然后传输给保存方法
        //判断此数组长度是多少
        if (listDepressed.value.length == 20) {
            let list = []
            for (let i = 0; i < scaleList.value.length; i++) {
                if (scaleList.value[i].flag == '20210617020516') {
                    list.push(scaleList.value[i])
                }
            }
            let listTm = JSON.parse(JSON.stringify(list))
            subScaleData(listTm, "20210617020516")
        }


    }
    //将知觉压力问卷的数据存储进数组

    if (scaleList.value[topicIndex.value - 1].flag == '20210913093250' && !listStress.value.includes(scaleList.value[topicIndex.value - 1].id)) {
        listStress.value.push(scaleList.value[topicIndex.value - 1].id)
        //调用知觉压力数据保存接口
        //如果长度达到指定数目
        if (listStress.value.length == 30) {
            let list = []
            for (let i = 0; i < scaleList.value.length; i++) {
                if (scaleList.value[i].flag == '20210913093250') {
                    list.push(scaleList.value[i])
                }
            }
            let listTm = JSON.parse(JSON.stringify(list))

            subScaleData(listTm, "20210913093250")
        }

    }
    //将焦虑自评量的数据存储进数组
    if (scaleList.value[topicIndex.value - 1].flag == '20210617000853' && !listAnxiety.value.includes(scaleList.value[topicIndex.value - 1].id)) {
        listAnxiety.value.push(scaleList.value[topicIndex.value - 1].id)
        //调用焦虑
        if (listAnxiety.value.length == 20) {
            let list = []
            for (let i = 0; i < scaleList.value.length; i++) {
                if (scaleList.value[i].flag == '20210617000853') {
                    list.push(scaleList.value[i])
                }
            }
            let listTm = JSON.parse(JSON.stringify(list))
            subScaleData(listTm, "20210617000853")
        }

    }

    //判断当前是不是最后一题
    //如果是最后一题就不++了
    if (topicIndex.value == scaleList.value.length) {
        // 最后一题就进行提交了
        //判断不是这三个的话
        if (scaleList.value[topicIndex.value - 1].flag != '20210617020516' && scaleList.value[topicIndex.value - 1].flag != '20210913093250' && scaleList.value[topicIndex.value - 1].flag != '20210617000853') {
            let listTm = JSON.parse(JSON.stringify(scaleList.value))
            subScaleData(listTm, flag.value)
        }
        // subScaleData(listTm, "20210617000853")
        return
    }
    topicIndex.value++

}
//将选择的传输给方法---自带flag
const subScaleData = async (data: any, flag: string) => {
    if (isLock.value) {
        return
    }
    isLock.value = true
    // if (scaleList.value[topicIndex.value - 1].isCheck == '') {
    //     ElMessage({
    //         message: '请选择当前题目',
    //         type: "warning",
    //     })
    //     return
    // }
    //开始调用提交数据的方法

    // testRecord: JSON.stringify(productData()),

    //开始处理数据
    // productData()
    let params = {
        beginTime: startTime.value,
        orgName: userInfo.userInfo.orgName,
        orgNo: userInfo.userInfo.orgNo,
        planId: planId.value,
        planName: planName.value,
        taskFlag: flag,
        taskName: flagName.value,
        testRecord: JSON.stringify(productData(data)),
        type: '0',
        userName: userInfo.userInfo.userName,
        userNo: userInfo.userInfo.userNo,
    }
    const res = await saveScaleApi(params)

    //1.先判断是否需要做附加题---根据查询出来列表  --不显示但是必做的---且状态含有未完成，
    //2.接下来查看需要看总共几个需要做的附加题---将未完成的题目---合并到一块---到时候
    //3.判断做完的有且有多少个题目-----未做完的量表有多少个题目    


    isLock.value = false
    ElMessage({
        message: '提交完成',
        type: "success",
    })
    //判断当前 flag 是可选的三个吗
    //如果是的话---
    if (flag == '20210617020516' || flag == '20210913093250' || flag == '20210617000853') {
        //判断是否是做完了
        if (topicIndex.value == scaleList.value.length) {
            //这时是全部的都做完了
            //做完后目前先跳转到测试计划页面
            router.push({ name: 'plan' })
        }
    }
    if (flag == '20210617140713') {

        queryNeedScale()
        //如果是排除是其他两个则直接返回
    } else if (flag != '20210617020516' && flag != '20210913093250' && flag != '20210617000853') {
        //此时做完需要跳转到计划页面
        router.push({ name: 'plan' })
    }





    // isCompleted.value = true
    //跳转到缓冲中间件
    // setTimeout(() => {
    //     isLock.value = false;
    //     router.push({
    //         name: 'scaleMid', params: {
    //             planId: planId.value,
    //             planName: planName.value,
    //             flag: flag.value,
    //             flagName: flagName.value,
    //             // num: num.value
    //         }
    //     })
    // }, 1500)
}
//根据计划ID查询问题
const queryNeedScale = async () => {
    //
    //查询需要测试的计划
    //如果在就是登录了
    if (userInfo.token) {
        let userNo = ''
        //登录的话
        //判断当前是否有后台管理

        userNo = userInfo.userInfo.userNo

        //调用根据用户查询计划的API
        let res: any = await userPlanApi(userNo)
        //

        for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].id = planId.value) {
                planObj.value = res.data[i]
            }

        }
        //将list赋值进去
        planObj.value.list = [];
        let params = {
            planId: planObj.value.id,
            userNo: userInfo.userInfo.userNo
        }
        //调用详细的API
        let temp: any = await userPlanDetailApi(params)
        planObj.value.list = temp.data
        console.log('planObj')
        console.log(planObj.value)
        //判断是否需要
        //判断量表中有几个是必须测试的且不显示的
        let list = []
        for (let i = 0; i < planObj.value.list.length; i++) {
            //先判断类型--在判断必做且不显示的---将这个写存储在数组
            if (planObj.value.list[i].contentType == '0' && planObj.value.list[i].isAvailable == '1' && planObj.value.list[i].isDisplayed == '0') {
                //修改
                //
                list.push(planObj.value.list[i])
            }
        }
        //将对象的list字段设置新的需要测试的
        planObj.value.list = list;

        //以此查询出来需要需要做的但是未完成的
        //必做的全部计算出来全部需要做的题
        let listNeedAll = []
        let listIsComplate = []
        let listNoComplate = []
        for (let i = 0; i < planObj.value.list.length; i++) {
            //查询出全部的问题
            //根据flag查询出来的题
            //let res: any = await queryScaleDetailApi(planObj.value.list[i].flag)
            if (planObj.value.list[i].isCompleted == '1') {
                let res: any = await getScaleApi(planObj.value.list[i].flag)
                listIsComplate.push(...res.data)
                listNeedAll.push(...res.data)
            }
            //计算未完成数目
            if (planObj.value.list[i].isCompleted == '0') {
                let res: any = await getScaleApi(planObj.value.list[i].flag)
                listNoComplate.push(...res.data)
                listNeedAll.push(...res.data)
            }
            //查询出来后将值赋值给另一数组
            //总共需要做的题的数目
        }
        //测试全部数字
        planAllNum.value = listNeedAll.length;
        //测试已完成
        planIsComplateNum.value = listIsComplate.length;
        //测试未完成
        planNoComplateNum.value = listNoComplate.length;
        console.log('总长度')
        console.log(listNeedAll.length)
        console.log('已经测过的长度')
        console.log(listIsComplate.length)
        console.log('未测过的长度')
        console.log(listNoComplate.length)
        //判断 如果总长度是0的话--需要跳转到测试计划页
        if (planAllNum.value == 0) {
            //跳转计划页面
            router.push({ name: 'plan' })
        } else {
            //如果长度不是0的话--需要修改文本
            //设置标志为2
            isComplate.value = '2'
        }
        //这时应该清空一下index 
        topicIndex.value = 1
        scaleList.value = listNoComplate
        for (let i = 0; i < scaleList.value.length; i++) {
            scaleList.value[i].isCheck = ''
        }
        console.log(scaleList.value)

    }


}
//根据flag查询量表详情


// console.log(res)
// scaleName.value = res.data.name;
// detail.value = res.data.description;
// theory.value = res.data.theory;
// //参考文献
// console.log(res.data.reference)
// reference.value = res.data.reference.split('//');
// console.log(reference.value)


const productData = (data: any) => {
    //循环列表
    //查看isCheck字段
    //根据字段拿出答案
    //将答案放入数组
    let testRecord = []
    for (let i = 0; i < data.length; i++) {
        for (let k = 0; k < data[i].answerList.length; k++) {
            if (data[i].isCheck === data[i].answerList[k].name) {
                //r
                testRecord.push(data[i].answerList[k])
            }
        }
    }

    return testRecord

}
//上一题的方法
const lastTopic = () => {
    if (topicIndex.value == 1) {
        ElMessage({
            message: '已经是第一题了',
            type: "warning",
        })
        return
    }
    topicIndex.value--
}
//点击选中选项的事件
const radioFun = () => {
    nextTopic()
}




//刚进入页面就将高度设置为页面需要的
onMounted(() => {


    flag.value = route.params.flag as string;
    planId.value = route.params.planId as string
    planName.value = route.params.planName as string
    flagName.value = route.params.flagName as string
    num.value = route.params.num as string
    isComplate.value = route.params.isComplate as string
    //进到界面开始轮询

    // 判断是否SCL90
    if (flag.value == '20210617140713') {
        //如果是的话--判断scl90的状态
        if (isComplate.value == '0') {
            getScaleFun(flag.value)
        } else if (isComplate.value == '2') {
            queryNeedScale();
        }
    } else {
        getScaleFun(flag.value)
    }
    getStartTime()

    //判断是否是完成了
    //如果标志是

})
//获取当前时间
const getStartTime = () => {
    let date = new Date()
    startTime.value = format(date, "yyyy-MM-dd HH:mm:ss");
    console.log(startTime.value)
}

//根据flag 获取当前的题目
const getScaleFun = async (val: string) => {
    scaleList.value = []
    let res: any = await getScaleApi(val)
    console.log(res.data)
    scaleList.value = res.data
    for (let i = 0; i < scaleList.value.length; i++) {
        scaleList.value[i].isCheck = ''
    }

}
//界面销毁函数


//轮旋切换页面的方法



//退出页面销毁 方法
onUnmounted(() => {

})




</script>

<template>
    <div class="home_header_out">
        <div class=" home_header_inner">
            <CpmdHeader />
            <div class="report_top">
                <div class="report_jt">
                    <span v-if="!(flag == '20210617140713' && isComplate == '2')">{{ flagName }}</span>
                    <span v-if="flag == '20210617140713' && isComplate == '2'"> 症状自评量表（附加题）</span>
                    <span v-show="!isCompleted" class="des">请根据您的表现回答下列问题，每道题请选择最符合您的情况的选项。</span>
                </div>
                <img v-show="!isCompleted" class="xlts_img" src="../assets/scale/scale.png" />
            </div>

        </div>
        <div class="kply">
            <div class="kply_inner" :style="{ border: isCompleted ? '8px solid #ffffff' : '8px solid #B2F2D2' }">
                <div style="padding :10px 100px">
                    <el-progress v-if="!(flag == '20210617140713' && isComplate == '2')" :text-inside="true"
                        :stroke-width="20" :percentage="(topicIndex / scaleList.length) * 100" color="#48D68E">
                        <span style="color:#000000">{{ topicIndex }}/{{ scaleList.length }}</span>
                    </el-progress>
                    <el-progress v-if="flag == '20210617140713' && isComplate == '2'" :text-inside="true"
                        :stroke-width="20" :percentage="((topicIndex + planIsComplateNum) / planAllNum) * 100"
                        color="#48D68E">
                        <span style="color:#000000">{{ topicIndex + planIsComplateNum }}/{{ planAllNum }}</span>
                    </el-progress>
                    <div v-if="scaleList.length > 0">
                        <div class="scale_title" v-if="!(flag == '20210617140713' && isComplate == '2')">{{ topicIndex
                            }}：{{ scaleList[topicIndex - 1].content }}</div>
                        <div class="scale_title" v-if="flag == '20210617140713' && isComplate == '2'">{{ topicIndex +
                            planIsComplateNum }}：{{ scaleList[topicIndex - 1].content }}</div>
                        <el-radio-group v-model="scaleList[topicIndex - 1].isCheck" class="scale_radio_group">
                            <el-radio-button
                                v-for="item in scaleList[topicIndex - 1].checkItems.split('；').sort(() => { return Math.random() - 0.5 })  "
                                @change="radioFun" :label="item" :value="item" />
                        </el-radio-group>
                        <div class="scale_button">
                            <el-row>
                                <el-col :span="12" class="scale_button_inner">
                                    <div v-show="topicIndex > 1" class="scale_button_self" @click="lastTopic">上一题
                                    </div>
                                </el-col>
                                <el-col :span="12" class="scale_button_inner">
                                    <div v-show="topicIndex < scaleList.length" class="scale_button_self"
                                        @click="nextTopic">下一题</div>
                                    <!-- <div v-show="topicIndex == scaleList.length" class="scale_button_self"
                                        @click="subScaleData">提交</div> -->
                                </el-col>
                            </el-row>


                        </div>
                    </div>

                </div>

            </div>

        </div>

    </div>


</template>
<style lang="scss" scoped>
:deep(.el-progress-bar__outer) {
    background-color: #f3f3f3;
    border-radius: 100px;
    height: 6px;
    overflow: hidden;
    position: relative;
    vertical-align: middle;
}

:deep(.el-radio-group) {
    align-items: center;
    display: flex;
    flex-wrap: wrap;
    font-size: 0;
    flex-direction: column;
}

:deep(.el-radio-button) {
    display: inline-block;
    outline: none;
    position: relative;
    width: 80% !important;
}

:deep(.el-radio-button__inner) {
    width: 100%;
    border-radius: 40px !important;
    margin-top: 10px;
    border: 4px solid #B2F2D2;
    border-left: 4px solid #B2F2D2 !important;
    padding: 10px 10px;
    font-size: 14px;
    font-weight: 700;
    text-align: left;

}

:deep(.el-radio-button__inner:hover) {
    width: 100%;
    border-radius: 40px !important;
    margin-top: 10px;
    border: 4px solid #B2F2D2;
    border-left: 4px solid #B2F2D2 !important;
    padding: 10px 10px;
    font-size: 14px;
    font-weight: 700;
    text-align: left;

    color: #000000;
    background-color: #48D68E;
    color: #ffffff;

}

:deep().el-radio-button__original-radio:checked+.el-radio-button__inner {
    background-color: #48D68E;
    border-color: #B2F2D2;
    box-shadow: 0 0 0 0 var(--el-radio-button-checked-border-color, var(--el-color-primary));
    color: var(--el-radio-button-checked-text-color, var(--el-color-white));
}

.home_header_out {
    // position: relative;
    padding-bottom: 60px;
    width: 100%;
    min-width: 1200px;
    background-image: url('../assets/home/bg_ty.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-color: #FAFAFA; //估计是需要动态

    //获取屏幕宽度home_header_out 这个div的宽度--然后宽度*1000再除1920即为当前div的宽度
    .home_header_inner {
        min-height: 1;
        left: 0;
        right: 0;
        margin: auto;
        // height: 100px;
        width: 1200px;

        .report_top {
            width: 860px;
            margin-left: 170px;
            margin-top: 20px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0px;

            .xlts_img {
                margin-right: 100px;
                width: 100px;
            }

            .report_jt {
                display: flex;
                flex-direction: column;
                font-size: 20px;
                font-weight: 700;
                letter-spacing: 3px;

                .des {
                    color: #888888;
                    // opacity: 0.4;
                    font-size: 15px;
                    letter-spacing: 0px;
                    margin-top: 10px;
                }
            }
        }
    }

    .kply {
        width: 100%;
        margin-top: 10px;
        margin-bottom: 9px;
        // width: 860px;
        // background-color: #FAFAFA;

        .kply_inner {
            // border: 8px solid #B2F2D2;

            min-height: 500px;
            left: 0;
            right: 0;
            margin: auto;
            width: 860px;
            // padding: 20px 20px;
            background-color: #ffffff;
            border-radius: 40px;

            .scale_title {
                margin-top: 20px;
                font-size: 18px;
                letter-spacing: 2px;
                line-height: 20px;

                .scale_radio_group {
                    display: flex;
                    flex-direction: column;
                }
            }

            .scale_button {
                margin-top: 60px;
                margin-bottom: 20px;

                .scale_button_inner {
                    text-align: center;
                    display: flex;
                    justify-content: center;

                    .scale_button_self {

                        border-radius: 12px;
                        border: 3px solid #48D68E;
                        color: #ffffff;
                        background-color: #000000;
                        margin-right: 20px;
                        padding: 10px 40px;
                        cursor: pointer;
                        display: flex;
                        align-items: center;
                        font-size: 14px;
                    }
                }
            }

            .finish_calss {
                display: flex;
                flex-direction: column;

                .finish_img {
                    margin-top: 60px;
                    display: flex;
                    flex-direction: column;
                    align-items: center;

                    .finish_font {
                        margin-top: 40px;
                        font-size: 30px;
                        margin-bottom: 100px;
                    }
                }
            }
        }
    }


}



.home_mid {
    // background-color: blanchedalmond;
    width: 1200px;
    left: 0;
    right: 0;
    margin: auto;
    margin-top: 40px;
    // position: relative;




    .kepu_title {
        text-align: center;

        font-size: 50px;
        color: #111111;
        line-height: 95px;

        // width: 100%;
        // left: 0;
        // right: 0;
        // margin: auto
    }

    .kepu_title_sub {
        margin-top: 30px;
        text-align: center;
        font-size: 28px;
        color: #48D68E;
        line-height: 26px;
    }

    .man1_group {
        margin-top: 60px;
        height: 100%;
        display: flex;

        .man1 {
            position: relative;
            width: 327px;
            // height: 100%;

            // height: 100%
            .man1_img {
                position: absolute;
                bottom: 0;
                /* bottom: 0px; */
                /* height: auto; */
                width: 100%;
                left: 100px
            }

        }

        .des {
            border: #48D68E solid 5px;
            border-radius: 40px;
            padding: 20px;
            letter-spacing: 6px;
            flex: 1;

            .des_inner {
                border: 1px dashed #48D68E;
                border-radius: 40px;
                padding-bottom: 40px;
                padding-top: 30px;
                padding-left: 100px;
                padding-right: 20px;
                letter-spacing: 6px;
                font-weight: normal;
                font-size: 24px;
                color: #333333;
                line-height: 40px;
            }
        }
    }

    .man2_group {
        margin-top: 60px;
        height: 100%;
        display: flex;

        .man2 {
            position: relative;
            width: 327px;
            // height: 100%;

            // height: 100%
            .man2_img {
                position: absolute;
                bottom: 0;
                /* bottom: 0px; */
                /* height: auto; */
                width: 100%;
                left: -100px
            }

        }

        .des2 {
            border: #48D68E solid 5px;
            border-radius: 40px;
            padding: 20px;
            letter-spacing: 6px;
            flex: 1;

            .des2_inner {
                border: 1px dashed #48D68E;
                border-radius: 40px;
                padding-bottom: 40px;
                padding-top: 30px;
                padding-left: 20px;
                padding-right: 100px;
                letter-spacing: 6px;
                font-weight: normal;
                font-size: 24px;
                color: #333333;
                line-height: 40px;
            }
        }
    }

    .get_more {
        text-align: center;

        img {
            width: 300px;
            margin-top: 60px;
            margin-bottom: 60px;
        }
    }
}

// .home_footer_out {
//     width: 100%;
//     background-color: #000000;
// }</style>
