<template>
    <div class="assess-model">
        <div> <LHeader :text="title"></LHeader></div>
        <div class="assess-model-container">
            <div class="assess-model-group"  v-for="typeItem in types"  :key="typeItem.factorName">
                <div class="assess-model-select-title"><van-icon name="label" /><span>{{typeItem.factorName}}</span></div>
                <template v-if="typeItem.factorList.length">
                    <van-collapse v-model="activeNames" accordion>
                        <van-collapse-item
                            :title="item.factorSubName"
                            :name="typeItem.factorName+'_'+item.factorSubName"
                            v-for="item in typeItem.factorList"  
                            :key="typeItem.factorName+'_'+item.factorSubName"
                        >
                        <template #title>
                            <div class="van-cell__title">{{ item.factorSubName }}</div>
                            <div class="van-cell__tip" v-if="item.remark">备注：{{ item.remark }}</div>
                        </template>
                        <van-radio-group v-model="item.value">
                                <van-radio v-for="(child) in item.factorItemsList" :key="item.name+child.indicatorItem" :name="child.id">{{ child.indicatorItem }}</van-radio>
                        </van-radio-group>
                        <template slot="right-icon">
                                <span :class="{'active-value':item.value!=-1,'right-text':true}">{{getName(item)}}</span>
                                <van-icon name="arrow" class="van-cell__right-icon"/>
                        </template>
                        </van-collapse-item>
                    </van-collapse>
                </template>
                <template v-else>
                    <div class="empty">
                        <van-icon name="failure"></van-icon>
                        <div>暂无数据</div>
                    </div>
                </template>
                </div>
        </div>
         <footer class="assess-model-footer">
            <van-button  round type="info" @click="save">完成</van-button>
        </footer>
    </div>

</template>

<script>
import LHeader from "@/components/header.vue";
import { getFun, postFun } from "@/service/table";
    export default {
        components:{
            LHeader
        },
        data(){
            return {
                title:'影响因子',
                activeNames:[],
                types:[],
                ids:'',  //人,机 
                assessModel:this.$store.state.assessModel
            }
        },
        mounted(){
            const {ids} = this.$route.query;
            // 如果用户刷新页面,从新存储step1
            const present = localStorage.getItem('presentForm')
           let presentForm =present ?JSON.parse(present):null;
            if(!this.assessModel.step1.length&&ids){
                this.$store.commit('SET_ASSESS_STEP1',ids)
            }
            if(presentForm&&presentForm.evaluationItemIds){   // 用户刷新
                this.$store.commit('SET_ASSESS_STEP2',presentForm.evaluationItemIds);
            }
            this.ids = ids;
            this.getList()

        },
        methods:{
            getName(item){
                const name = item.factorItemsList.find(x=>x.id===item.value)
                // return ?.indicatorItem||''
                return name?name.indicatorItem:''
            },
            // 根据ids获取列表
            getList(){
                getFun('/risk/plan/evaluation/getFactorListByType',{
                    factorNames:this.ids
                }).then(res=>{
                    const types = res.data;
                    // 需要给每一个选项添加 '未涉及'选项
                    types.forEach(x=>{
                        if(x.factorList.length){
                            x.factorList.forEach(val=>{
                                val.factorItemsList = [...val.factorItemsList,{indicatorItem:'未涉及',id:-1}]
                                val.value =-1
                            })
                        }
                    })
                    this.types = res.data;
                      if(this.assessModel.step2.length){
                            this.edit(this.assessModel.step2.split(','))
                        }
                })
            },
            // data为选项的id[]
            edit(datas){
                datas.forEach((data)=>{
                    this.types.forEach(val=>{
                        val.factorList.forEach(factor => {
                                const has = factor.factorItemsList.find(x=>x.id==data);
                                if(has){
                                    factor.value = data;
                                }
                        });
                    })
                })
            },

            // 保存 数据处理和进行下一步操作
            save(){
               let unSelect = [];
                // 只传输修改的
                let types =JSON.parse(JSON.stringify(this.types));
                // types进行深拷贝
               types.forEach(val=>{
                   val.factorList = val.factorList.filter(x=>x.value!==-1);
                   if(!val.factorList.length){
                        unSelect.push(val.factorName)
                   }
                })
               if(unSelect.length){
                   this.$dialog.confirm({
                       message:`${unSelect.join('、')}未选择，是否继续？`
                   }).then(()=>{
                       this.countScroe(types);
                       this.result(types)
                   }).catch(()=>{
                   })
               }else{
                   this.countScroe(types);    
                   this.result(types)
               }
            },
            // 计算分值
            countScroe(types){  //获取处理后的types

                /**
                 * 数据样例:
                 *  [
                 *      {
                 *          factorName: '人',
                 *          factorList: [
                 *              {
                 *                  name:'题目名称'
                 *                  factorItemsList:[ 
                 *                      {
                 *                          value: 1,
                 *                          indicatorScore: 2 （选项分数)
                 *                       },
                 *                   ]
                 *               }
                 *           ]   
                 *      },
                 *
                 *  ]
                 * */ 
                this.average = 0;  //平均分
                this.averageTotal = 0;
                types.forEach(val=>{
                    // 计算 ’人、机‘大类的总值val.total
                    val.total = val.factorList.reduce((total,item)=>{
                        const sum = item.factorItemsList.find(idx=>idx.id===item.value);
                        return total+(sum?sum.indicatorScore:0)
                    },0)
                    // 计算 ’人、机‘大类的平均值val.average
                    val.average = val.factorList.length?val.total/val.factorList.length:0;  

                    // 计算 ’人+机‘ 的平均值总值
                    this.averageTotal+=val.average;
                })
                const len = types.filter(x=>x.total&&x.total!=0);
                // 计算 ’人+机‘的平均值
                this.average = len.length?this.averageTotal/len.length:0;
                this.average = this.average.toFixed(2)
            },

            // 存储数据，跳转页面
            result(types){
                let step2 = []
                types.forEach(val=>{
                    step2 = [...step2,...val.factorList.map(x=>x.value)]
                })
                this.$store.commit('SET_ASSESS_STEP1',this.ids)
                 this.$store.commit('SET_ASSESS_STEP2',step2.join(','))  //需要往后端传递的数据
                 this.$router.push({
                    name: "resultPage",
                    query: {
                        score:  this.average
                    }
                });
            }
        }
    }
</script>

<style lang="less" scoped>
.assess-model{
    background: #fff;
    z-index: 10;
    .assess-model-select-title{
        font-weight: 400;
        font-size: 13px;
        padding:0.1rem 0.3rem;
        background: #f4f4f4;
        font-weight: bold;
        .van-icon{
            margin-right: 0.08rem;
            font-size: 15px;
            transform: translateY(1px);
        }
    }
    .assess-model-container{
        height: calc(100% - 1.5rem);
        overflow: auto;
        .assess-model-group{
        ::v-deep .van-cell{
                .van-cell__title{
                    // font-weight: bold;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                    margin-right: 10px;
                }
                .active-value{
                    color: #1989fa;
                }
                .right-text{
                    display: inline-block;
                    max-width: 3rem;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                }
            }
            .van-cell__right-icon::before{
                transform: rotate(90deg);
            }
            .van-collapse-item__title--expanded .van-cell__right-icon::before{
                transform: rotate(-90deg);
            }
            .van-radio-group{
                .van-radio{
                    margin: 0.2rem 0;
                }
            }
            ::v-deep .van-collapse-item__content{
                padding: 0.2rem 0.6rem;
            }
        }
       
    }
    .assess-model-footer{
        width: 100%;
        height: 1.4rem;
        z-index: 9;
        position: fixed;
        bottom: 0px;
        text-align: center;
        line-height: 1rem;
        .van-button{
            width: 90%;
            margin: 0 auto;
        }
    }
    .empty{
        width: 100%;
        text-align: center;
        font-size: 0.4rem;
        color: #e5e5e5;
        padding-top: 20%;
        .van-icon{
            font-size: 2.2rem;
        }
    }
    .van-cell__tip{
        color: #bfbfbf;
        font-size: 0.2rem;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }
}
</style>