<template>
    <el-dialog
		:visible.sync="isShow"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
		@close="handleClose"
		custom-class="batch-computed-dialog fit-screen-dialog"
		center
		top="2vh"
		v-dialogDrag
        :title="showSave ? $t('EtaBasePage.title_batch_save') : $t('EtaBasePage.title_batch_calc')"
	>
        <div class="batch-computed-wrap" v-if="!showSave">
            <el-form inline :disabled="operationForm.view">
            <div class="type-wrap">
                <div style="margin-right:50px">
                    <span><!-- 计算公式 -->{{$t('EtaBasePage.calculate_formula')}}</span>
                    <el-select :disabled="isEdit" v-model="computedType" @change="handleComputedTypeChange" :placeholder="$t('Edb.please_select')">
                        <el-option 
                            v-for="opt in computedBatchTypes" 
                            :key="opt.type" 
                            :label="opt.name"
                            :value="opt.type"
                        />
                    </el-select>
                </div>
                <div style="flex:1">
                    <!-- 累计值转月/季值 -->
                    <el-form-item v-if="computedType=='toMonthSeason'">
                        <el-radio-group v-model="subComputedType" @change="handleComputedSubTypeChange">
                            <el-radio :label="5">
                                <!-- 转月值 -->
                                {{$t('Edb.CalculatesAll.to_monthly_v2')}}
                            </el-radio>
                            <el-radio :label="61">
                                <!-- 转季值 -->
                                {{$t('Edb.CalculatesAll.to_quarterly_v2')}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <!-- N期移动均值、N期环比值、N期环差值 -->
                    <el-form-item required v-if="[8,12,13].includes(computedType)" :label="$t('EtaBasePage.label_n_val')" style="width:280px">
                        <el-input v-model="formData.nNum" :placeholder="$t('Edb.InputHolderAll.input_n_value')" type="number" style="width:200px"></el-input>
                    </el-form-item>

                    <!-- 超级季节性 -->
                    <template v-if="computedType==35">
                        <el-form-item required :label="$t('EtaBasePage.label_n_val')" style="width:280px">
                            <el-input v-model="formData.nNum" :placeholder="$t('Edb.InputHolderAll.input_n_value')" type="number" style="width:200px"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.label_calendar')"  style="width:180px">
                            <el-select v-model="formData.calendarType" style="width:120px">
                                <el-option :label="$t('Chart.calendar_gre')" value="公历"></el-option>
                                <el-option :label="$t('Chart.calendar_lunar_text')" value="农历"></el-option>
                            </el-select>
                        </el-form-item>
                    </template>

                    <!-- 降频 -->
                    <template v-if="computedType==51">
                        <el-form-item required :label="$t('Edb.Detail.e_fre')" style="width:180px">
                            <el-select v-model="formData.frequency" style="width:120px">
                                <el-option v-for="opt in frequencyArr" :key="opt.value" :label="opt.label" :value="opt.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.label_val_type')"  style="width:200px">
                            <el-select v-model="formData.valueType" style="width:120px">
                                <el-option key="期末值" :label="$t('EtaBasePage.val_type_end')" value="期末值"/>
                                <el-option key="平均值" :label="$t('EtaBasePage.val_type_average')" value="平均值"/>
                            </el-select>
                        </el-form-item>
                    </template>

                    <!-- 累计值 -->
                    <template v-if="computedType=='accumulate'">
                        <el-form-item>
                            <el-radio v-model="subComputedType" :label="62">
                                <!-- 累计值 -->
                                {{$t('Edb.CalculatesAll.cumulate')}}
                            </el-radio>
                        </el-form-item>
                        <el-form-item required :label="$t('Edb.Detail.e_fre')" style="width:180px" v-if="subComputedType==62">
                            <el-select v-model="formData.frequency" style="width:120px">
                                <el-option v-for="opt in frequencyArr" :key="opt.value" :label="opt.label" :value="opt.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('Edb.CalculatesAll.latest_processing')"  style="width:210px" v-if="subComputedType==62">
                            <el-select v-model="formData.newValue" style="width:120px">
                                <el-option :label="$t('EtaBasePage.default_select_text')" :value="0"/>
                                <el-option :label="$t('EtaBasePage.mean_imputation_select_text')" :value="1"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-radio v-model="subComputedType" :label="63">
                                <!-- /* '年初至今累计值' */ -->
                                {{$t('Edb.CalculatesAll.cumulate_oneyear')}}
                            </el-radio>
                        </el-form-item>
                    </template>

                    <!-- 指数修匀 -->
                    <template v-if="computedType==72">
                        <el-form-item required :label="$t('EtaBasePage.alpha_value_lable')" style="width:220px">
                            <el-input v-model.trim="formData.alphaValue" style="width:140px" :placeholder="$t('Edb.InputHolderAll.input_alpha_val')"></el-input>
                        </el-form-item>
                        </template>

                        <!-- 与常数计算 -->
                        <template v-if="computedType=='withNum'">
                        <el-form-item required :label="$t('EtaBasePage.formula_lable')">
                            <el-input v-model="formData.formula" :placeholder="$t('EtaBasePage.input_formula_msg')" clearable style="width: 200px"/>
                            <span>
                                <!-- 公式示例：A+100，或A*2 -->
                                {{$t('EtaBasePage.formula_example_text')}}
                            </span>
                        </el-form-item>
                    </template>

                    <!-- 与单指标计算 -->
                    <template v-if="computedType=='withEDB'">
                        <el-form-item required :label="$t('EtaBasePage.metric_label_b')">
                            <el-select
                                v-model="select_target"
                                v-loadMore="searchLoad"
                                :filterable="!select_target"
                                clearable
                                :placeholder="$t('Edb.InputHolderAll.input_name')"
                                style="width: 250px"
                                remote
                                :remote-method="getTarget"
                                @click.native="inputFocusHandle"
                                @change="chooseTarget"
                                @blur="search_have_more = false"
                            >
                                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                                <el-option
                                    v-for="item in searchOptions"
                                    :key="item.EdbInfoId"
                                    :label="$parent.currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
                                    :value="item.EdbInfoId"
                                    :disabled="!item.HaveOperaAuth"
                                >
                                    <div>
                                        <img 
                                            :src="$icons.lock_ico2" 
                                            width="18" 
                                            height="18" 
                                            style="vertical-align:middle" 
                                            v-if="!item.HaveOperaAuth"
                                        />
                                        {{$parent.currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName}}
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item required :label="$t('EtaBasePage.formula_lable')">
                            <el-input v-model="formData.formula" :placeholder="$t('EtaBasePage.input_formula_msg')" clearable style="width: 200px"/>
                            <span>
                                <!-- 公式示例：A+B，或A/B，A/(A+B) -->
                            {{$t('EtaBasePage.formula_example_text_a_b')}}
                            </span>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.create_edb_time_index')">
                            <el-cascader
                                v-model="formData.timeSeriesVal"
                                style="width:180px"
                                :options="timeSeriesOpt"
                                :props="{emitPath:false}"
                                :show-all-levels="false"
                                :placeholder="$t('Edb.please_select')"
                            ></el-cascader>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.null_val_deal')">
                            <el-select
                                v-model="formData.nullValueWay"
                                :placeholder="$t('Edb.please_select')"
                                style="width:180px"
                            >
                                <el-option
                                    v-for="item in nullWayOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.max_null_val')" v-if="showMaxNullDeal">
                            <el-select
                                v-model="formData.maxNullWay"
                                :placeholder="$t('Edb.please_select')"
                            >
                                <el-option :label="$t('EtaBasePage.equal_zeto')" :value="1" />
                                <el-option label="跳过空值" :value="2" />
                            </el-select>
                        </el-form-item>
                    </template>

                    <!-- 多指标求和/平均 -->
                    <template v-if="computedType=='multipleEDB'">
                        <el-form-item style="margin-right:30px">
                        <el-radio-group :disabled="isEdit" v-model="subComputedType">
                            <el-radio :label="81"><!--  -->{{$t('EtaBasePage.sum_radio_label')}}</el-radio>
                            <el-radio :label="82"><!-- 求平均 -->{{$t('EtaBasePage.average_radio_label')}}</el-radio>
                        </el-radio-group>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.create_edb_time_index')">
                            <el-cascader
                                v-model="formData.timeSeriesVal"
                                style="width:180px"
                                :options="timeSeriesOpt"
                                :props="{emitPath:false}"
                                :show-all-levels="false"
                                :placeholder="$t('Edb.please_select')"
                            ></el-cascader>
                        </el-form-item>
                        <el-form-item :label="$t('EtaBasePage.null_val_deal')">
                            <el-select
                                v-model="formData.nullValueWay"
                                :placeholder="$t('Edb.please_select')"
                                style="width:180px"
                            >
                                <el-option
                                    v-for="item in nullWayOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </template>

                    <!-- 升频 -->
                    <template v-if="computedType==14">
                        <el-form-item :label="$t('EtaBasePage.null_val_deal')" prop="emptyType">
                            <el-select
                                v-model="formData.emptyType"
                                :placeholder="$t('Edb.InputHolderAll.input_fre')"
                            >
                                <el-option :label="$t('EtaBasePage.null_val_deal_2')" :value="0"></el-option>
                                <el-option :label="$t('EtaBasePage.null_val_deal_3')" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </template>

                </div>
            </div>
            </el-form>
            <div class="filter-wrap" style="margin-top:20px">
                <p style="margin-bottom:10px">
                    <!-- 待选指标（选择指标数量不超过{{MAXAddNUM}}） -->
                    {{$t('EtaBasePage.pending_metrics',{num:MAXAddNUM})}}
                </p>
                <div>
                    <cascader
                        style="display:inline-block"
                        v-model="filter.classify"
                        :options="classifyOpt"
                        clearable
                        collapse-tags
                        :placeholder="$t('EtaBasePage.label_classify')"
                        cascaderWidth="width: 240px"
                        @changeVal="handleFilter"
                        :config="{ multiple: true, emitPath: false }"
                    />
                    <el-select
						v-model="filter.frequency"
						:placeholder="$t('EtaBasePage.select_frequency')"
						style="width: 140px"
						clearable
                        multiple
                        collapse-tags
                        @change="handleFilter"
                        :disabled="[5,61].includes(subComputedType)"
					>
						<el-option
							v-for="item in frequencyArr"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
                    <el-cascader
                        v-model="filter.user"
                        :placeholder="$t('EtaBasePage.table_col_creator')"
                        :options="sysUserOpts"
                        :props="sysUserProps"
                        collapse-tags
                        :show-all-levels="false"
                        clearable
                        filterable
                        style="width:240px"
                        @change="handleFilter"
                    />
                    <el-input 
                        :placeholder="$t('Edb.InputHolderAll.input_name_orid')" 
                        v-model="filter.keyword"
                        style="width: 200px"
                        @keydown.enter.native="handleFilter"
                    >
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <el-checkbox 
                        :label="$t('EtaBasePage.label_all_check')" 
                        v-model="isCheckAll" 
                        :indeterminate="isCheckIndeterminate" 
                        style="margin-left:10px"
                        @change="listCheckAllChange"
                        :disabled="operationForm.view"
                    />
                </div>
            </div>
            <div class="table-wrap">
                <div class="left-box">
                    <el-table 
                        :data="list" 
                        border 
                        @sort-change="sortChange"  
                        @selection-change="selectionChange"
                        ref="edbDataRef" 
                        @select="selectHandle" 
                        @select-all="selectAllHandle"
                        height="500px"
                        v-loading="listLoading"
                    >
                        <el-table-column type="selection" min-width="50" align="center" :selectable="filterEdbAuth"/>
                        <el-table-column :label="$t('EtaBasePage.full_metric_name')" show-overflow-tooltip align="center" :prop="$parent.currentLang==='en'?'EdbNameEn':'EdbName'"/>
                        <el-table-column :label="$t('Edb.Detail.e_latest_date')" align="center" prop="EndDate" width="120px" />
                        <el-table-column :label="$t('Edb.Detail.e_latest_value')" align="center" show-overflow-tooltip prop="EndValue" width="80px"/>
                        <el-table-column :label="$t('EtaBasePage.table_col_creator')" align="center" show-overflow-tooltip prop="SysUserRealName" width="80px"/>
                        <el-table-column :label="$t('Edb.Detail.e_fre')" align="center" prop="Frequency" width="50px">
                            <template slot-scope="scope">
                                <span>{{ getFrequencyTrans(scope.row.Frequency) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('Edb.Detail.e_unit')" show-overflow-tooltip align="center" :prop="$parent.currentLang==='en'?'UnitEn':'Unit'" width="50px">
                            <template slot-scope="scope">
                                <span>{{ getUnitTrans(scope.row.Unit) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <m-page 
                        style="margin-top:10px"
                        class="table-page" 
                        v-show="total"
                        :total="total" 
                        :pageSize="pageSize"
                        :page_no="page"
                        :pagercount="5"
                        @handleCurrentChange="pageNumberChange"
                    />
                </div>
                <div style="padding-top:200px;margin:0 30px">
                    <el-button type="primary" :disabled="operationForm.view" :loading="addLoading" @click="getAddEdbListData">
                        <!-- 加入已选指标 -->
                        {{$t('EtaBasePage.add_to_selections')}}
                    </el-button>
                </div>
                <div class="right-box">
                    <el-table 
                        :data="selectList" 
                        border 
                        height="500px"
                    >
                        <el-table-column :label="$t('EtaBasePage.serial_num')" width="50px" align="center" prop="No" v-if="computedType=='multipleEDB'">
                            <template slot-scope="scope">
                                {{scope.$index|getNoText}}
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('EtaBasePage.full_metric_name')" show-overflow-tooltip align="center" :prop="$parent.currentLang==='en'?'EdbNameEn':'EdbName'"/>
                        <el-table-column width="50px" align="center" v-if="!operationForm.view">
                            <template slot="header" slot-scope="scope">
                                <img @click="handleDelSelect('all')" style="width:15px;height:15px;cursor: pointer;" src="~@/assets/img/ai_m/delete.png" alt="">
                            </template>
                            <template slot-scope="scope">
                                <img @click="handleDelSelect(scope)" style="width:15px;height:15px;cursor: pointer;" src="~@/assets/img/ai_m/delete.png" alt="">
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div style="text-align:center;margin:60px 0 40px 0">
                <el-button type="primary" plain @click="handleCloseSelf">{{$t('Dialog.cancel_btn')}}</el-button>
                <el-button type="primary" @click="handleNextStep">{{$t('Dialog.next_step')}}</el-button>
            </div>
        </div>
        <!-- 结果保存 -->
        <batchComputedSave 
            :select_target="select_target"
            :computedType="computedType" 
            :subComputedType="subComputedType" 
            :selectList="selectList" 
            :formData="formData" 
            :isEdit="isEdit"
            :operationForm="operationForm"
            @close="showSave=false" 
            @addCallBack="handleAddSuccess"
            v-else
        />
    </el-dialog>
</template>

<script>
import mPage from '@/components/mPage.vue'
import {computedBatchTypesV2,getBatchComputedTypesV2} from './util'
import { dataBaseInterface,departInterence } from '@/api/api.js';
import batchComputedSave from './batchComputedSave.vue';
import {generateSeriesArray} from './util'
const tag_arr = generateSeriesArray();
export default {
    components:{mPage,batchComputedSave},
    props:{
        isShow:{
            type: Boolean
        },
        operationForm: {
			type: Object,
		},
        type: {
			type: Number
		},
    },
    filters:{
        getNoText(e){
            return tag_arr[e]
        }
    },
    computed:{
        // 最大添加指标的上限
        MAXAddNUM(){
            let num=50
            if(this.computedType=='multipleEDB'){
                num=100
            }
            return num
        },
        /* max空值处理显示 当输入的公式包含MAX、MIN且空值处理为0时，输入公式失焦后出现右侧选项； */
		showMaxNullDeal() {
			let haveMaxOrMin =  this.formData.formula.toUpperCase().includes('MAX') || this.formData.formula.toUpperCase().includes('MIN')

			return haveMaxOrMin && this.formData.nullValueWay===4
		},
        timeSeriesOpt(){
            let arr=[
                {
                    // label:`指标A`,
                    label:this.$t('EtaBasePage.edbTagA'),
                    value:'A'
                },
                {
                    // label:`指标B`,
                    label:this.$t('EtaBasePage.edbTagB'),
                    value:'B'
                }
            ]
            if(this.computedType=='multipleEDB'){
                arr=this.selectList.map((item,index)=>{
                    return{
                        label:`指标${tag_arr[index]}`,
                        value:tag_arr[index]
                    }
                })
            }
            return [
                {
                    // label:'指定指标时间序列',
                    lable:this.$t('EtaBasePage.specify_series_label'),
					value:'0',
                    children:arr
                },
                {
					// label:'所有指标时间序列并集',
                    lable:this.$t('EtaBasePage.union_series_label'),
					value:'all',
				}
            ]
        },

        frequencyArr(){
            if(this.computedType==75){
                
                return [
                {
					value: '周度',
					label: /* '周度' */this.$t('Edb.FreAll.week'),
				},
				{
					value: '旬度',
					label: /* '旬度' */this.$t('Edb.FreAll.dekad'),
				},
				{
					value: '月度',
					label: /* '月度' */this.$t('Edb.FreAll.month'),
				},
				{
					value: '季度',
					label: /* '季度' */ this.$t('Edb.FreAll.quarter'),
				},
				
				{
					value: '年度',
					label: /* '年度' */ this.$t('Edb.FreAll.year'),
				}]
            }
            return [
                {
					value: '日度',
					label: /* '日度'  */this.$t('Edb.FreAll.day'),
				},
				{
					value: '周度',
					label: /* '周度' */this.$t('Edb.FreAll.week'),
				},
				{
					value: '旬度',
					label: /* '旬度' */this.$t('Edb.FreAll.dekad'),
				},
				{
					value: '月度',
					label: /* '月度' */this.$t('Edb.FreAll.month'),
				},
				{
					value: '季度',
					label: /* '季度' */ this.$t('Edb.FreAll.quarter'),
				},
				
				{
					value: '年度',
					label: /* '年度' */ this.$t('Edb.FreAll.year'),
				}]
        },
        computedBatchTypes(){
            return getBatchComputedTypesV2()
        }
    },
    watch: {
        isShow(n){
            if(!n){
                this.subComputedType=''
                this.select_target=''
                this.selectList=[]
                this.tableDataCheckedList=[]
                this.tableDataIds=[]
                this.isCheckAll=false
                this.isCheckIndeterminate=false
                this.checkAllStatus=false
                this.selectionReactCancel=false
                this.isEdit=false
                this.showSave=false
                this.computedType=computedBatchTypesV2[0].type
                this.filter={
                    classify:'',
                    frequency:'',
                    user:'',
                    keyword:''
                }
                this.formData={
                    nNum:1,
                    calendarType:'公历',
                    frequency:'',
                    valueType:'期末值',
                    newValue:0,
                    alphaValue:'',
                    formula:'',
                    timeSeriesVal:'A',
                    nullValueWay:0,
                    maxNullWay:1,
                    emptyType:0
                }
            }else{
                // 编辑多指标求和\平均
                if([81,82].includes(this.type)){
                    this.initData()
                }
                this.handleFilter()

                this.getClassifyOpt()
                this.getSysUserList()
            }
        }
    },
    data() {
        return {
            showSave:false,//显示结果保存模块
            /* computedBatchTypes:computedBatchTypesV2,//计算类型筛选项 */
            computedType:computedBatchTypesV2[0].type,//当前选中的计算类型
            subComputedType:'',//二级计算类型
            formData:{
                nNum:1,
                calendarType:'公历',
                frequency:'',
                valueType:'期末值',
                newValue:0,
                alphaValue:'',
                formula:'',
                timeSeriesVal:'A',
                nullValueWay:0,
                maxNullWay:1,
                emptyType:0,
            },

            select_target:'',
			searchOptions:[],//指标列表
            search_have_more:false,
            search_page: 1,
			current_search: '',

            filter:{
                classify:'',
                frequency:'',
                user:'',
                keyword:''
            },

            classifyOpt: [],
			classifyProps: {
				label: 'ClassifyName',
				value: 'ClassifyId',
				children: 'Children',
				multiple: true,
                emitPath:false
			},
            sysUserOpts:[],
            sysUserProps:{
                value: "AdminId",
                label: "RealName",
                children: "ChildrenList",
                multiple: true,
                emitPath:false
            },

            nullWayOptions: [
               
				{ label: /* '查找前后35天最近值' */  this.$t('EtaBasePage.null_val_deal_0'),value: 0 },
				{ label: /* '不计算' */ this.$t('EtaBasePage.not_alculate_options'),value: 1 },
				{ label: /* '前值填充' */this.$t('EtaBasePage.forward_fill_options'),value: 2 },
				{ label: /* '后值填充' */this.$t('EtaBasePage.backward_fill_options') ,value: 3 },
				{ label: /* '等于0' */this.$t('EtaBasePage.equal_zeto') ,value: 4 },
			],

            isCheckAll:false,//是否全选
            isCheckIndeterminate:false,// 标志列表当前是全选状态还是不是全选状态和 isCheckAll不一样
            checkAllStatus:false,
            selectionReactCancel:false,// 是否不触发 selection的逻辑

            listLoading:false,
            page:1,
            pageSize:20,
            total:0,
            list:[],

            tableDataCheckedList:[],
            tableDataIds:[],

            selectList:[],//添加到右侧的数据
            addLoading:false,

            isEdit:false,//是否为多指标求和等编辑

        }
    },
    
    methods: {
        // 编辑时初始化数据
        initData(){
            this.isEdit=true
            const arr=this.operationForm.CalculateList||[]
            this.selectList=arr.map(item=>{
                return {
                    ClassifyId:item.ClassifyId,
                    EdbInfoId:item.FromEdbInfoId,
                    EdbName:item.FromEdbName,
                    Frequency:item.Frequency,
                    Unit:item.Unit
                }
            })
            this.computedType='multipleEDB'
            this.subComputedType=this.type
            this.formData.timeSeriesVal=this.operationForm.EdbInfoDetail.Extra?JSON.parse(this.operationForm.EdbInfoDetail.Extra).DateTag:'A'
            this.formData.nullValueWay=this.operationForm.EdbInfoDetail.EmptyType||0

        },
        //批量计算成功回调
        handleAddSuccess(type,params){
            this.$emit('addCallBack',type,params)
        },
        // 跳转下一步
        handleNextStep(){
            if(this.selectList.length===0){
                this.$message.warning(/* "请选择指标"  */this.$t('Edb.InputHolderAll.input_select_edb'))
                return
            }
            if([8,12,13,35].includes(this.computedType) && !this.formData.nNum){
                this.$message.warning(/* "请输入N数值"  */ this.$t('Edb.InputHolderAll.input_n_value'))
                return
            }
            if([51].includes(this.computedType)&& !this.formData.frequency){
                this.$message.warning(/*'请选择频度'*/this.$t('Edb.InputHolderAll.input_fre'))
                return
            }
            if(['accumulate'].includes(this.computedType)&&this.subComputedType==62&& !this.formData.frequency){
                this.$message.warning(/*'请选择频度'*/this.$t('Edb.InputHolderAll.input_fre'))
                return
            }
            if(this.computedType==72&&!this.formData.alphaValue){
                this.$message.warning(/*'请输入alpha值'*/this.$t('Edb.InputHolderAll.input_alpha_val'))
                return
            }
            if(this.computedType==72&&(Number(this.formData.alphaValue)<=0||Number(this.formData.alphaValue)>=1)){
                this.$message.warning(/*''请输入>0，<1的数值的alpha值''*/ this.$t('EtaBasePage.numeric_greater_msg'))
                return
            }
            if(this.computedType=='withEDB'&&!this.select_target){
                this.$message.warning(/*'请选择指标B'*/this.$t('EtaBasePage.select_indicator_msg'))
                return
            }
            if(['withNum','withEDB'].includes(this.computedType)&&!this.formData.formula){
                this.$message.warning(/*'请输入公式'8*/this.$t('EtaBasePage.input_formula_msg'))
                return
            }

            this.isCheckAll=false
            this.isCheckIndeterminate=false
            this.checkAllStatus=false
            this.tableDataCheckedList=[]
            this.tableDataIds=[]

            this.showSave=true
        },

        // 点击加入已选指标库
        async getAddEdbListData(){
            if(!(this.isCheckAll || this.isCheckIndeterminate ) || (!(this.list && this.list.length>0))){
                this.$message.warning(/* "请选择指标"  */this.$t('Edb.InputHolderAll.input_select_edb'))
                return
            }
            if(this.selectList.length>=this.MAXAddNUM){
                this.$message.warning(/* "已达批量添加指标数量上限"  */this.$t('EtaBasePage.limit_indicators_msg'))
                return
            }
            const params={
                SysUserIds:this.filter.user?this.filter.user.join(','):'',
                ClassifyIds:this.filter.classify?this.filter.classify.join(','):'',
                Keyword:this.filter.keyword,
                Frequency:this.filter.frequency?this.filter.frequency.join(','):'',
                SelectAll:this.checkAllStatus,
                EdbInfoIds:this.tableDataCheckedList.join(',')
            }
            this.addLoading=true
            const res=await dataBaseInterface.getBatchFilterAddEdbList(params)
            this.addLoading=false
            if(res.Ret!=200) return
            // 加入到已选指标中 要去重
            const arr=res.Data.SearchItem||[]
            const temArr=this.mergeAndDistinct(this.selectList,arr)
            // 截取数组 防止数量溢出
            this.selectList=temArr.filter(_ =>_.HaveOperaAuth).slice(0,this.MAXAddNUM)
        },
        mergeAndDistinct(arr1, arr2) {
            // 合并两个数组
            const mergedArray = arr1.concat(arr2);

            // 根据 EdbInfoId 字段进行去重
            const distinctArray = mergedArray.filter((item, index, self) => {
                return index === self.findIndex(t => t.EdbInfoId === item.EdbInfoId);
            });

            return distinctArray;
        },

        // 删除已选指标库指标
        handleDelSelect(e){
            if(this.operationForm.view) return
            if(e==='all'){
                this.selectList=[]
                return
            }
            const index=e.$index
            this.selectList.splice(index,1)
        },

        // 切换计算类型
        handleComputedTypeChange(){
            this.subComputedType=''
            this.select_target=''
            this.formData={
                nNum:1,
                calendarType:'公历',
                frequency:'',
                valueType:'期末值',
                newValue:0,
                alphaValue:'',
                formula:'',
                timeSeriesVal:'A',
                nullValueWay:0,
                maxNullWay:1,
                emptyType:0
            }
            this.filter={
                classify:'',
                frequency:'',
                user:'',
                keyword:''
            }
            this.selectList=[]
            if(this.computedType=='toMonthSeason'){
                this.subComputedType=5
                this.filter.frequency=['月度']
            }else if(this.computedType=='accumulate'){
                this.subComputedType=62
            }else if(this.computedType=='multipleEDB'){
                this.subComputedType=81
            }
            this.handleFilter()
        },
        handleComputedSubTypeChange(){
            if(this.subComputedType==61){
                this.filter.frequency=['季度']
            }
            if(this.subComputedType==5){
                this.filter.frequency=['月度']
            }
            this.selectList=[]
            this.handleFilter()
        },

        /* 指标列表 */
		getTarget(query) {
			this.search_page = 1;
			this.current_search = query;
			this.searchApi(this.current_search);
		},

		/* 聚焦获取当前检索 */
		inputFocusHandle(e) {
			this.search_page = 1;
			this.current_search = e.target.value;
			this.searchApi(this.current_search);
		},

		searchApi(query,page=1) {
			dataBaseInterface.targetSearchByPage({
				KeyWord:query,
				CurrentIndex: page,
				FilterSource:  1,
				Frequency: ''
			}).then(res => {
				if(res.Ret !== 200) return
				const { List,Paging } = res.Data;
				this.search_have_more = page < Paging.Pages;
				let arr = page === 1 ? List : this.searchOptions.concat(List);

				this.searchOptions = arr;
					
			})
		},

		searchLoad() {
			if(!this.search_have_more) return;
			this.searchApi(this.current_search,++this.search_page)
		},

        handleClose(){
            this.showSave=false
            this.$emit('close')
        },
        handleCloseSelf(){//仅仅关闭批量计算弹窗
            this.$emit('closeSelf')
        },

        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({ClassifyType:-1})
            if (res.Ret !== 200) return
            this.filterNodes(res.Data.AllNodes||[]);
			this.classifyOpt = res.Data.AllNodes || [];
        },

        // 获取所有系统用户
        async getSysUserList() {
            const res = await departInterence.getQuestionAdminList();
            if (res.Ret === 200) {
                this.sysUserOpts = res.Data.List||[];
            }
        },

        // 获取指标列表
        async getEDBList(type){
            this.listLoading=true
            const res=await dataBaseInterface.getBatchAddEdbSearchList({
                CurrentIndex:this.page,
                PageSize: this.pageSize,
                SysUserIds:this.filter.user?this.filter.user.join(','):'',
                ClassifyIds:this.filter.classify?this.filter.classify.join(','):'',
                Keyword:this.filter.keyword,
                Frequency:this.filter.frequency?this.filter.frequency.join(','):'',
                NotFrequency:this.computedType==75?'日度':''
            })
            this.listLoading=false
            if(res.Ret===200){
                this.list=res.Data.SearchItem||[]
                this.total=res.Data.Paging.Totals||0

                if(this.list.length>0){
                    this.tableDataIds = this.list.map(it => it.EdbInfoId)
                }else{
                    this.tableDataIds = []
                }

                if(type == 'adjustSelection'){
                    this.adjustSelection()
                }else{
                    
                    this.isCheckAll=false
                    this.checkAllStatus=false
                    this.isCheckIndeterminate=false
                    
                    this.listCheckAllChange(this.isCheckAll)
                }
            }
        },

        pageNumberChange(e){
            this.page=e
            this.getEDBList('adjustSelection')
        },

        handleFilter(e){
            this.page=1
            this.list=[]
            this.getEDBList()
        },

        // 切换列表全选按钮状态
        listCheckAllChange(check){
            this.tableDataCheckedList=[]
            this.checkAllStatus=check
            if(check){
                // 全选
                this.$refs.edbDataRef && this.$refs.edbDataRef.clearSelection()
                this.$refs.edbDataRef && this.$refs.edbDataRef.toggleAllSelection()
            }else{
                //全不选
                this.$refs.edbDataRef && this.$refs.edbDataRef.clearSelection()
            }
        },

        selectionChange(val){
            if(this.selectionReactCancel) return 
        
            // selectAllHandle的触发在selectionChange后面，将selectionChange的逻辑延迟一下
            setTimeout(()=>{
                // 去重
                let duplicateArr = Array.from(new Set(this.tableDataCheckedList))
                
                if((duplicateArr.length == this.total && (!this.checkAllStatus))
                    || (duplicateArr.length == 0 && this.checkAllStatus)){
                    this.isCheckAll = true
                    this.isCheckIndeterminate=false
                }else if((duplicateArr.length == 0 && (!this.checkAllStatus))
                    || (duplicateArr.length == this.total && this.checkAllStatus)){
                    this.isCheckAll = false
                    this.isCheckIndeterminate=false
                }else{
                    this.isCheckAll = false
                    this.isCheckIndeterminate=true
                }
            },1)

        },

        //用户手动勾选数据行的 Checkbox 时触发的事件	
        selectHandle(selection, row){
            if(this.selectionReactCancel) return 

            let check=false
            if(selection.some(it => it.EdbInfoId == row.EdbInfoId)){
                // 勾选
                // 勾选
                if(this.checkAllStatus){
                    check=false
                }else{
                    check=true
                }
            }else{
                // 取消勾选
                if(this.checkAllStatus){
                    check=true
                }else{
                    check=false
                }
            }
            if(check){
                this.tableDataCheckedList.push(row.EdbInfoId)
            }else{
                this.tableDataCheckedList=this.tableDataCheckedList.filter(it => it!=row.EdbInfoId)
            }
        },

        // 用户手动勾选全选 Checkbox 时触发的事件
        selectAllHandle(selection){
            if(this.selectionReactCancel) return 
            let check = false; // 从tableDataCheckedList 添加还是删除
            if(selection && selection.length>0){
                // 全选
                if(this.checkAllStatus){
                    check=false
                }else{
                    check=true
                }
            }else{
                // 全不选
                if(this.checkAllStatus){
                    check=true
                }else{
                    check=false
                }
            }
            if(check){
                this.tableDataCheckedList =  [...this.tableDataCheckedList,...this.tableDataIds]
            }else{
                this.tableDataCheckedList = this.tableDataCheckedList.filter(it => !this.tableDataIds.includes(it))
            }
        },

        adjustSelection(){
            this.selectionReactCancel=true
            if(!this.checkAllStatus){
                this.tableDataCheckedList.map(it =>{
                    let row = this.list.find(da => da.EdbInfoId==it)
                    if(row){
                        setTimeout(()=>{
                            this.$refs.edbDataRef.toggleRowSelection(row,true)
                        },10)
                    }
                })
            }else{
                this.$refs.edbDataRef.toggleAllSelection()
                this.tableDataCheckedList.map(it =>{
                    let row = this.list.find(da => da.EdbInfoId==it)
                    if(row){
                        setTimeout(()=>{
                            this.$refs.edbDataRef.toggleRowSelection(row,false)
                        },50)
                    }
                })
            }
            setTimeout(()=>{
                this.selectionReactCancel=false
            },50)
        },

        filterEdbAuth(row) {
            return row.HaveOperaAuth
        }



    },
}
</script>

<style lang="scss">
.batch-computed-dialog{
    max-width: 1200px;
    width:90vw;
	overflow: hidden;
}
.batch-computed-wrap{
    .type-wrap{
        display: flex;
    }
    .table-wrap{
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        .left-box{
            width: 50%;
        }
        .right-box{
            flex: 1;
            flex-shrink: 0;
        }
    }
}
</style>