<template>
	<el-dialog
		:visible.sync="isBatchComputed"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
		@close="cancelHandle"
		custom-class="batch-computed-dialog"
		center
		width="1200px"
		top="5vh"
		v-dialogDrag
	>
		<div slot="title" style="display: flex; align-items: center">
			<img
				:src="$icons.computed"
				style="color: #fff; width: 16px; height: 16px; margin-right: 5px"
			/>
			<span style="font-size: 16px">{{ titleMap.get(type) }}</span>
		</div>

    <div class="cont">
				<!-- 多选source -->
			<ul class="label-cont">
				<li v-for="item in sourceList" :key="item.key" :class="{act: type === item.key}" @click="init();$emit('changeSource',item.key)">{{item.label}}</li>
			</ul>
      <ul class="target-ul">
				<li class="target-li" v-for="(list, index) in targetList" :key="index">
					<span class="li-tag">{{ list.tag }}</span>
					<el-select
						v-model="list.target"
						v-loadMore="searchLoad"
						:filterable="!list.target"
						clearable
						:placeholder="$t('Edb.InputHolderAll.input_name')"
						style="width: 400px"
						@change="chooseTarget"
						@clear="clearHandle(index)"
						remote
						:remote-method="searchTarget"
						@click.native="inputFocusHandle"
					>
						<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>

					<i class="el-icon-tickets" style="color:#409EFF;font-size:18px" @click="$emit('lookHistory',list.target)" v-if="list.target"/>

					<i
						class="el-icon-error del-tag"
						v-if="index > 1"
						@click="delTarget(index)"
					/>
					<span class="target-date" v-if="list.start_date">{{
						`${list.start_date}至${list.end_date}`
					}}</span>
				</li>
			</ul>
      <span class="add-icon" @click="addTargetHandle">
				<i class="el-icon-circle-plus-outline" style="color: #5882ef; font-size: 16px"/>
				<!-- 添加更多指标 --> {{$t('EtaBasePage.add_more_edb')}}
			</span>
      <ul class="form-ul">
        <li class="form-li" v-for="(list, index) in targetList" :key="index">
          <span class="li-tag">{{ list.tag }}</span>
          <el-input
						v-model="list.targetName"
						:placeholder="$t('Edb.InputHolderAll.input_name')"
            style="margin: 0 10px;width:25%"
					/>
					<cascader
						style="width: 25%"
						v-model="list.menu"
						:options="options"
						clearable
						:placeholder="$t('Edb.InputHolderAll.input_menu')"
						cascaderWidth="width: 100%"
						:config="{ checkStrictly: true }"
					/>
					<selectUnit 
						v-model="list.unit" 
						style="width: 15%;margin: 0 10px" 
						:disabled="[6,7,32,33,75].includes(type)"
					/>
          <el-input
            v-if="[8,12,13,39,43,44].includes(type)"
            v-model="list.n_num"
            style="width: 20%;margin-right:10px"
            :placeholder="$t('Edb.InputHolderAll.input_n_val')"
            type="number"
            @change="NchangeHandle(list.tag)"
          />
          <el-select
						v-model="list.frequency"
						:placeholder="$t('Edb.InputHolderAll.input_fre')"
						style="width: 20%"
						clearable
            :disabled="[6,7,32,33,5,42,61,64,63,66,75].includes(type)"
					>
						<el-option
							v-for="item in frequencyArr"
							:key="item"
							:label="item"
							:value="item"
						>
						</el-option>
					</el-select>
        </li>
      </ul>
    </div>

		<div class="dia-bot">
			<el-button
				type="primary"
				style="margin-right: 20px"
				@click="saveHandle"
				:loading="loading"
				>{{loading ? $t('Edb.calculate_ing') : saveBtnMap.get(type)}}</el-button
			>
			<el-button type="primary" plain @click="cancelHandle('cancel')"><!-- 取消 -->{{$t('Dialog.cancel_btn')}}</el-button>
		</div>
		<el-popover
			placement="top-start"
			width="500"
			trigger="click">
			<p style="padding:30px;line-height:25px;" v-html="$parent.tips.get(type)"/>
			<span slot="reference" class="tip-label"><!-- 公式说明 -->{{$t('Edb.formula_instru')}}</span>
		</el-popover>
	</el-dialog>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import { unitArr } from '@/utils/defaultOptions';
import { frequencyArr } from './util'

const tag_arr = [];
for(let i=0;i<26;i++) tag_arr.push(String.fromCharCode(65+i));
export default {
	name:'',
	props: {
		isBatchComputed: {
			type: Boolean
		},
		type: {
			type: Number
		},
		operationForm: {
			type: Object,
		},
		edbSource: { // ''||'predict'
			type: String,
			default: ''
		}
	},
	watch: {
		isBatchComputed(newval) {
			newval && this.getMenu();

			let isEta = this.$route.path==='/database';
			this.sourceList = [5,61,42,64].includes(this.type)
				? [{ label: /* '累计值转月值' */this.$t('Edb.CalculatesAll.to_month'),key:isEta?5:42 },{ label: /* '累计值转季值' */this.$t('Edb.CalculatesAll.to_quarter'),key: isEta?61:64 }]
				: [62,63,65,66].includes(this.type)
				? [{ label: /* '累计值' */this.$t('Edb.CalculatesAll.cumulate'),key: isEta?62:65 },{ label: /* '年初至今累计值' */this.$t('Edb.CalculatesAll.cumulate_oneyear'),key: isEta?63:66 }]
				: []

		}
	},
	data () {
		return {
			searchOptions:[],//指标列表

      targetList: [
        {
					tag: tag_arr[0],
					target: '',
					start_date: '',
					end_date: '',
          targetName: '',
          unit: '',
          menu: '',
          frequency: '',
          n_num: 1,
				},
				{
					tag: tag_arr[1],
					target: '',
					start_date: '',
					end_date: '',
          targetName: '',
          unit: '',
          menu: '',
          frequency: '',
          n_num: 1,
				},
      ],

			titleMap: new Map([
				[6,this.$t('Edb.CalculatesAll.on_year')],/* '同比值' */
				[7,this.$t('Edb.CalculatesAll.differ')],/* '同差值' */
				[8,this.$t('Edb.CalculatesAll.n_move_average')],/* 'N数值移动平均计算' */
				[12,this.$t('Edb.CalculatesAll.n_rate')],/* 'N数值环比值' */
				[13,this.$t('Edb.CalculatesAll.n_differ')],/* 'N数值环差值'  */
				[14,this.$t('Edb.CalculatesAll.up_conver')],/* 升频 */
				[5,this.$t('Edb.CalculatesAll.to_month_quarter')],/* '累计值转月/季值' */
				[61,this.$t('Edb.CalculatesAll.to_month_quarter')],/* '累计值转月/季值' */
				[62,this.$t('Edb.CalculatesAll.cumulate')],/* '累计值' */
				[63,this.$t('Edb.CalculatesAll.cumulate')],/* '累计值' */
				[32,this.$t('Edb.CalculatesAll.on_year')],/* '同比值' */
				[33,this.$t('Edb.CalculatesAll.differ')],/* '同差值' */
				[39,this.$t('Edb.CalculatesAll.n_move_average')],/* 'N数值移动平均计算' */
				[43,this.$t('Edb.CalculatesAll.n_rate')],/* 'N数值环比值' */
				[44,this.$t('Edb.CalculatesAll.n_differ')],/* 'N数值环差值'  */
				[45,this.$t('Edb.CalculatesAll.up_conver')],/* 升频 */
				[42,this.$t('Edb.CalculatesAll.to_month_quarter')],/* '累计值转月/季值' */
				[64,this.$t('Edb.CalculatesAll.to_month_quarter')],/* '累计值转月/季值' */
				[65,this.$t('Edb.CalculatesAll.cumulate')],/* '累计值' */
				[66,this.$t('Edb.CalculatesAll.cumulate')],/* '累计值' */
				[75,this.$t('Edb.CalculatesAll.day_mean')]/* '日均值' */
			]),//标题
			saveBtnMap: new Map([
				[6,this.$t('Edb.CalculateBtns.on_year')],/* '同比值计算' */
				[7,this.$t('Edb.CalculateBtns.differ')],/* '同差值计算' */
				[8,this.$t('Edb.CalculateBtns.n_move_average')],/* '移动平均计算' */
				[12,this.$t('Edb.CalculateBtns.n_rate')],/* '环比值计算' */
				[13,this.$t('Edb.CalculateBtns.n_differ')],/* '环差值计算' */
				[14,this.$t('Edb.CalculateBtns.up_conver')],/* '升频计算' */
				[32,this.$t('Edb.CalculateBtns.on_year')],/* '同比值计算' */
				[33,this.$t('Edb.CalculateBtns.differ')],/* '同差值计算' */
				[39,this.$t('Edb.CalculateBtns.n_move_average')],/* '移动平均计算' */
				[43,this.$t('Edb.CalculateBtns.n_rate')],/* '环比值计算' */
				[44,this.$t('Edb.CalculateBtns.n_differ')],/* '环差值计算' */
				[45,this.$t('Edb.CalculateBtns.up_conver')],/* '升频计算' */
				[5,this.$t('Edb.CalculateBtns.to_month')],/* '转月值计算' */
				[61,this.$t('Edb.CalculateBtns.to_quarter')],/* '转季值计算'  */
				[62,this.$t('Edb.CalculateBtns.cumulate')],/* '累计值计算' */
				[63,this.$t('Edb.CalculateBtns.cumulate_oneyear')],/* '年初至今计算' */
				[42,this.$t('Edb.CalculateBtns.to_month')],/* '转月值计算' */
				[64,this.$t('Edb.CalculateBtns.to_quarter')],/* '转季值计算'  */
				[65,this.$t('Edb.CalculateBtns.cumulate')],/* '累计值计算' */
				[66,this.$t('Edb.CalculateBtns.cumulate_oneyear')],/* '年初至今计算' */
				[75,this.$t('Edb.CalculateBtns.day_mean')],/* '日均值计算' */
			]),//保存文案
			unitArr,
			options: [],
			levelProps: {
				label: 'ClassifyName',
				value: 'ClassifyId',
				children: 'Children',
				checkStrictly: true
			},
			frequencyArr,
			fre_options: ['天','周','月','季','年'],
			moveTypeOpions: [
				{
					label: '领先',
					key: 1
				},
				{
					label: '滞后',
					key: 2
				},
			],
			loading:false,
			
			search_have_more: false,
			search_page: 1,
			current_search: '',

			sourceList:[]

		};
	},
	methods: {
    /* 搜索指标 */
		searchTarget(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);
		},

		async searchApi(query,page=1) {
			const res = this.edbSource === 'predict'
				? await preDictEdbInterface.edbSearch({
            Keyword: query,
            CurrentIndex: page,
						FilterSource: this.type === 45 ? 3 : this.type === 66 ? 6 : 1,
						Frequency: this.type===64?'季度': ''
          })
				: await dataBaseInterface.targetSearchByPage({
					KeyWord:query,
					CurrentIndex: page,
					FilterSource: this.type === 14 ? 3 : this.type === 63 ? 6 : 1,
					Frequency: this.type===61?'季度': ''
				})
				if(res.Ret !== 200) return

				const { List,Paging } = res.Data;
				this.search_have_more = page < Paging.Pages;
				this.searchOptions = page === 1 ? List : this.searchOptions.concat(List);
					
		},

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

    /* 选中指标 显示开始日期结束日期 */
		chooseTarget(val) {
			if (val) {
				const choose_obj = this.searchOptions.find(item => item.EdbInfoId === val);
				this.targetList.forEach(list => {
					if (list.target === val) {
            let default_opt = this.setDefaultOption(choose_obj,list);
						list.start_date = choose_obj.StartDate;
						list.end_date = choose_obj.EndDate;
            list.targetName = default_opt.targetName;
            list.unit = default_opt.unit;
            list.frequency = default_opt.frequency;
						list.menu = default_opt.menu||0
					}
				});

			}
		},

    /* 添加额外的指标列 */
		addTargetHandle() {
      if(this.targetList.length === 26) this.$message.warning(this.$t('EtaBasePage.num_overrun_msg'))
			let tag = this.targetList[this.targetList.length-1].tag;
			let index = tag_arr.findIndex(item => item === tag);
			const item = {
				tag: tag_arr[index+1],
				target: '',
				start_date: '',
				end_date: '',
        targetName: '',
        unit: '',
        menu: '',
        frequency: '',
        n_num: 1,
			};
			this.targetList.push(item);
		},

		/* 清空指标和关联日期 */
		clearHandle(index) {
			this.targetList[index].start_date = '';
			this.targetList[index].end_date = '';
			this.targetList[index].targetName = '';
			this.targetList[index].unit = '';
			this.targetList[index].menu = '';
			this.targetList[index].frequency = '';
			this.targetList[index].n_num = 1;
		},
    
		// 删除指标
		delTarget(index) {
			this.targetList.splice(index, 1);
		},

		/* 获取目录结构 */
		async getMenu() {
			const res = this.edbSource === 'predict'
				? await preDictEdbInterface.classifyListV2()
				: await dataBaseInterface.menuListV3()
				if (res.Ret !== 200) return
				//this.edbSource !== 'predict' && this.filterNodes(res.Data.AllNodes);
				// this.options = res.Data.AllNodes || [];
				
				this.filterNodes(res.Data.AllNodes||[]);
				this.options = res.Data.AllNodes || [];
				
		},
		// 递归改变第三级目录结构
		filterNodes(arr) {
			arr.length &&
				arr.forEach((item) => {
					item.Children.length && this.filterNodes(item.Children);
					if (!item.Children.length) {
						delete item.Children;
					}
				});
		},

	  /* 过滤负数 小数点*/
    filterCode(item) {
      item.moveVal=item.moveVal.replace(/[^\.\d]/g,'').replace('.','');
    },

		init() {
			this.searchOptions = [];
      this.targetList = [
        {
					tag: tag_arr[0],
					target: '',
					start_date: '',
					end_date: '',
          targetName: '',
          unit: '',
          menu: '',
          frequency: '',
          n_num: 1,
				},
				{
					tag: tag_arr[1],
					target: '',
					start_date: '',
					end_date: '',
          targetName: '',
          unit: '',
          menu: '',
          frequency: '',
          n_num: 1,
				},
      ]
			// this.$refs.form.resetFields();
		},
		/* 保存 */
		async saveHandle() {
      let filterArr = this.targetList.filter(item=> item.target);
      if(!filterArr.length) return this.$message.warning('请选择指标');
      let isEnough = filterArr.every(item => item.targetName&&item.unit&&item.menu&&item.frequency)
      console.log(isEnough)
      if(!isEnough) return this.$message.warning('请填写完整信息');

      let params = filterArr.map(item => ({
        CalculateId: item.tag,
        CalculateInfo: {
          ClassifyId: Array.isArray(item.menu)?item.menu[item.menu.length - 1]:item.menu,
          EdbName: item.targetName,
          Formula: String(item.n_num),
          Frequency:item.frequency,
          FromEdbInfoId: item.target,
          MoveFrequency: "天",
          MoveType: 1,
          Source: this.type,
          Unit: item.unit
        }
      }))

      const res = this.edbSource === 'predict' 
			? await preDictEdbInterface.batchCalculateTargetAdd(params)
			: await dataBaseInterface.batchCalculateTargetAdd(params)

      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.$message.success(this.$t('MsgPrompt.add_msg'));
        this.init();
        this.$emit('addCallBack','add',{ code:Success[0].UniqueCode,id:Success[0].EdbInfoId,classifyId:Success[0].ClassifyId});
      }
		},

    /* 处理失败 */
    dealFailHandle(arr) {
      let failTagArr = arr.map(_ =>_.CalculateId);
      this.targetList = this.targetList.filter(_ => failTagArr.includes(_.tag));
    },

		/* 关闭弹窗 */
		cancelHandle(type) {
			this.init()
			this.$emit('cancel');
			type==='cancel' && this.$emit('openPrev');
		},

		// N数值变化，名称也变化
		NchangeHandle(tag) {
			let obj = this.targetList.find(item => item.tag === tag);
			const edbInfo = this.searchOptions.find(item => item.EdbInfoId === obj.target);
			let edbName = this.$parent.currentLang==='en'?edbInfo.EdbNameEn:edbInfo.EdbName;

			const name_map = {
				8: edbName,
				12: `${edbName}${obj.n_num}${obj.frequency.slice(0,1)}环比`,
				13: `${edbName}${obj.n_num}${obj.frequency.slice(0,1)}环差`,
				39: edbName,
				43: `${edbName}${obj.n_num}${obj.frequency.slice(0,1)}环比`,
				44: `${edbName}${obj.n_num}${obj.frequency.slice(0,1)}环差`,
			}
      obj.targetName = name_map[this.type] || '';
		},

		/* 单位默认同步基础指标
		同比 同差 频度同步 单位无 
		转月 平均值 频度单位同步
				
		同比 同差值：默认名称为指标名称+同比/同差
		n数值环比/环差值计算：默认名称为指标名称+N+频度+环比/环差
		转月 平均计算 升频默认指标名称同步
		*/
		setDefaultOption(obj,list) {
			let edbName = this.$parent.currentLang==='en'?obj.EdbNameEn:obj.EdbName;
			let unit = this.$parent.currentLang ==='en'?obj.UnitEn:obj.Unit;

			switch (this.type) {
				case 6:
				case 32: 
					return {
						targetName: `${edbName}同比`,
						unit: '无',
						frequency: obj.Frequency
					}
				case 7: 
				case 33: 
					return {
						targetName: `${edbName}同差`,
						unit,
						frequency: obj.Frequency
					}
				case 8: 
				case 39: 
					return {
						targetName: edbName,
						unit,
						frequency: obj.Frequency
					}
				case 14:
				case 45: return {
									targetName: edbName,
									unit,
									frequency: '日度'
								}
				case 12:
				case 43: 
					return{
						targetName: `${edbName}${list.n_num}${obj.Frequency.slice(0,1)}环比`,
						unit: '无',
						frequency: obj.Frequency
					}
				case 13: 
				case 44: 
					return {
						targetName: `${edbName}${list.n_num}${obj.Frequency.slice(0,1)}环差`,
						unit: '无',
						frequency: obj.Frequency
					}
				case 5:
				case 42: 
					return {
						targetName: edbName,
						unit,
						frequency: obj.Frequency
					}
				case 61:
				case 64: 
					return {
						targetName: edbName,
						unit: '无',
						frequency: '季度'
					}
				case 62:
				case 65: 
					return {
						targetName: edbName,
						unit: '无',
						frequency: obj.Frequency
					}
				case 63:
				case 66: 
					return {
						targetName: edbName,
						unit: '无',
						frequency: obj.Frequency
					}
				case 75: 
					return {
						targetName: `${edbName}日均值`,
						unit,
						frequency: obj.Frequency,
						menu: obj.ClassifyId,
					}
			}
    }  
	},
	created() {},
	mounted() {},
}
</script>
<style lang='scss'>
.batch-computed-dialog {
	position: relative;
	div::-webkit-scrollbar {
		width: 6px !important;
	}
	.el-input-number .el-input__inner {
		padding: 0 34px 0 4px;
	}
	.el-dialog__body {
		max-height: 750px;
		overflow: auto;
	}
  .el-cascader .el-input {
			width: 100%;
	}
	.cont {
    padding: 0 40px ;
		.label-cont {
			display: flex;
			align-items: center;
			margin-bottom: 15px;
			li {
				cursor: pointer;
				font-size: 16px;
				margin-right: 24px;
				&:hover {
					color: #409EFF;
				}
				&.act {
					color: #409EFF;
				}
			}
		}
    .target-ul {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			.target-li {
				position: relative;
				margin-bottom: 30px;
				.li-tag {
					font-size: 16px;
					margin-right: 8px;
				}
				.del-tag {
					position: absolute;
					right: -30px;
					top: 12px;
					font-size: 16px;
					cursor: pointer;
				}
				.target-date {
					color: #5882ef;
					position: absolute;
					bottom: -25px;
					left: 24px;
				}
			}
		}
		.add-icon {
			font-size: 16px;
			color: #5882ef;
			cursor: pointer;
		}
    .form-ul {
      padding-top: 20px;
      margin-top: 20px;
      border-top: 1px dashed #AAB4CC;
      .form-li {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
      }
    }
	}
	.dia-bot {
		padding: 20px 0 30px;
		display: flex;
		justify-content: center;
	}
	.tip-cont {
		padding: 30px;
	}
	.tip-label {
		position: absolute;
		bottom: 30px;
		right: 30px;
		color: #409EFF;
		cursor: pointer;
	}
}
</style>