<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">{{ switchType.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="请输入指标名称"
						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"
						>
						</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"/>
				添加更多指标
			</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="请输入指标名称"
            style="margin: 0 10px;width:25%"
					/>
          <el-cascader
						v-model="list.menu"
						:options="options"
						:props="levelProps"
						clearable
						placeholder="请选择指标目录"
            style="width: 25%"
					/>
					<selectUnit 
						v-model="list.unit" 
						style="width: 15%;margin: 0 10px" 
						:disabled="[6,7,32,33].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="请输入N数值"
            type="number"
            @change="NchangeHandle(list.tag)"
          />
          <el-select
						v-model="list.frequency"
						placeholder="请选择频率"
						style="width: 20%"
						clearable
            :disabled="[6,7,32,33,5,42,61,64,63,66].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 ? '计算中...' : save_txts.get(type)}}</el-button
			>
			<el-button type="primary" plain @click="cancelHandle('cancel')">取消</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">公式说明</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';

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: '累计值转月值',key:isEta?5:42 },{ label: '累计值转季值',key: isEta?61:64 }]
				: [62,63,65,66].includes(this.type)
				? [{ label: '累计值',key: isEta?62:65 },{ label: '年初至今累计值',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,
				},
      ],

			switchType: new Map([
				[6,'同比值'],
				[7,'同差值'],
				[8,'N数值移动平均计算'],
				[12,'N数值环比值'],
				[13,'N数值环差值'],
				[14,'升频'],
				[5,'累计值转月/季值'],
				[61,'累计值转月/季值'],
				[62,'累计值'],
				[63,'累计值'],
				[32,'同比值'],
				[33,'同差值'],
				[39,'N数值移动平均计算'],
				[43,'N数值环比值'],
				[44,'N数值环差值'],
				[45,'升频'],
				[42,'累计值转月/季值'],
				[64,'累计值转月/季值'],
				[65,'累计值'],
				[66,'累计值'],
			]),//标题
			save_txts: new Map([
				[6,'同比值计算'],
				[7,'同差值计算'],
				[8,'移动平均计算'],
				[12,'环比值计算'],
				[13,'环差值计算'],
				[14,'升频计算'],
				[32,'同比值计算'],
				[33,'同差值计算'],
				[39,'移动平均计算'],
				[43,'环比值计算'],
				[44,'环差值计算'],
				[45,'升频计算'],
				[5,'转月值计算'],
				[61,'转季值计算'],
				[62,'累计值计算'],
				[63,'年初至今计算'],
				[42,'转月值计算'],
				[64,'转季值计算'],
				[65,'累计值计算'],
				[66,'年初至今计算'],
			]),//保存文案
			unitArr,
			options: [],
			levelProps: {
				label: 'ClassifyName',
				value: 'ClassifyId',
				children: 'Children',
			},
			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;
					}
				});

			}
		},

    /* 添加额外的指标列 */
		addTargetHandle() {
      if(this.targetList.length === 26) this.$message.warning('添加指标个数已达上限')
			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 || [];
		},
		// 递归改变第三级目录结构
		filterNodes(arr) {
			arr.length &&
				arr.forEach((item) => {
					item.Children.length && this.filterNodes(item.Children);
					if (item.Level === 2) {
						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: item.menu[item.menu.length - 1],
          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.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);
			const name_map = {
				8: edbInfo.EdbName,
				12: `${edbInfo.EdbName}${obj.n_num}${obj.frequency.slice(0,1)}环比`,
				13: `${edbInfo.EdbName}${obj.n_num}${obj.frequency.slice(0,1)}环差`,
				39: edbInfo.EdbName,
				43: `${edbInfo.EdbName}${obj.n_num}${obj.frequency.slice(0,1)}环比`,
				44: `${edbInfo.EdbName}${obj.n_num}${obj.frequency.slice(0,1)}环差`,
			}
      obj.targetName = name_map[this.type] || '';
		},

		/* 单位默认同步基础指标
		同比 同差 频度同步 单位无 
		转月 平均值 频度单位同步
				
		同比 同差值：默认名称为指标名称+同比/同差
		n数值环比/环差值计算：默认名称为指标名称+N+频度+环比/环差
		转月 平均计算 升频默认指标名称同步
		*/
		setDefaultOption(obj,list) {

			switch (this.type) {
				case 6:
				case 32: 
					return {
						targetName: `${obj.EdbName}同比`,
						unit: '无',
						frequency: obj.Frequency
					}
				case 7: 
				case 33: 
					return {
						targetName: `${obj.EdbName}同差`,
						unit: obj.Unit,
						frequency: obj.Frequency
					}
				case 8: 
				case 39: 
					return {
						targetName: obj.EdbName,
						unit: obj.Unit,
						frequency: obj.Frequency
					}
				case 14:
				case 45: return {
									targetName: obj.EdbName,
									unit: obj.Unit,
									frequency: '日度'
								}
				case 12:
				case 43: 
					return{
						targetName: `${obj.EdbName}${list.n_num}${obj.Frequency.slice(0,1)}环比`,
						unit: '无',
						frequency: obj.Frequency
					}
				case 13: 
				case 44: 
					return {
						targetName: `${obj.EdbName}${list.n_num}${obj.Frequency.slice(0,1)}环差`,
						unit: '无',
						frequency: obj.Frequency
					}
				case 5:
				case 42: 
					return {
						targetName: obj.EdbName,
						unit: obj.Unit,
						frequency: obj.Frequency
					}
				case 61:
				case 64: 
					return {
						targetName: obj.EdbName,
						unit: '无',
						frequency: '季度'
					}
				case 62:
				case 65: 
					return {
						targetName: obj.EdbName,
						unit: '无',
						frequency: obj.Frequency
					}
				case 63:
				case 66: 
					return {
						targetName: obj.EdbName,
						unit: '无',
						frequency: obj.Frequency
					}
			}
    }  
	},
	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>