<template>
	<el-dialog
		:visible.sync="isOpenDialog"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
		@close="cancelHandle"
		custom-class="dynamic-differ-dialog"
		center
		width="1090px"
		top="8vh"
		v-dialogDrag
	>
		<div slot="title" style="display: flex; align-items: center">
			<span style="font-size: 16px">{{ title }}</span>
		</div>
		<div class="dialog-main">
			<ul class="add-cont">
				<li class="add-li" v-for="(list, index) in addList" :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="item.EdbName"
							:value="item.EdbInfoId"
						>
						</el-option>
					</el-select>
					<i
						class="el-icon-error del-tag"
						v-if="index > 3"
						@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="computed-min">
				<div class="computed-top">
					<span>计算公式</span>
					<el-input placeholder="请输入公式" v-model="formula" clearable style="margin: 0 8px"/>
          <el-button type="primary" @click="getResult">一键计算</el-button>
				</div>
				<span class="example-txt"
					>公式示例：A*0.5+B*C*1.2+120-MAX(A,B,C)</span
				>
				<span class="example-txt">函数支持：MAX(),MIN()</span>
			</div>
      
      <el-table
        border
        :data="resultData"
				v-if="resultData.length"
        max-height="320"
      >
        <el-table-column
          v-for="item in tableColums"
          :key="item.label"
          :label="item.label"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          align="center"
        >
          <template slot-scope="scope">
            <span :style="scope.row.isPredict&&'color: orange'">{{ scope.row[item.key] }}</span>
          </template>
        </el-table-column>
					<div slot="empty" style="padding:20px 0 30px;">
						<img src="~@/assets/img/data_m/table_no.png" alt="" style="display:block;width:135px;height:90px;margin: 10px auto 5px;">
						<span>暂无指标</span>
					</div>
      </el-table>
		</div>
		<div class="dia-bot">
			<el-button
				type="primary"
				style="margin-right: 20px"
				@click="saveHandle"
				>保存</el-button
			>
			<el-button type="primary" plain @click="cancelHandle">取消</el-button>
		</div>
	</el-dialog>
</template>

<script>
import * as preDictEdbInterface  from '@/api/modules/predictEdbApi.js';
const tag_arr = [];
for(var i=0;i<26;i++) tag_arr.push(String.fromCharCode(65+i));
export default {
	name: '',
	props: {
		isOpenDialog: {
			type: Boolean,
		},
		title: {
			type: String,
			default: '设置环比增加值',
		},
		dialog_formula: {
			type: String,
		},
		edbList: {
			type: Array,
		},
	},
	watch: {
		isOpenDialog(newval) {
			/* 回显 */
			if (this.edbList.length && newval) {
				this.addList = _.cloneDeep(this.edbList);
				this.formula = this.dialog_formula;

				this.searchOptions = this.edbList.map(item => ({
					EdbInfoId: item.target,
					EdbName: item.name,
				}))
			}
		},
	},
	data() {
		return {
			addList: [
				{
					tag: tag_arr[0],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
				{
					tag: tag_arr[1],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
				{
					tag: tag_arr[2],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
				{
					tag: tag_arr[3],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
			],
			searchOptions: [],
			formula: '', //计算公式
			dataloading: false,

			search_have_more: false,
			search_page: 1,
			current_search:'',

      tableColums: [
        {
					label: '日期',
					key: 'DataTime',
				},
				{
					label: '环比增加值',
					key: 'Value',
				},
      ],

      resultData: [],//
		};
	},
	methods: {

		/* 添加额外的指标列 */
		addTargetHandle() {
			let tag = this.addList[this.addList.length-1].tag;
			let index = tag_arr.findIndex(item => item === tag);
			const item = {
				tag: tag_arr[index+1],
				target: '',
				name: '',
				start_date: '',
				end_date: ''
			};
			this.addList.push(item);
		},

		/* 搜索指标 */
		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);
		},

		searchApi(query,page=1) {
			preDictEdbInterface
          .edbSearch({
            Keyword: query,
            CurrentIndex: page
          })
          .then((res) => {
            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.addList.forEach((list) => {
					if (list.target === val) {
						list.name = choose_obj.EdbName;
						list.start_date = choose_obj.StartDate;
						list.end_date = choose_obj.EndDate;
					}
				});
			}
		},
		/* 清空指标和关联日期 */
		clearHandle(index) {
			this.addList[index].start_date = '';
			this.addList[index].end_date = '';
			this.addList[index].name = '';
		},
		// 删除指标
		delTarget(index) {
			this.addList.splice(index, 1);
		},
		saveHandle() {
			if (!this.formula) return this.$message.warning('计算公式不能为空');
			// 指标id数组
      let target_arr = this.addList.filter(item => item.target);
			
			this.$emit('ensureBack',{arr:target_arr,formula: this.formula})
			this.cancelHandle();
		},

		/* 获取数据 */
		async getResult() {
			if (!this.formula) return this.$message.warning('计算公式不能为空');
			
			let EdbInfoIdArr = this.addList.filter(_ => _.target).map(_ => ({
				EdbInfoId: _.target,
				FromTag: _.tag
			}))

			const params = {
				RuleType: 9,
				EndDate: '',
				Value: this.formula,
				EdbInfoIdArr
			}

			const { Ret,Data } = await preDictEdbInterface.getRuleNineData(params);
			if(Ret !== 200) return

			this.resultData = Data.DataList.map(_ => ({
				..._,
				isPredict: _.DataTimestamp > this.$moment(Data.LatestDate+' 8:00').valueOf()
			})) || [];
		},
		
		init() {
			this.addList = [
				{
					tag: tag_arr[0],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
				{
					tag: tag_arr[1],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
				{
					tag: tag_arr[2],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
				{
					tag: tag_arr[3],
					name: '',
					target: '',
					start_date: '',
					end_date: '',
				},
			];
			this.searchOptions = [];
			this.formula = '';
			this.resultData = [];
		},
		cancelHandle() {
			this.init();
			this.$emit('update:isOpenDialog',false);
		},
	},
	mounted() {},
};
</script>
<style lang="scss">
.dynamic-differ-dialog {
	overflow: hidden;
	div::-webkit-scrollbar {
		width: 6px !important;
	}
	.el-dialog__body {
		max-height: 700px;
		overflow: auto;
	}
	.dialog-main {
		padding: 25px 42px 25px 25px;
		.el-cascader .el-input {
			width: 340px;
		}
		.add-cont {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			.add-li {
				position: relative;
				margin-bottom: 48px;
				.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;
		}
		.computed-min {
			margin: 50px 0;
			.example-txt {
				display: block;
				margin-left: 70px;
				margin-top: 15px;
			}
		}
	}
	.dia-bot {
		padding-bottom: 40px;
		display: flex;
		justify-content: center;
	}
}
</style>
