<template>
	<el-dialog
		:visible.sync="isOperation"
		:close-on-click-modal="false"
		:modal-append-to-body="false"
		@close="cancelHandle"
		custom-class="operation-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">{{ (operationForm.edb_id ? (operationForm.view ? '查看' : '编辑') : '') + switchType.get(type) }}</span>
		</div>
		<div class="dialog-main">

			<!-- 多选source -->
			<ul class="label-cont" v-if="!operationForm.view && !operationForm.edb_id">
				<li v-for="item in sourceList" :key="item.key" :class="{act: type === item.key}" @click="init();$emit('changeSource',item.key)">{{item.label}}</li>
			</ul>

			<div class="min-top">
				<label >选择指标：</label>

				<el-select
					v-model="select_target"
					v-loadMore="searchLoad"
					:filterable="!select_target"
					clearable
					placeholder="请输入指标名称"
					style="width: 85%"
					remote
					:remote-method="getTarget"
					@click.native="inputFocusHandle"
					@change="chooseTarget"
					@blur="search_have_more = false"
					:disabled="operationForm.view"
				>
					<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="handleSelectBtnClick" v-if="select_target"/>
				
			</div>
			<div class="middle">
				<label>已选指标：</label>
				<el-table
				:data="tableData"
				style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);margin-top:10px;"
				border>
					<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>{{ scope.row[item.key] }}</span>
						</template>
					</el-table-column>
					<el-table-column
						width="110"
						align="center"
						label="操作"
						v-if="!operationForm.view"
					>
						<template slot-scope="scope">
							<span class="deletesty" @click="delTarget">删除</span>
						</template>
					</el-table-column>
					<div slot="empty" style="padding:20px 0 30px;">
						<tableNoData text="暂无指标" size="mini"/>
					</div>
				</el-table>
				<ul 
				class="data-ul" 
				ref="dataUl" 
				@scroll="scrollHandle"
				v-if="dataList.length">
					<li
						class="value-item"
						v-for="(item, index) in dataList"
						:key="item.EdbDataId"
					>
						<span class="value-label">
							<i class="new-tag" v-if="index === 0"></i>
							{{item.DataTime}}
						</span>
						<span class="value-label" style="min-width:200px;text-align:center;">{{item.Value}}</span>
					</li>
				</ul>
				<div class="form-cont">
					<el-form
						ref="form"
						label-position="right"
						inline
						label-width="80px"
						:model="formData"
						:rules="formRules"
						:disabled="operationForm.view"
					>
						<el-form-item label="移动方式" style="display: block;" v-if="type === 22" prop="moveVal">
							<el-select
								v-model="formData.moveType"
								style="width: 100px"
								placeholder=""
								size="mini"
								@change="refreshTarget"
							>
								<el-option
									v-for="item in moveTypeOpions"
									:key="item.key"
									:label="item.label"
									:value="item.key"
								>
								</el-option>
							</el-select>
							<el-input
								style="width: 80px"
								type="number"
								min="0"
								size="mini"
								v-model="formData.moveVal"
								@keyup.native="filterCode(formData)"
							></el-input>
							<el-select
								v-model="formData.moveUnit"
								size="mini"
								placeholder=""
								style="width: 100px"
								@change="refreshTarget"
							>
								<el-option
									v-for="item in fre_options"
									:key="item"
									:label="item"
									:value="item"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="指标名称" prop="targetName">
							<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">
							<el-cascader
								v-model="formData.menu"
								:options="options"
								:props="levelProps"
								clearable
								placeholder="请选择指标目录"
							/>
						</el-form-item>
						<el-form-item label="频度" prop="frequency">
							<el-select
								v-model="formData.frequency"
								placeholder="请选择频度"
								style="width: 340px"
								clearable
								:disabled="[5,14,61,63].includes(type)||(!operationForm.edb_id&&[6,7].includes(type))"
							>
								<el-option
									v-for="item in frequencyArr"
									:key="item"
									:label="item"
									:value="item"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="N等于" prop="n_num" v-if="[8,12,13,35].includes(type)">
							<el-input
								v-model="formData.n_num"
								style="width: 340px"
								placeholder="请输入N数值"
								type="number"
								@change="NchangeHandle"
							/>
						</el-form-item>
						<el-form-item label="日历" prop="calendar_type" v-if="type===35">
							<el-select
								v-model="formData.calendar_type"
								placeholder="请选择日历"
								style="width: 340px"
								@change="NchangeHandle"
							>
								<el-option
									v-for="item in calendarOptions"
									:key="item.key"
									:label="item.label"
									:value="item.label"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="数据取值" prop="value_type" v-if="type===51">
							<el-select
								v-model="formData.value_type"
								placeholder="请选择数据取值类型"
								style="width: 340px"
							>
								<el-option key="期末值" label="期末值" value="期末值"/>
								<el-option key="平均值" label="平均值" value="平均值"/>
							</el-select>
						</el-form-item>
					</el-form>
				</div>
			</div>
		</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 ? '保存' : 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 { formRules } from './util';
import { unitArr } from '@/utils/defaultOptions';
export default {
	name:'',
	props: {
		isOperation: {
			type: Boolean
		},
		type: {
			type: Number
		},
		operationForm: {
			type: Object,
		}
	},
	watch: {
		isOperation(newval) {
			newval && this.getMenu();
			if(newval && this.operationForm.edb_id) {
				const backData = _.cloneDeep(this.operationForm);
				this.select_target = backData.oldedb_id;
				const { 
					edb_id,
					targetName,
					unit,
					menu,
					frequency,
					formula,
					moveType,
					moveUnit,
					moveVal,
					oldedb_id,
					oldEdb_name,
					calendar_type
				} = backData;
				this.formData = {
					edb_id,
					targetName,
					unit,
					menu,
					frequency,
					n_num: formula,
					value_type: this.type === 51 ? formula : '期末值',
					moveType,
					moveUnit,
					moveVal,
					calendar_type
				}
				this.getDataList();

				//回显时的默认options
				this.searchOptions = [
					{
						EdbInfoId: oldedb_id,
						EdbName: oldEdb_name,
					}
				]
			}

			this.sourceList = [5,61].includes(this.type)
				? [{ label: '累计值转月值',key: 5 },{ label: '累计值转季值',key: 61 }]
				: [62,63].includes(this.type)
				? [{ label: '累计值',key: 62 },{ label: '年初至今累计值',key: 63 }]
				: []
		}
	},
	data () {
		return {
			select_target:'',
			searchOptions:[],//指标列表
			haveMore: true,
			dataList:[],
            tableData:[],
			page_no:1,
			tableColums:[
					{
					label: '指标ID',
					key: 'EdbCode',
				},
				{
					label: '指标名称',
					key: 'EdbName',
				},
				{
					label: '频度',
					key: 'Frequency',
				},
				{
					label: '单位',
					key: 'Unit',
				},
				{
					label: '起始时间',
					key: 'StartDate',
					minwidthsty: '100px'
				},
				{
					label: '更新时间',
					key: 'ModifyTime',
					minwidthsty: '110px'
				},
				{
					label: '来源',
					key: 'SourceName',
				},
			],
			switchType: new Map([
				[5,'累计值转月/季值'],
				[6,'同比值'],
				[7,'同差值'],
				[8,'N数值移动平均计算'],
				[12,'N数值环比值'],
				[13,'N数值环差值'],
				[14,'升频'],
				[22,'时间移位'],
				[35,'超季节性'],
				[40,'数据调整'],
				[52,'年化'],
				[51,'降频'],
				[61,'累计值转月/季值'],
				[62,'累计值'],
				[63,'累计值'],
			]),//标题
			save_txts: new Map([
				[5,'转月值计算'],
				[6,'同比值计算'],
				[7,'同差值计算'],
				[8,'移动平均计算'],
				[12,'环比值计算'],
				[13,'环差值计算'],
				[14,'升频计算'],
				[22,'保存'],
				[35,'超季节性计算'],
				[52,'年化计算'],
				[51,'降频计算'],
				[61,'转季值计算'],
				[62,'累计值计算'],
				[63,'年初至今计算'],
			]),//保存文案
			formData: {
				targetName:'',
				unit:'',
				menu:'',
				frequency:'',
				n_num: 1,
				moveType: 1,
				moveUnit: '天',
				moveVal: '',
				calendar_type: '公历',
				value_type: '期末值'
			},
			formRules,
			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: '',

			calendarOptions: [
				{label: '公历',key: 1},
				{label: '农历',key: 2},
			],

			sourceList: [],

		};
	},
	methods: {
		/* 指标列表 */
		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) {

			const filterMap = {
				5: 2,
				14: 3,
				63: 6
			}

			dataBaseInterface.targetSearchByPage({
				KeyWord:query,
				CurrentIndex: page,
				FilterSource: filterMap[this.type] ? filterMap[this.type] : 1,
				Frequency: this.type===61?'季度': ''
			}).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 = 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)
		},

		/* 获取目录结构 */
		getMenu() {
			dataBaseInterface.menuListV3().then((res) => {
				if (res.Ret === 200) {
					//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;
					}
				});
		},
		/* 获取指标数据 */
		getDataList() {
			dataBaseInterface.targetList({
				PageSize: 10,
				CurrentIndex: this.page_no,
				EdbInfoId: this.select_target,
			}).then(res => {
				if(res.Ret === 200) {
					if(res.Data) {
						res.Data.Item.ModifyTime = res.Data.Item.ModifyTime.substr(0,10);
						this.tableData = [res.Data.Item] || [];
						this.haveMore =  this.page_no < res.Data.Paging.Pages ? true : false;
						this.dataList = this.page_no === 1 ? (res.Data.Item.DataList || []) : this.dataList.concat(res.Data.Item.DataList);
					}else {
						this.tableData = [];
						this.dataList = [];
					}
				}
			})
		},
		/* 滚动加载 */
		scrollHandle(e) {
			const dom = e.target
			let scrollTop = dom.scrollTop; //滑入屏幕上方的高度
			let windowHeitht = dom.clientHeight; //页面的高度
			let scrollHeight = dom.scrollHeight; //整个div的高度
			let total = scrollTop + windowHeitht
			if(total >= scrollHeight && this.haveMore){
				this.page_no ++;
				this.getDataList();
			}
		},
		/* 选择指标 */
		chooseTarget(val) {
			if(val) {
				let obj = this.searchOptions.find(item => item.EdbInfoId === val);
				if(obj.Frequency !== '月度' && this.type === 5) {
					this.select_target = '';
					this.$message.warning('只能选择月度指标')
					return;
				}
				//频度 名称默认同步
				this.setDefaultOption(obj);
				this.page_no = 1;
				this.dataList.length ? this.$refs.dataUl.scrollTop = 0 : null;
				this.getDataList()
			}else {
				this.tableData = [];
				this.dataList = [];
			}
		},
		/* 删除已选指标 */
		delTarget() {
			this.tableData = [];
			this.dataList = [];
			this.select_target = '';
			this.page_no = 1;
		},

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

		init() {
			this.page_no = 1;
			this.select_target = '';
			this.searchOptions = [];
			this.tableData = [];
			this.dataList = [];
			this.formData = {
				targetName:'',
				unit:'',
				menu:'',
				frequency:'',
				n_num: 1,
				moveType: 1,
				moveUnit: '天',
				moveVal: '',
				calendar_type: '公历',
				value_type: '期末值'
			};
			this.$refs.form.resetFields();
		},
		/* 保存 */
		async saveHandle() {
			if(!this.select_target) this.$message.warning('指标不能为空')
			
				console.log(this.formData)
				await this.$refs.form.validate();
				this.loading = true;

				const valueMap = {
					22: 'moveVal',
					51: 'value_type'
				}

				let params ={
					Source: this.type,
					EdbName: this.formData.targetName,
					Unit: this.formData.unit,
					ClassifyId: this.formData.menu[this.formData.menu.length - 1],
					Frequency: this.formData.frequency,
					Formula: valueMap[this.type] ? String(this.formData[valueMap[this.type]]) : String(this.formData.n_num),
					FromEdbInfoId: this.select_target,
					MoveFrequency: this.formData.moveUnit,
					MoveType: this.formData.moveType, 
					Calendar: this.formData.calendar_type,
				}

				const res = this.operationForm.edb_id 
					? await dataBaseInterface.calculateTargetEdit({ ...params,EdbInfoId: this.operationForm.edb_id })
					: 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');
		},

		// N数值变化，名称也变化
		NchangeHandle() {
			if(!this.select_target) return;
			let obj = this.searchOptions.find(item => item.EdbInfoId === this.select_target);
			const tMap=new Map([
				['日度','D'],
				['周度','W'],
				['旬度','T'],
				['月度','M'],
				['季度','Q'],
				['年度','Y'],
			])
			const name_map = {
				8: `${obj.EdbName}/${this.formData.n_num}${tMap.get(obj.Frequency)}MA`,
				12: `${obj.EdbName}${this.formData.n_num}${obj.Frequency.slice(0,1)}环比`,
				13: `${obj.EdbName}${this.formData.n_num}${obj.Frequency.slice(0,1)}环差`,
				35: `${obj.EdbName}超季节性/${this.formData.n_num}年${this.formData.calendar_type==='公历'?'':'/'+this.formData.calendar_type}`
			}
			this.formData.targetName = name_map[this.type] || '';
		},

		/* 单位默认同步基础指标
		同比 同差 频度同步 单位无 
		转月 平均值 频度单位同步
				
		同比 同差值：默认名称为指标名称+同比/同差
		n数值环比/环差值计算：默认名称为指标名称+N+频度+环比/环差
		转月 平均计算 变频默认指标名称同步
		2023/2/6 
		N数值移动平均计算:原指标名称/N*MA
		变频:原指标名称/频度+变频
		*/
		setDefaultOption(obj) {
			const tMap=new Map([
				['日度','D'],
				['周度','W'],
				['旬度','T'],
				['月度','M'],
				['季度','Q'],
				['年度','Y'],
			])
			const name_map = {
				5: obj.EdbName,
				8: `${obj.EdbName}/${this.formData.n_num}${tMap.get(obj.Frequency)}MA`,
				14: `${obj.EdbName}/${obj.Frequency}升频`,
				6: `${obj.EdbName}同比`,
				7: `${obj.EdbName}同差`,
				12: `${obj.EdbName}${this.formData.n_num}${obj.Frequency.slice(0,1)}环比`,
				13: `${obj.EdbName}${this.formData.n_num}${obj.Frequency.slice(0,1)}环差`,
				35: `${obj.EdbName}超季节性/${this.formData.n_num}年${this.formData.calendar_type==='公历'?'':'/'+this.formData.calendar_type}`,
				52: `${obj.EdbName}年化`,
				51: `${obj.EdbName}/${obj.Frequency}降频`,
				61:  obj.EdbName,
				62:  obj.EdbName,
				63:  obj.EdbName,
			}

			this.formData = {
				targetName: name_map[this.type] || '',
				frequency: this.type === 14 ? '日度' : this.type === 61 ? '季度' : this.type === 62 ? '' : obj.Frequency,
				unit: [5,8,14,7,35].includes(this.type) ? obj.Unit : '无',
				menu:'',
				n_num: 1,
				moveType: 1,
				moveUnit: '天',
				moveVal: '',
				calendar_type: this.formData.calendar_type,
				value_type: this.formData.value_type
			}
		},
        handleSelectBtnClick(){
            //计算指标打开弹窗,基础指标打开新页面
            if(this.tableData[0].EdbType===2){
                this.$emit('lookHistory',this.select_target)
            }else{
                const {ClassifyId,UniqueCode,EdbInfoId} = this.tableData[0]
                let {href} = this.$router.resolve({path:`/database`,query:{code:UniqueCode,id:EdbInfoId,classifyId:ClassifyId}});
                window.open(href,'_blank');
            }
        }
	},
	created() {},
	mounted() {},
}
</script>
<style lang='scss'>
.operation-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: 780px;
		overflow: auto;
	}
	.dialog-main {
		.el-cascader .el-input {
			width: 340px;
		}
		.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;
				}
			}
		}
		.min-top {
			padding: 20px 30px;
			border: 1px solid #ECECEC;
			box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
			border-radius:4px;
		}
		.middle {
			margin-top: 20px;
			.data-ul {
				margin-top: 5px;
				border-bottom: 1px solid #dcdfe6;
				max-height: 140px;
				overflow-y: auto;
				.value-item {
					/* width: 100%; */
					padding: 14px 0;
					border: 1px solid #dcdfe6;
					border-bottom: none;
					display: flex;
					justify-content: space-around;
					.value-label {
						position: relative;
						color: #666;
					}
					.new-tag {
						width: 6px;
						height: 6px;
						display: inline-block;
						position: absolute;
						left: -12px;
						top: 50%;
						transform: translateY(-50%);
						border-radius: 50%;
						background: #f00;
					}
				}
			}
			.form-cont {
				padding-top: 30px;
				margin-top: 30px;
				border-top: 1px dashed #AAB4CC;
				input::-webkit-outer-spin-button,
				input::-webkit-inner-spin-button {
						-webkit-appearance: none;
				}
				input[type="number"]{
					-moz-appearance: textfield;
				}
			}
		}
	}
	.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>