<template>
	<el-dialog
		:visible.sync="isShow"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
		@close="cancelHandle"
		custom-class="diffusionIndex-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">扩散指数</span>
		</div>
		<div class="dialog-main">
      <div class="main-top">
        <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-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>
				<div class="date_select_wrapper">
					<label style="flex-shrink:0">扩散指标日期</label>
					<el-radio-group 
						v-model="formData.date_type" 
						style="margin: 0 30px;flex-shrink:0"
						@change="initSelectHandle"
						:disabled="operationForm.view"
					>
						<el-radio :label="1">全部日期并集</el-radio>
						<el-radio :label="2">部分日期并集</el-radio>
					</el-radio-group>
					<el-checkbox-group v-model="formData.select_date" v-if="formData.date_type===2" :disabled="operationForm.view">
						<el-checkbox v-for="item in targetList" :key="item.target"  :label="item.tag" style="margin: 0 15px 10px 0" @change="setConcatDate">{{item.tag}}</el-checkbox>
					</el-checkbox-group>
				</div>
				<div class="concat-date" v-if="formData.date_type===2 && formData.select_date.length && concat_date.start">{{concat_date.start}}至{{concat_date.end}}</div>
      </div>
			<el-form
        ref="form"
				inline
        class="form-cont"
        label-position="left"
        label-width="80px"
        :model="formData"
        :rules="formRules"
        :disabled="operationForm.view"
      >
        	<el-form-item label="指标名称" prop="targetName" style="margin-right: 40px;">
            <el-input
              v-model="formData.targetName"
              style="width: 340px"
              placeholder="请输入指标名称"
            />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
			<selectUnit 
			  	v-model="formData.unit" 
				style="width:340px" 
				:disabled="!operationForm.edb_id&&[6,7].includes(type)"
			/>
          </el-form-item>
          <el-form-item label="指标目录" prop="menu" style="margin-right: 40px;">
            <el-cascader
              v-model="formData.menu"
              :options="options"
              :props="levelProps"
              clearable
              placeholder="请选择指标目录"
							style="width: 340px"
            />
          </el-form-item>
          <el-form-item label="频度" prop="frequency">
            <el-select
              v-model="formData.frequency"
              placeholder="请选择频度"
              style="width: 340px"
              clearable
            >
              <el-option
                v-for="item in frequencyArr"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
			</el-form>
		</div>
		<div class="dia-bot" v-if="!operationForm.view">
			<el-button
				type="primary"
				style="margin-right: 20px"
				@click="saveHandle"
				:loading="loading"
				>{{loading ? '计算中...' : operationForm.edb_id ? '保存' : '扩散指数计算'}}</el-button
			>
			<el-button type="primary" plain @click="cancelHandle('cancel')">取消</el-button>
		</div>
		<el-popover
			placement="top-start"
			width="360"
			trigger="click">
			<p v-if="isPredict" style="padding:30px;line-height:25px;" v-html="$parent.tips.get(type)"/>
			<p v-else 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 { formRules } from './util';
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: {
		isShow: {
			type: Boolean
		},
		type: {
			type: Number
		},
		operationForm: {
			type: Object,
		},
		isPredict:{//是否是预测指标
			type: Boolean,
			default:false
		}
	},
	watch: {
		isShow(newval) {
			newval && this.getMenu();
			if(newval && this.operationForm.edb_id) {
				const backData = _.cloneDeep(this.operationForm);

				this.formData = {
					targetName: backData.targetName,
					menu: backData.menu,
					frequency: backData.frequency,
					unit: backData.unit,
					date_type:  JSON.parse(backData.date).DateType,
					select_date: JSON.parse(backData.date).CheckList || []
				}

				this.targetList = backData.from_arr.map(item => ({
						tag: item.FromTag,
						target: item.FromEdbInfoId,
						start_date: item.StartDate,
						end_date: item.EndDate
					})
				)

				//options 回显
				this.searchOptions = backData.from_arr.map(item => ({
					EdbInfoId: item.FromEdbInfoId,
					EdbName: item.FromEdbName,
					StartDate: item.StartDate,
					EndDate: item.EndDate,
				}))

				this.formData.select_date.length && this.formData.date_type === 2 && this.setConcatDate()
			}
		}
	},
	data () {
		return {
			searchOptions:[],//指标列表
			formData: {
				targetName:'',
				unit:'',
				menu:'',
				frequency:'',
				date_type: 1,
				select_date: []
			},
			formRules,
			unitArr,
			options: [],
			levelProps: {
				label: 'ClassifyName',
				value: 'ClassifyId',
				children: 'Children',
			},
			frequencyArr: ['日度', '周度','旬度', '月度', '季度', '年度'],
			fre_options: ['天','周','月','季','年'],
			loading:false,
			
			search_have_more: false,
			search_page: 1,
			current_search: '',

      targetList: [
        {
          tag: tag_arr[0],
					target: '',
					start_date: '',
					end_date: '',
        },
         {
          tag: tag_arr[1],
					target: '',
					start_date: '',
					end_date: '',
        }
      ],

			concat_date: {
				start: '',
				end: ''
			}
		};
	},
	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 params={
				KeyWord:query,
				CurrentIndex: page
			}
			const res=this.isPredict
        ? await preDictEdbInterface.edbSearch(params)
        : await dataBaseInterface.targetSearchByPage(params)
				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 = this.operationForm.edb_id ? arr.filter(item => item.EdbInfoId !== this.operationForm.edb_id) : arr;
					
		},

		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) {
						list.start_date = choose_obj.StartDate;
						list.end_date = choose_obj.EndDate;
					}
				});

				this.formData.select_date.length && this.formData.date_type === 2 && this.setConcatDate()
			}
		},

		/* 清空指标和关联日期 */
		clearHandle(index) {
			this.targetList[index].start_date = '';
			this.targetList[index].end_date = '';
		},

		initSelectHandle() {
			this.formData.select_date=[];
			this.concat_date = {
				start: '',
				end: ''
			}
		},

		/* 获取目录结构 */
		async getMenu() {
			const res = this.isPredict
      ? await preDictEdbInterface.classifyListV2()
      : await dataBaseInterface.menuListV3()
				if (res.Ret === 200) {
					/* if(!this.isPredict){
						this.filterNodes(res.Data.AllNodes);
						this.options = res.Data.AllNodes || [];
					}else{
						this.options = 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;
					}
				});
		},

		/* 显示合并日期 */
		setConcatDate() {
			if(!this.formData.select_date) {
				this.concat_date = {
					start: '',
					end: ''
				}
				return
			}
			let arr = this.targetList.filter(_ => this.formData.select_date.includes(_.tag)&&_.target)
				.map(_ =>([ new Date(_.start_date).getTime(),new Date(_.end_date).getTime()])).flat(Infinity)
			this.concat_date = arr.length ? {
				start: this.$moment(Math.min(...arr)).format('YYYY-MM-DD'),
				end:this.$moment(Math.max(...arr)).format('YYYY-MM-DD'),
			} : { start: '', end: '' }
		},

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

		/* 添加指标 */
		addTargetHandle() {
			if(this.targetList.length === 26) return 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: ''
			};
			this.targetList.push(item);
		},

		// 删除指标
		delTarget(index) {
			this.targetList.splice(index, 1);
		},

		init() {
			this.searchOptions = [];
			this.formData = {
				targetName:'',
				unit:'',
				menu:'',
				frequency:'',
				date_type: 1,
				select_date: []
			};
      this.targetList = [
        {
          tag: tag_arr[0],
					target: '',
					start_date: '',
					end_date: '',
        },
         {
          tag: tag_arr[1],
					target: '',
					start_date: '',
					end_date: '',
        }
      ]
			this.$refs.form.resetFields();
		},

		/* 保存 */
		async saveHandle() {
				let filterArr = this.targetList.filter(item=> item.target);
				if(!filterArr.length) return this.$message.warning('请选择指标');
			
				await this.$refs.form.validate();
				this.loading = true;
				const {
					targetName,
					unit,
					menu,
					frequency,
					date_type,
					select_date
				} = this.formData;
				let params ={
					Source: this.type,
					EdbName: targetName,
					Unit: unit,
					ClassifyId: menu[menu.length - 1],
					Frequency: frequency,
					Formula: JSON.stringify({ DateType: date_type,CheckList: select_date }),
					EdbInfoIdArr: filterArr.map(_=>({ EdbInfoId: _.target,FromTag: _.tag  })),
				}

				const res = this.operationForm.edb_id 
					? this.isPredict?await preDictEdbInterface.operateEdbSave({...params,EdbInfoId: this.operationForm.edb_id}):await dataBaseInterface.calculateTargetEdit({ ...params,EdbInfoId: this.operationForm.edb_id })
					: this.isPredict?await preDictEdbInterface.operateEdbSave(params):await dataBaseInterface.calculateTargetSave(params)
					this.loading = false;
					if (res.Ret !== 200) return
					this.$message.success(res.Msg);

					this.operationForm.edb_id 
						? this.$emit('addCallBack','edit') 
						: this.$emit('addCallBack','add',{ code:res.Data.UniqueCode,id:res.Data.EdbInfoId,classifyId:params.ClassifyId });
					this.init();
		},
		/* 关闭弹窗 */
		cancelHandle(type) {
			this.init()
			this.$emit('cancel');
			type==='cancel' && !this.operationForm.edb_id && this.$emit('openPrev');
		},
	},
}
</script>
<style lang="scss">
.diffusionIndex-dialog {
  div::-webkit-scrollbar {
		width: 6px !important;
	}
	.el-input-number .el-input__inner {
		padding: 0 34px 0 4px;
	}
	.el-dialog__body {
		max-height: 780px;
		overflow: auto;
	}
  .el-cascader .el-input {
    width: 100%;
  }
}
</style>
<style lang='scss' scoped>
.diffusionIndex-dialog {
	position: relative;

  .form-cont {
		margin-top: 40px;
		padding-top: 30px;
		border-top: 1px dashed #AAB4CC;
	}
	.date_select_wrapper {
		display: flex;
		margin-top: 30px;
	}
	.concat-date {
		margin-top: 40px;
		color:#5882ef
	}
	.dialog-main {
		padding: 0 50px 30px;
    .target-ul {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			margin-bottom: 30px;
			.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;
		}
	}
	.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>