<template>
    <div class="batch-computed-save-wrap">
        <el-table 
            :data="list" 
            border 
            height="500px"
        >
            <el-table-column label="指标全称" align="center" prop="EdbName"/>
            <el-table-column label="生成指标名称" align="center">
                <template slot-scope="scope">
                    <el-input :disabled="operationForm.view" v-model="scope.row.name" placeholder="请填写指标名称" style="width:100%"/>
                </template>
            </el-table-column>
            <el-table-column label="单位" align="center" width="200px">
                <template slot-scope="scope">
                    <selectUnit :disabled="operationForm.view||[6].includes(sourceTypeVal)" v-model="scope.row.unit"/>
                </template>
            </el-table-column>
            <el-table-column label="频度" align="center" width="200px">
                <template slot-scope="scope">
                    <el-select
						v-model="scope.row.frequency"
						placeholder="请选择频率"
                        @change="handleFrequencyChange(scope)"
                        :disabled="operationForm.view||[5,6,14,61,63].includes(sourceTypeVal)"
					>
						<el-option
							v-for="item in frequencyArr"
							:key="item"
							:label="item"
							:value="item"
						>
						</el-option>
					</el-select>
                </template>
            </el-table-column>
            <el-table-column align="center" width="300px">
                <template slot="header" slot-scope="scope">
                    <span style="margin-right:40px;display:inline-block">目录</span>
                    <el-radio-group :disabled="operationForm.view" v-model="classifyType" @change="handleClassifyTypeChange">
                        <el-radio :label="0">分目录</el-radio>
                        <el-radio :label="1">同目录</el-radio>
                    </el-radio-group>
                </template>
                <template slot-scope="{row,$index}">
                    <el-cascader
						v-model="row.classify"
						:options="classifyOpt"
						:props="levelProps"
						placeholder="请选择指标目录"
                        :disabled="(classifyType===1&&$index>0)||operationForm.view"
                        @change="handleClassifyChange(row,$index)"
					/>
                </template>
            </el-table-column>
        </el-table>
        <div style="text-align:center;margin:60px 0 40px 0" v-if="!operationForm.view">
            <el-button type="primary" plain @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading">{{loading ? '批量计算中...' : '批量计算'}}</el-button>
        </div>
    </div>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import {generateSeriesArray} from './util'
const tag_arr = generateSeriesArray();
export default {
    props:{
        computedType:null,
        subComputedType:null,
        selectList:null,
        formData:null,
        select_target:null,
        operationForm:null,
        isEdit:false
    },
    computed: {
        sourceTypeVal(){
            if(!this.computedType) return 0
            if(this.subComputedType) return this.subComputedType
            return ['withNum','withEDB'].includes(this.computedType)?4:this.computedType
        }
    },
    data() {
        return {
            frequencyArr: ['日度', '周度','旬度','月度', '季度', '年度'],

            list:[],

            classifyType:0,
            classifyOpt: [],
			levelProps: {
				label: 'ClassifyName',
				value: 'ClassifyId',
				children: 'Children',
				checkStrictly: true,
                emitPath:false
			},

            loading:false,

            computedArr:[],//多指标求和\平均的指标数组
        }
    },
    mounted() {
        this.initData()
        this.getClassifyOpt()
    },
    methods: {
        // 初始化数据
        initData(){
            let arr=[]

            // 如果是多指标求和\平均
            if(this.computedType==='multipleEDB'){
                this.computedArr=this.selectList
                // 如果是编辑时
                if(this.isEdit){
                    this.list=[{
                        EdbName:this.operationForm.EdbInfoDetail.EdbName,
                        EdbInfoId:this.operationForm.EdbInfoDetail.EdbInfoId,
                        name:this.operationForm.EdbInfoDetail.EdbName,
                        unit:this.operationForm.EdbInfoDetail.Unit,
                        frequency:this.operationForm.EdbInfoDetail.Frequency,
                        classify:this.operationForm.EdbInfoDetail.ClassifyId
                    }]
                    return
                }
                arr=[{...this.selectList[0]}]
            }else{
                arr=this.selectList
            }
            
            
            arr.forEach(item=>{
                this.setDefaultVal(item)
            })
            
        },
        // 设置默认值
        setDefaultVal(item){
            const obj={
                EdbName:item.EdbName,
                EdbInfoId:item.EdbInfoId,
                name:'',
                unit:'',
                frequency:'',
                classify:''
            }
            const tMap=new Map([
				['日度','D'],
				['周度','W'],
				['旬度','T'],
				['月度','M'],
				['季度','Q'],
				['年度','Y'],
			])
			const name_map = {
                4:item.EdbName,
				5: `${item.EdbName}转月值`,
				8: `${item.EdbName}/${this.formData.nNum}${tMap.get(item.Frequency)}MA`,
				14: `${item.EdbName}/日频`,
				6: `${item.EdbName}同比`,
				7: `${item.EdbName}同差`,
				12: `${item.EdbName}${this.formData.nNum}${item.Frequency.slice(0,1)}环比`,
				13: `${item.EdbName}${this.formData.nNum}${item.Frequency.slice(0,1)}环差`,
				35: `${item.EdbName}超季节性/${this.formData.nNum}年${this.formData.calendarType==='公历'?'':'/'+this.formData.calendarType}`,
				52: `${item.EdbName}年化值`,
				51: `${item.EdbName}/${this.formData.frequency.substr(0,1)}频`,
				61:  `${item.EdbName}转季值`,
				62:  `${item.EdbName}累计值/${this.formData.frequency}`,
				63:  `${item.EdbName}年初至今累计值`,
                72:`${item.EdbName}指数修匀`,
				75: `${item.EdbName}日均值`,
                81:item.EdbName,
                82:item.EdbName,
			}
			
			let frequerncyMap = {
				14: '日度',
				61: '季度',
                62:this.formData.frequency,
                51:this.formData.frequency,
			}

            obj.name=name_map[this.sourceTypeVal] || ''
            obj.frequency=frequerncyMap[this.sourceTypeVal]|| item.Frequency
            obj.classify=item.ClassifyId||''

            if([5,8,14,7,35,75].includes(this.sourceTypeVal)){
                obj.unit=item.Unit
            }else if([4].includes(this.sourceTypeVal)){
                obj.unit=''
            }else{
                obj.unit='无'
            }
            

            this.list.push(obj)
        },
        // 频度变化 修改指标名
		handleFrequencyChange(e){
			if(!this.sourceTypeVal||![51,62].includes(this.sourceTypeVal)) return;
            const obj=this.list[e.$index]
			const name_map = {
				51: `${obj.EdbName}/${obj.frequency.substr(0,1)}频`,
				62:  `${obj.EdbName}累计值/${obj.frequency}`,
			}
			this.list[e.$index].name=name_map[this.sourceTypeVal]
		},

        // 同目录修改
        handleClassifyChange(e,index){
            if(this.classifyType===1){
                // 修改所有的指标的目录为第一个
                this.list.forEach(item=>{
                    item.classify=e.classify
                })
            }
        },

        handleClassifyTypeChange(){
            this.handleClassifyChange(this.list[0])
        },

        // 提交计算
        async handleSubmit(){
            const edbList=this.list.map((item,index)=>{
                return{
                    CalculateId:tag_arr[index],
                    ClassifyId:item.classify,
                    EdbName:item.name,
                    Frequency:item.frequency,
                    Unit:item.unit,
                    FromEdbInfoId:this.isEdit?0:item.EdbInfoId,
                    EdbInfoId:this.isEdit?item.EdbInfoId:0
                }
            })
            const valueMap = {
				51: 'valueType',
                72:'alphaValue'
			}
            const params={
                EdbList:edbList,
                Formula:valueMap[this.sourceTypeVal] ? String(this.formData[valueMap[this.sourceTypeVal]]) : String(this.formData.nNum),
                Source:this.sourceTypeVal,
                CalculateFormula:this.sourceTypeVal===4? JSON.stringify([{f:this.formData.formula,d:''}]) : this.formData.formula,
                EdbInfoIdArr:this.select_target?[{EdbInfoId:this.select_target,FromTag:'B'}]:[],
                MoveType:0,
                MoveFrequency:'',
                Calendar:this.formData.calendarType,
                EmptyType: this.formData.nullValueWay,
				MaxEmptyType: this.formData.maxNullWay,
                Extra:JSON.stringify({
                    LastValType:this.formData.newValue,
                    DateTag:this.formData.timeSeriesVal
                })
            }
            // 处理多指标求和\平均 情况的数据
            if(this.computedType==='multipleEDB'){
                const arr=this.computedArr.map((item,index)=>{
                    return{
                        EdbInfoId:item.EdbInfoId,
                        FromTag:tag_arr[index]
                    }
                })
                params.EdbInfoIdArr=arr
            }
            console.log(params);

            let isEnough = params.EdbList.every(item => item.EdbName&&item.Unit&&item.ClassifyId&&item.Frequency)
            if(!isEnough) return this.$message.warning('请填写完整信息');

            this.loading=true
            const tipMsg=setTimeout(() => {
                this.$message.success('请等待计算完成,该过程可能持续2-3分钟')
            }, 500);
            const res=this.isEdit?await dataBaseInterface.batchCalculateTargetEdit(params) : await dataBaseInterface.batchCalculateTargetAdd(params)
            this.loading=false
            clearTimeout(tipMsg)
            
            if(res.Ret !== 200) return

            const { Fail,Success } = res.Data;

            if(Fail.length) {
                let message = '';
                Fail.forEach(item => {
                    message+=`${item.CalculateId}:${item.Msg}</br>`
                })

                this.$message({
                    dangerouslyUseHTMLString: true,
                    message,
                    type: 'error'
                })
                this.dealFailHandle(Fail)
            }else {
                this.$message.success('添加成功');
                // this.init();
                this.$emit('addCallBack','add',{ code:Success[0].UniqueCode,id:Success[0].EdbInfoId,classifyId:Success[0].ClassifyId});
            }

        },

        // 处理批量添加失败的指标
        dealFailHandle(data){
            let temarr=[]
            data.forEach(item=>{
                const index=tag_arr.indexOf(item.CalculateId)
                temarr.push(this.list[index])
            })
            this.list=temarr
        },


        handleClose(){
            this.$emit('close')
        },
        filterNodes(arr) {
			arr.length &&
				arr.forEach((item) => {
					item.Children.length && this.filterNodes(item.Children);
					if (!item.Children.length) {
						delete item.Children;
					}
				});
		},
        // 获取指标分类
        async getClassifyOpt(){
            const res=await dataBaseInterface.menuListV3()
            if (res.Ret !== 200) return
            this.filterNodes(res.Data.AllNodes||[]);
			this.classifyOpt = res.Data.AllNodes || [];
        },
    },
}
</script>

<style lang="scss">
.batch-computed-save-wrap{
    .el-input{
        input{
            border: none;
            text-align: center;
        }
    }
    .el-table tr{
        background-color: #fff !important;
        &:hover>td{
            background-color: transparent !important; /* 或者其他想要的颜色值 */
        }
    }
}
</style>