<template>
	<div class="predictEdb-container" >
		<span
			class="slide-icon slide-right"
			@click="isSlideLeft = !isSlideLeft"
			v-show="isSlideLeft"
		>
			<i class="el-icon-d-arrow-right"></i>
		</span>
		<div class="predict-edb-main" id="box">
      <div class="main-left left" id="left" v-show="!isSlideLeft">
				<div class="datasheet_top">
						<el-button v-permission="permissionBtn.predictEdbPermission.edbPreData_addEdb"
							type="primary" @click="addEdbHandle">添加指标</el-button>
						<el-button v-permission="permissionBtn.predictEdbPermission.edbPreData_calcuEdb"
							type="primary" @click="addComputedHandler" style="margin-right:10px;">计算指标</el-button>
						<change-lang v-permission="permissionBtn.predictEdbPermission.edbPreData_switchEn"
							:lang="currentLang" style="height: 32px;" @changeLang="changeLangHandle"/>
				</div>
				<div class="search-cont" v-loading="searchLoading">
					<el-select
						v-model="search_txt"
						ref="searchRef"
						:filterable="!search_txt"
						remote
						clearable
						placeholder="指标名称"
						style="width: 100%"
						:remote-method="searchHandle"
						@focus="searchHandle('')"
					>
						<i slot="prefix" class="el-input__icon el-icon-search"></i>
						<el-option
							v-for="item in searchOptions"
							:key="item.EdbInfoId"
							:label="currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
							:value="item.EdbInfoId"
						>
							<span>{{ currentLang==='en' ? (item.EdbNameEn||item.EdbName) : item.EdbName }}</span>
						</el-option>
					</el-select>
				</div>
        <div style="margin:20px 0;padding:0 20px;display:flex;justify-content:space-between">
					<span>目录</span>
					<el-checkbox v-model="isOnlyMe"  @change="onlyMeHandler">只看我的</el-checkbox>
				</div>
				<div class="tree-cont">
					<el-tree
						ref="treeRef"
						class="target_tree"
						:data="treeData"
						node-key="UniqueCode"
						:props="defaultProp"
						:allow-drag="canDragHandle"
						:allow-drop="canDropHandle"
						:current-node-key="select_node"
						:default-expanded-keys="defaultShowNodes"
						draggable
						:expand-on-click-node="false"
						check-strictly
						empty-text="暂无分类"
						lazy
						:load="getLazyTreeData"
						@node-expand="handleNodeExpand"
						@node-collapse="handleNodeCollapse"
						@current-change="nodeChange"
						@node-drop="dropOverHandle"
						@node-drag-end="dropMouseLeave"
						@node-drag-leave="dropMouseLeave"
						@node-drag-enter="dropMouseOver"
					>
						<span class="custom-tree-node" slot-scope="{ node, data }">
							<el-input
								ref="editVal"
								style="width: 90px"
								placeholder="请输入值"
								class="label-input"
								v-model="new_label"
								v-if="data.isEdit"
								@blur="changeValue(data)"
							/>
							<span
								@dblclick.stop="editNodeLabel(data)"
								v-else
								class="text_oneLine node_label"
								:style="`width:${
									(select_node === data.UniqueCode && node.Nodewidth) || ''
								}`"
							>
								<span>{{ currentLang==='en' ? (data.ClassifyNameEn||data.ClassifyName) : data.ClassifyName }}</span>
							</span>
							<span
								style="display: flex; align-items: center"
								v-if="select_node === data.UniqueCode"
							>
								<img
									src="~@/assets/img/data_m/move_ico.png"
									alt=""
									style="width: 14px; height: 14px; margin-right: 8px"
									v-if="data.Button.MoveButton"
								/>
								<img
									src="~@/assets/img/set_m/add.png"
									alt=""
									style="width: 14px; height: 14px; margin-right: 8px"
									@click.stop="addNode(node, data)"
									v-if="data.Button.AddButton&&!data.EdbInfoId"
								/>
								<img
									src="~@/assets/img/set_m/edit.png"
									alt=""
									style="width: 15px; height: 14px; margin-right: 8px"
									@click.stop="editNode(node, data)"
									v-if="data.Button.OpButton&&!data.EdbInfoId"
								/>
								<img
									slot="reference"
									src="~@/assets/img/set_m/del.png"
									alt=""
									style="width: 14px; height: 14px"
									@click.stop="removeNode(node, data)"
									v-if="data.Button.DeleteButton&&!data.EdbInfoId"
								/>
								<i class="el-icon-view" v-if="data.EdbInfoId" @click.stop="viewNode(node,data)"></i>
								<img 
									v-if="data.Button.ShowChartRelation" 
									@click.stop="showAssociateChart=true,showAssociateComputeData=false"
									src="~@/assets/img/icons/associate_chart.png" 
									style="width: 14px; height: 14px;margin-left: 8px"
									alt=""
								/>
								<img 
									v-if="data.Button.ShowEdbRelation" 
									@click.stop="showAssociateComputeData=true,showAssociateChart=false"
									src="~@/assets/img/icons/associate_data.png" 
									style="width: 14px; height: 14px;margin-left: 8px"
									alt=""
								/>
							</span>
						</span>
					</el-tree>
					<div
						class="noDepart"
						@click="addLevelOneHandle"
						v-if="opLevelOneClassify"
					>
						<img
							src="~@/assets/img/set_m/add_ico.png"
							alt=""
							style="width: 16px; height: 16px; margin-right: 10px"
						/>
						<span>添加分类</span>
					</div>
				</div>
				<span
					class="move-btn resize"
					v-drag
					id="resize"
					@mousemove="dynamicNode && resetNodeStyle(dynamicNode)"
				></span>
				<span class="slide-icon slide-left" @click="isSlideLeft = !isSlideLeft">
					<i class="el-icon-d-arrow-left"></i>
				</span>
      </div>

			<div class="main-right" id="right" :style="isSlideLeft ? 'width:100%' : 'width:80%'">

				<!-- 详情 -->
				<div class="edb-detail-wrapper" v-if="select_id&&!showAssociateChart&&!showAssociateComputeData">
					<div class="detail-top">
						<span class="title">{{ currentLang==='en'?(edb_nameEn||edbName):edbName }}</span>
						<ul class="action-ul">
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_enNameSetting"
								class="editsty" @click="clickEdbNameHandle" v-if="currentLang==='ch'||!edb_nameEn">
								设置英文名称
							</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_edbSource"
								class="editsty" @click="isLookHistory=true;lookEdbId=select_id">指标溯源</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_update"
								class="editsty" @click="updateEdbPartHandle">更新</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_edit"
								class="editsty" @click="editEdbHandle('')" v-if="edbButton.OpButton">编辑</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_save"
								class="editsty" @click="saveEdbHandle" v-if="detail_show_chart">保存</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_recalcu"
								class="editsty" @click="updateEdbHandle">重新计算</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_del"
								class="deletesty" @click="delEdbHandle" v-if="edbButton.DeleteButton">删除</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_copyData"
								class="editsty" @click="copyData">复制数据</li>
							<li v-permission="permissionBtn.predictEdbPermission.edbPreData_viewData"
								class="editsty" @click="detail_show_chart=!detail_show_chart">{{detail_show_chart ? '查看数据' : '查看图表'}} </li>
						</ul>
					</div>

					<!--  -->
					<div class="detail-wrap">
						
						<component 
							:is="detail_show_chart?'edbDetail':'childData'"
							:id="select_id"
							:lang="currentLang" 
							ref="detailComponentRef"
							
							@updateTit="setNameBack"
							@setCurrentClassify="setCurrentClassify"
							@setOpera="(obj) => { edbButton = obj }"
							@openEnNameDia="openEnNameDia"
						/>
					</div>
				</div>

				<!-- 列表 -->
				<div class="sheet-list-cont" v-else-if="!select_id">
					<div class="list-top">
						<span>共{{ edb_total }}个预测指标</span>
					</div>
					<div
						class="edbChartList-wrapper"
						ref="listRef"
						@scroll="loadMoreHandle"
					>
						<el-col
						:span="6"
						style="margin-bottom: 20px; padding-right: 20px"
						v-for="item in edbChartList"
						:key="item.EdbInfoId"
						>
						<el-card class="sheet-item">
							<div slot="header" class="item-top">
							<span class="text_oneLine">{{ currentLang === 'en' ? (item.EdbNameEn||item.EdbName) : item.EdbName }}</span>
							</div>
							<img
							:src="item.ChartImage"
							alt=""
							class="chart-img"
							@click="detailShowHandle(item)"
							/>
							<div class="item-bottom">
							<span>创建时间: {{ item.CreateTime.slice(0,10) }}</span>
							</div>
						</el-card>
						</el-col>
					</div>
					<div v-if="!edb_total" class="nodata">
						<tableNoData text="暂无指标"/>
					</div>
				</div>

				<!-- 指标关联图模块 -->
				<div class="edb-detail-wrapper" style="padding: 30px 20px;" v-if="showAssociateChart&&select_id">
					<dataAssociateChart :edbInfoId="select_id"></dataAssociateChart>
				</div>
				<div class="edb-detail-wrapper" style="padding: 30px 20px;" v-if="showAssociateComputeData&&select_id">
					<dataAssociateComputeData :edbInfoId="select_id"></dataAssociateComputeData>
				</div>
			</div>
		</div>

		<!-- 计算弹窗控制 -->
		<el-dialog
		:visible.sync="isOpenComputed"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="isOpenComputed=false;"
		custom-class="dialog-computed"
		top="12vh"
		center
		width="950px"
		v-dialogDrag>
			<div class="dialog-computed-header">
				<el-radio-group v-model="computed_source" size="medium" @change="computed_type = 0">
					<el-radio-button :label="1">常规计算</el-radio-button>
					<el-radio-button :label="2">批量计算</el-radio-button>
				</el-radio-group>
			</div>
			<ul class="computed-ul">
				<li
					:class="['cpmputed-li',{'act':item.type === computed_type}]" 
					v-for="item in computedTypes" 
					:key="item.type" 
					@click="changeComputedType(item.type)"
					>
					{{item.name}}

					<el-popover
						placement="top-start"
						width="450"
						trigger="hover"
						v-if="tips.get(item.type)"
					>
						<p style="padding:20px;line-height:25px;" v-html="tips.get(item.type)"/>
						<i slot="reference" class="el-icon-warning-outline"/>
					</el-popover>
				</li>
			</ul>
		</el-dialog>

		<!-- 指标弹窗 -->
		<edb-dialog
			:isShow.sync="isEdbDia"
			:title="edbdia_title"
			:edbForm="edbForm"
			@successHandle="handleEdbCallBack"
		/>

		<!-- 分类弹窗 -->
		<edbClassifyDia
			:isOpenDialog.sync="classifyDia"
			:title="dialog_title"
			:form="classifyForm"
			@successCallback="getTreeData"
		/>

		<!-- 输入英文指标弹窗 -->
		<set-en-name-dia 
			:isOpenDialog="setEnName" 
			@cancel="setEnName=false" 
			:formData="formItemArray" 
			@updateEnName="updateEnName" 
			cType="predictEbd" 
		/>

		<!-- 运算指标弹窗 -->
		<computedDialog
			:isOpenComputed="computed_type === 31"
			:title="computedTit"
			:calulateForm="calulateForm"
			:calulateList="calulateList"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
			@lookHistory="id => {isLookHistory=true;lookEdbId=id;}"
		/>

		<!-- 同比同差计算弹窗 -->
		<!-- 转月值 同比 同差 平均值弹窗 -->
		<operationDialog
			:isOperation="[42,32,33,39,43,44,45,46,49,54,55,64,65,66,69,70].includes(computed_type) && computed_source===1"
			:type="computed_type"
			:operationForm="operationForm"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
			@lookHistory="id => {isLookHistory=true;lookEdbId=id;}"
			@changeSource="changeComputedType"
		/>

		<!-- 规则详情弹窗 -->
		<rules-detail
			:isOpenDialog.sync="isShowRuleDialog"
			:rules="showRules"
			:fromEdbInfo="showFromEdbInfo"
		/>

		<!-- 批量计算弹窗 -->
		<batchComputedDialog
			:isBatchComputed="[32,33,39,43,44,45,42,64,65,66].includes(computed_type) && computed_source===2"
			:type="computed_type"
			edbSource="predict"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
			@lookHistory="id => {isLookHistory=true;lookEdbId=id;}"
			@changeSource="changeComputedType"
		/>
			
		<!-- 拼接弹窗 -->
		<joint-target-dia
			:isShow="computed_type === 'joint'"
			:params="operationForm"
			:isPredict="true"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
		/>

		<!-- 拟合残差弹窗 -->
		<fittingResidueDia
			:isShow="computed_type === 50"
			:type="50"
			:operationForm="operationForm"
			:isPredict="true"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
		/>

		<!-- 扩散指数弹窗 -->
		<diffusionIndexDialog
			:isShow="computed_type === 56 && computed_source===1"
			:type="computed_type"
			:isPredict="true"
			:operationForm="operationForm"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
		/>

		 <!-- 指标历史记录 -->
    <edbHistoryDialog
      :isOpenDialog.sync="isLookHistory"
      :edbId="lookEdbId"
    />

	</div>
</template>

<script>
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import { dataBaseInterface } from '@/api/api.js';
import leftMixin from './mixins/mixin';
import edbDialog from './components/edbDia.vue'
import childChart from './components/childChart.vue'
import childData from './components/childData.vue'
import edbDetail from './components/edbDetail.vue'
import edbClassifyDia from './components/classifyDia.vue'
import changeLang from "@/views/dataEntry_manage/components/changeLang.vue"
import setEnNameDia from "@/views/dataEntry_manage/components/setEnNameDia.vue"
import computedDialog from './components/computedDialog';
import operationDialog from './components/operationDialog';
import rulesDetail from './components/rulesDetailDia.vue'
import batchComputedDialog from '@/views/dataEntry_manage/databaseComponents/batchComptedDialog.vue';
import jointTargetDia from '@/views/dataEntry_manage/databaseComponents/jointTargetDia'
import fittingResidueDia from '@/views/dataEntry_manage/databaseComponents/fittingResidueDia.vue';
import diffusionIndexDialog from '@/views/dataEntry_manage/databaseComponents/diffusionIndexDia.vue';
import { formulaTip } from '@/views/dataEntry_manage/databaseComponents/util';
import dataAssociateChart from '@/views/dataEntry_manage/databaseComponents/dataAssociateChart.vue'
import dataAssociateComputeData from '@/views/dataEntry_manage/databaseComponents/dataAssociateComputeData.vue'

export default {
	name:'',
	components: { 
		edbDialog,
		childChart,
		childData,
		edbClassifyDia,
		changeLang,
		setEnNameDia,
		computedDialog,
		operationDialog,
		edbDetail,
		rulesDetail,
		jointTargetDia,
		fittingResidueDia,
		batchComputedDialog,
		diffusionIndexDialog,
		dataAssociateChart,
		dataAssociateComputeData
	},
	mixins:[ leftMixin ],
	beforeRouteLeave (to, from, next) {
		// 前去编辑则存一次选择的节点
		if(to.path=='/editpredictEdb'){
			const obj={
				code:this.select_node,
				id:this.select_id
			}
			sessionStorage.setItem('predictEdbTreeData',JSON.stringify(obj))
		}else{
			sessionStorage.setItem('predictEdbTreeData','')
		}
		next()
	},
	data () {
		return {
			showData: false,
			search_txt: '',
			searchOptions:[],
			isSlideLeft: false,//左侧分类收起

			select_node: '',//节点唯一标识code
			select_classify: '',
			new_label:'',//双击修改的value
			treeData: [], //分类数据
			defaultShowNodes: [], //展开节点
			defaultProp: {
				label: 'ClassifyName',
				children: 'Children',
				isLeaf:'isLeaf'
			}, //树结构配置项
			dynamicNode: null,
			edbName: '',
			edb_nameEn: '',
			edbUserId: '',

			/* 分类弹窗 */
			dialog_title:'', 
			classifyDia: false, //
			classifyForm: {},

			/* 添加指标弹窗 */
			isEdbDia: false,
			edbdia_title:'',
			edbForm: {},

			select_id: '',//选中的id
			sheetDetailInfo: {},

			detail_show_chart: true,//详情展示方式 chart data

			/* 列表 */
			publicHaveMove: true,//是否还有列表数据
			edbChartList: [],
			edb_total: 0,
			public_page: 1,
			public_pages_size: 16,

			currentLang:'ch', // ch(中文) en(英文)
			setEnName:false,
			// 传入的formItem所需内容
			formItemArray:[],

			/* 计算指标弹窗 */
			isOpenComputed:false,
			computedTit:'',
			calulateForm:{},
			operationForm:{},
			calulateList:[],
			computed_type:0,//打开弹窗的类型

			tips: new Map([
				[31,formulaTip.get(4)],
				[42,formulaTip.get(5)],
				[32,formulaTip.get(6)],
				[33,formulaTip.get(7)],
				[39,formulaTip.get(8)],
				[43,formulaTip.get(12)],
				[44,formulaTip.get(13)],
				[45,formulaTip.get(14)],
				['joint',formulaTip.get('joint')],
				[46,formulaTip.get(22)],
				[49,formulaTip.get(35)],
				[50,formulaTip.get(37)],
				[54,formulaTip.get(51)],
				[55,formulaTip.get(52)],
				[56,formulaTip.get(53)],
				['toMonthSeason',formulaTip.get('toMonthSeason')],
				['accumulate',formulaTip.get('accumulate')],
				[64,formulaTip.get(61)],
				[65,formulaTip.get(62)],
				[66,formulaTip.get(63)],
			]),//公式说明

			isShowRuleDialog: false,
			showRules: [],
			showFromEdbInfo: {},

			edbButton: {},//详情操作
			opLevelOneClassify: false,//一级分类按钮

			computed_source: 1,//计算类型 1常规 2批量
			isBatchComputed: false,//批量计算弹窗

			baseTypes: [
				{ name: '指标运算',type: 31 },
				{ name: '同比值',type: 32 },
				{ name: '同差值',type: 33 },
				{ name: 'N数值移动平均计算',type: 39 },
				{ name: '累计值转月值/转季值',type: 'toMonthSeason' },
				{ name: 'N数值环比值',type: 43 },
				{ name: 'N数值环差值',type: 44 },
				{ name: '升频',type: 45 },
				// { name: '指标拼接',type: 'joint' },
				{ name: '时间移位',type: 46 },
				{ name: '超季节性',type: 49 },
				{ name: '拟合残差',type: 50 },
				{  name: '年化',type: 55 },
				{ name: '降频',type: 54 },
				{ name: '扩散指数',type: 56 },
				{ name: '累计值',type: 'accumulate' }
			],
			batchTypes: [
				{ name: '同比值',type: 32 },
				{ name: '同差值',type: 33 },
				{ name: 'N数值移动平均计算',type: 39 },
				{ name: 'N数值环比值',type: 43 },
				{ name: 'N数值环差值',type: 44 },
				{ name: '升频',type: 45 },
				{ name: '累计值转月值/转季值',type: 'toMonthSeason' },
				{ name: '累计值',type: 'accumulate' }
			],
      isOnlyMe:false,//只看我的

			/* 查看历史弹窗 */
			isLookHistory: false,
			lookEdbId: 0,
			searchLoading:false,

			showAssociateChart:false,//显示指标关联的图
			showAssociateComputeData:false,//显示指标关联的引用计算指标
		};
	},
	computed: {
		computedTypes() {
			return this.computed_source === 1 ? this.baseTypes : this.batchTypes;
		},
		role() {
			let role = localStorage.getItem('Role') || '';
			if(['rai_admin','ficc_admin'].includes(role)) {
				return 'admin'
			}
			else {
				return role;
			}
		},
		/* 登录角色id */
		roleId() {
			let id = parseInt(localStorage.getItem('AdminId'));
			return id;
		},
	},
	watch: {
		/* 设置动态右侧区域宽度 */
    isSlideLeft(newval) {
      if (!newval) {
        this.$nextTick(() => {
          this.reloadRightWid();
        });
      }
    },
		// /* 表格id */
		select_id(newval) {
			this.detail_show_chart = true;
			this.$nextTick(()=>{
				//切换为曲线图 重置选择状态
				if(this.$refs.detailComponentRef){
					this.$refs.detailComponentRef.$refs.chartInfo.chartInfo.ChartType=1;
					this.$refs.detailComponentRef.$refs.chartInfo.year_select=10;
					this.$refs.detailComponentRef.$refs.chartInfo.select_date=[];
					this.$refs.detailComponentRef.$refs.chartInfo.season_year=[];
					this.$refs.detailComponentRef.$refs.chartInfo.dateTip='请选择时间段';

				}
			})
				
		},

		select_classify(newval) {
			if(this.$refs.listRef) this.$refs.listRef.scrollTop = 0;
			if(newval) {
				this.public_page = 1;
				this.getPublicList()
			}
		},

		/* 搜索关键词 */
		search_txt(newval) {
			if(newval) {
				let search_obj = this.searchOptions.find(_ => _.EdbInfoId === newval);
				let deep_arr = _.cloneDeep(this.treeData);
				// 查找图表的分类父级id
				let arr = this.findParentNodeHandle(deep_arr, search_obj.ClassifyId).reverse(); // 父的父的父-父的父-父
				this.defaultShowNodes = arr;
				this.select_node = search_obj.UniqueCode;
				this.$refs.treeRef.setCurrentKey(this.select_node);
				// 重置筛选状态
				this.select_id = newval;
			}
		}
	},
	methods: {
		setCurrentClassify(classifyId){
			//获取指标详情后才能拿到准确的classifyId
			//根据准备的id查找指标的父级目录并展开
			let deep_arr = _.cloneDeep(this.treeData);
			let arr = this.findParentNodeHandle(deep_arr, classifyId).reverse();

			this.defaultShowNodes = arr;
			this.$refs.treeRef.setCurrentKey(this.select_node);

			//滚动到高亮节点位置
			this.$nextTick(()=>{
				setTimeout(() => {
				const dom = document.querySelector(".el-tree-node.is-current");
				const parentDom = document.querySelector(".tree-cont");
				if (!dom || !parentDom) {
					this.searchLoading = false;
					return;
				}
				if (dom.offsetTop > parentDom.offsetHeight) {
					parentDom.scrollTo({
						top: dom.offsetTop - parentDom.offsetHeight / 2,
						left: 0,
						behavior: "smooth",
					});
				}
				this.searchLoading = false;
			}, 300);
			})
		},
		setNameBack({edb_name,edb_nameEn,userid}) {
			this.edbName=edb_name;
			this.edb_nameEn= edb_nameEn;
			this.edbUserId=userid;
		},

		/* 添加指标 */
		addEdbHandle() {
			if(!this.treeData.length) return this.$message.warning('请先添加预测指标分类');
			this.$router.push({
				path:'/addpredictEdb'
			})
		},

		/* 获取分类 */
		getTreeData(params=null) {
			preDictEdbInterface.classifyListV2({IsOnlyMe:this.isOnlyMe||false}).then(res => {
				const { Ret,Data } = res;
				
				if(Ret !== 200) return

				this.treeData = Data.AllNodes || [];
				this.opLevelOneClassify = Data.CanOpClassify;
				this.currentLang = Data.Language === 'EN' ? 'en' : 'ch';
				this.showData = true;
				this.$nextTick(() => {
					/* 新增完成后 处理树展开和选中 */
					params && this.selectCurrentNode(params);
				});

			})
		},

		/* 搜索 */
		searchHandle(query) {
			if (query) {
        /* 查找列表 */
        preDictEdbInterface
          .edbSearch({
            Keyword: query,
            CurrentIndex: 1,
						PageSize: 10000,
            IsOnlyMe:this.isOnlyMe||false
          })
          .then((res) => {
            if (res.Ret !== 200) return
            this.searchOptions = res.Data.List || [];
          });
      } else {
        this.searchOptions = [];
      }
		},

		/* 选中分类变化时 */
		nodeChange({ UniqueCode,EdbInfoId,ClassifyId },node) {
			this.search_txt = '';
			this.select_node = UniqueCode;
			this.select_id = EdbInfoId || 0;
			this.select_classify = !EdbInfoId ? ClassifyId : 0;
			this.resetNodeStyle(node);
			this.dynamicNode = node;
			this.showAssociateChart=false
			this.showAssociateComputeData=false
		},

		async saveEdbHandle() {
			const {Ret} = await preDictEdbInterface.saveChartInfo({
				EdbInfoId: this.select_id,
				MaxValue: Number(this.$refs.detailComponentRef.$refs.chartInfo.tableData[0].MaxData),
				MinValue: Number(this.$refs.detailComponentRef.$refs.chartInfo.tableData[0].MinData)
			})
			if(Ret !== 200) return
			this.$message.success('保存成功')
		},

		/* 添加一级目录 */
		addLevelOneHandle() {
			this.dialog_title = '添加';
			this.classifyForm = {
				classify_name: '',
				Level:0,
				ParentId:0
			}
			this.classifyDia = true;
		},
		addNode(node,{ClassifyName,ClassifyId}){
			this.dialog_title = '添加'
			/* 添加目录 */
			this.classifyForm = {
				classify_name:'',
				Level:node.level,
				ParentId:ClassifyId,
				level_1_Name:node.level === 1
				? ClassifyName
				: node.level === 2
				? node.parent.data.ClassifyName
				: node.parent.parent.data.ClassifyName,
				level_2_Name:node.level === 1
				? ''
				: node.level === 2
				? ClassifyName
				: node.parent.data.ClassifyName,
			}
			this.classifyDia = true;
		},
    /* 编辑节点 */
    editNode(node, { ClassifyName,ClassifyId,Level,ParentId}) {

      this.dialog_title = '编辑';
      /* 编辑目录 */
      this.classifyForm = {
        classify_name: ClassifyName,
        classify_id: ClassifyId,
        Level:node.level,
        ParentId:ParentId,
        level_1_Name:node.level === 1
            ? ClassifyName
            : node.level === 2
            ? node.parent.data.ClassifyName
            : node.parent.parent.data.ClassifyName,
        level_2_Name:node.level === 1
            ? ''
            : node.level === 2
            ? ClassifyName
            : node.parent.data.ClassifyName,
      };
      this.classifyDia = true;
    },

		 /* 删除节点校验 */
    async removeNode(node, { ClassifyId,EdbInfoId }) {

			const { Data } = await preDictEdbInterface.classifyDelCheck({ ClassifyId,EdbInfoId })

			const { DeleteStatus } = Data;

			DeleteStatus === 1 
			? this.$confirm('该分类下关联指标不可删除', '删除失败', {
				confirmButtonText: '知道了',
				showCancelButton: false,
				type: 'error',
			}) : DeleteStatus === 0 && !EdbInfoId
			?  this.$confirm('确定删除当前分类吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				this.delApi(ClassifyId, EdbInfoId)
			}): null;

    },

		 /* 删除方法 */
    delApi(ClassifyId, EdbInfoId, type='') {
      preDictEdbInterface
        .classifyDel({
          ClassifyId,
          EdbInfoId,
        })
        .then((res) => {
          if (res.Ret !== 200) return
					this.$message.success(res.Msg);

					if (!res.Data.EdbInfoId || !res.Data) this.select_id = '';

					//删除表格后自动显示下一张表格
					type && res.Data.EdbInfoId
						? this.getTreeData({
								code: res.Data.UniqueCode,
								id: res.Data.EdbInfoId,
								classifyId:res.Data.ClassifyId
							})
						: this.getTreeData();
        });
    },

		/* 删除指标 */
		delEdbHandle() {
			this.$confirm('ETA预测指标删除后不可恢复，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delApi(
            this.select_classify || 0,
            this.select_id,
            'del-edb'
          );
        })
        .catch(() => {});
		},

		/* 分类成功回调 */
		classifyCallback(type) {
			this.getTreeData();

			if (type === 'add') {
        //新增分类完成之后，展开父节点显示刚新增的分类，若已展开节点则不做处理
        let code = this.add_parent_id;
        let flag = this.defaultShowNodes.some(item => item === code);
        !flag && this.defaultShowNodes.push(code);
        this.add_parent_id = '';

      }
		},

		/* 展开对应菜单 显示详情 */
		detailShowHandle({ UniqueCode, EdbInfoId,ClassifyId}) {
			let params = {
				code: UniqueCode,
				id: EdbInfoId,
				classifyId:ClassifyId
			};
			this.selectCurrentNode(params);
			this.select_classify = 0;
		},

		/* 操作指标后 */
		handleEdbCallBack(param) {
			this.getTreeData(param)
			//编辑后刷数据
			if(!param) {
				console.log('编辑后刷数据');
				this.detail_show_chart ? this.$refs.detailComponentRef.getDetail('updateImg') : this.$refs.detailComponentRef.getData();
			}
		},

		/* 更新指标 */
		updateEdbHandle: _.debounce(function() {
			this.loading = this.$loading({
				lock: true,
				target:'.edb-detail-wrapper',
				text: '刷新数据中...',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, 0.8)'
			});
			preDictEdbInterface.edbRefresh({
				EdbInfoId: this.select_id
			}).then(res => {
				this.loading.close();
				if(res.Ret !== 200) return
				this.$message.success(res.Msg)

				//更新完刷数据
				console.log('更新完刷数据');
				
				this.detail_show_chart ? this.$refs.detailComponentRef.getDetail('updateImg') : this.$refs.detailComponentRef.getData();
			})
		},300),

		/* 部分刷新 */
		updateEdbPartHandle: _.debounce(function() {
			this.loading = this.$loading({
				lock: true,
				target:'.edb-detail-wrapper',
				text: '刷新数据中...',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, 0.8)'
			});
			preDictEdbInterface.edbPartRefresh({
				EdbInfoId: this.select_id
			}).then(res => {
				this.loading.close();
				if(res.Ret !== 200) return
				this.$message.success(res.Msg)

				//更新完刷数据
				console.log('更新完刷数据');
				
				this.detail_show_chart ? this.$refs.detailComponentRef.getDetail('updateImg') : this.$refs.detailComponentRef.getData();
			})
		},300),

		/* 编辑指标 */
		editEdbHandle(type="") {
			preDictEdbInterface.edbDetail({
				EdbInfoId: this.select_id
			}).then(res => {
				if(res.Ret !== 200) return

				const { RuleList,EdbType,Source,CalculateList } = res.Data;
				
				// 原始指标
				if(EdbType === 1) {
					!type && this.$router.push({
						path:'/editpredictEdb',
						query:{
							id:this.select_id
						}
					})

					if(type === 'view') {
						this.showRules = RuleList;
						this.showFromEdbInfo = CalculateList[0];
						this.isShowRuleDialog=true};
				} else {
					//计算指标
					this.setComputedDialogForm(res.Data,type);
					this.computed_type =[47,48].includes(Source)?'joint': Source;
				}

			})
		},

		/* 查看指标 */
		viewNode() {
			this.editEdbHandle('view')
		},

		/* 计算指标回显 */
		setComputedDialogForm({Source,CalculateList,CalculateFormula,EdbInfoId,EdbName,Unit,Frequency,ClassifyId,MoveType,MoveFrequency,Calendar},type='') {
			//找到指标的父级
			let deep_arr = _.cloneDeep(this.treeData);
			const parentNodes = this.findParentNodeHandle(deep_arr,ClassifyId,'ClassifyId')
			//指标运算 or 其他计算类型指标
			if( Source === 31 ) {
				/* 回显指标和表单 */
				this.computedTit = '编辑计算指标';
				/* 依赖的指标列表 */
				this.calulateList = CalculateList.map(item => ({
					tag: item.FromTag,
					edb_name: item.FromEdbName,
					target: item.FromEdbInfoId,
					start_date: item.StartDate,
					end_date: item.EndDate
				}))
				/* 公式和表单 */
				this.calulateForm =  {
					edb_id:EdbInfoId,
					formula: CalculateFormula,
					menu: parentNodes.reverse(),
					targetName: EdbName,
					unit: Unit,
					frequency: Frequency,
					view: type === 'view'
				};
			} else  {
				if([47,48,50,56].includes(Source)){//拟合残差
					this.operationForm={
						edb_id:EdbInfoId,
						targetName: EdbName,
						frequency: Frequency,
						unit: Unit,
						menu: parentNodes.reverse(),
						view: type === 'view',
						source: Source,
						date: CalculateFormula,
						pre_edb: Source === 47 ? CalculateList.find(item => item.FromTag === 'A').FromEdbInfoId : '', //俺也不懂为什么这么定义都是江西老表的锅
						after_edb: Source === 47 ? CalculateList.find(item => item.FromTag === 'B').FromEdbInfoId : '',
						old_stay_edb: Source === 48 ? CalculateList.find(item => item.FromTag === 'A').FromEdbInfoId : '',
						concat_edb: Source === 48 ? CalculateList.find(item => item.FromTag === 'B').FromEdbInfoId : '',
						from_arr: CalculateList,
					}
					return
				}
				this.operationForm = {
					oldedb_id: CalculateList[0].FromEdbInfoId,
					oldEdb_name: CalculateList[0].FromEdbName,
					edb_id: EdbInfoId,
					targetName: EdbName,
					unit: Unit,
					menu: parentNodes.reverse(),
					frequency: Frequency,
					formula: CalculateFormula || '',
					view: type === 'view',
					moveType: MoveType,
					moveUnit: MoveFrequency,
					moveVal: Source === 46 ? CalculateFormula : '',
					calendar_type: Source === 49 ? Calendar : '',
				}
			}
		},

		/* 复制数据 */
		copyData() {
			preDictEdbInterface.edbDataInfo({
        EdbInfoId: this.select_id,
        CurrentIndex: 1,
				PageSize: 100000,
      }).then(res => {
				if(res.Ret !== 200) return

				const { DataList,PredictDataList } = res.Data.Item;

				let total_data = [...PredictDataList,...DataList];
				let str = '日期\t 值\n';
        total_data.forEach((item) => (str += `${item.DataTime}\t${item.Value}\n`));
        this.$copyText(str).then(
          (res) => {
            this.$message.success('已成功复制!');
          },
          (err) => {
            this.$message.error('复制失败!');
          }
        );
			})
		},

		/* 获取表格列表 */
		getPublicList() {
			preDictEdbInterface.edbList({
				CurrentIndex: this.public_page,
				PageSize: this.public_pages_size,
        ClassifyId: this.select_classify || 0,
        IsOnlyMe:this.isOnlyMe||false,
			}).then(res => {
				if(res.Ret !== 200) return

				this.publicHaveMove = res.Data
            ? this.public_page < res.Data.Paging.Pages
            : false;
          this.edbChartList = res.Data
            ? this.public_page === 1
              ? res.Data.List
              : [...this.edbChartList, ...res.Data.List]
            : [];
        this.edb_total = res.Data ? res.Data.Paging.Totals : 0;
			})
		},

			/* 加载更多 */
		loadMoreHandle: _.throttle(function() {
			let scrollTop = this.$refs.listRef.scrollTop;
      let clientHeight = this.$refs.listRef.clientHeight;
      let scrollHeight = this.$refs.listRef.scrollHeight;
			if(scrollTop + clientHeight >= scrollHeight-10 && this.publicHaveMove){
				this.public_page++;
				this.getPublicList();
			}
		},300),

		/* 切换中英文 */
		changeLangHandle: _.debounce(async function (lang){
			this.search_txt = '';
			this.currentLang = lang;
			await dataBaseInterface.setUserLang({
				ConfigCode: 'predict_edb_language',
				ConfigValue: lang === 'en' ? 'EN' : 'CN'
			})
		},200),

		/* 编辑英文 */
		openEnNameDia(info){
			this.formItemArray=[{
				label:'指标名称',
				value:info.EdbName,
				key:'EdbName',
				notEdit:true
			}]
			// 中文单位有 才能编辑英文单位
			if(info.Unit && info.Unit!='无'){
				this.formItemArray.push({
					label:'单位',
					value:info.Unit,
					key:'Unit',
					notEdit:true
				},
				{
					label:'英文指标名称',
					value:info.EdbNameEn,
					key:'EdbNameEn',
					placeholder:'请输入英文指标名称'
				},
				{
					label:'英文单位',
					value:info.UnitEn,
					key:'UnitEn',
					placeholder:'请输入英文单位'
				})
			}else{
				this.formItemArray.push({
					label:'英文指标名称',
					value:info.EdbNameEn,
					key:'EdbNameEn',
					placeholder:'请输入英文指标名称'
				})
			}

			this.setEnName = true
		},

		clickEdbNameHandle() {
			this.$refs.detailComponentRef.changeEnOptions();
		},

		updateEnName(item){
			let params={
				EdbInfoId: Number(this.select_id),
				...item
			}
			dataBaseInterface.edbInfoEditEn(params).then(res=>{
				if(res.Ret ==200){
					this.$message({
						message:res.Msg,
						type:"success"
					})
					this.detail_show_chart ? this.$refs.detailComponentRef.getDetail() : this.$refs.detailComponentRef.getData();
					this.setEnName = false
					this.getTreeData({
						code: this.select_node,
						id: this.select_id
					});
				}
			})
		},

		/* 打开计算弹窗 */
		addComputedHandler() {
			this.computedTit = '计算指标';
			this.calulateList = [];
			this.calulateForm = {};
			this.operationForm = {};
			this.isOpenComputed = true;
		},

		/* 选择计算类型 */
		changeComputedType(type) {
			let typeMapSource = {
				'toMonthSeason': 42,
				'accumulate': 65
			}
			this.computed_type = typeMapSource[type] || type;;
			this.isOpenComputed = false;
		},

		/* 新增计算指标回调 */
		addComputedCallBack(type, params) {
			this.computed_type = 0;
			this.computed_source = 1;
			
			this.showAssociateChart=false;
			this.showAssociateComputeData=false;
			type === 'add' ? this.getTreeData(params) : this.getTreeData();
			if(type === 'edit') {
				this.detail_show_chart ? this.$refs.detailComponentRef.getDetail() : this.$refs.detailComponentRef.getData();
			}
		},

		/* 重绘右侧区域宽度 */
    reloadRightWid() {
      let total_wid = $('.predict-edb-main')[0].offsetWidth;
      let left = $('#left')[0].offsetWidth;
      let rigtWid = total_wid - left - 20 + 'px';
      $('#right')[0].style.width = rigtWid;

    },
    //只看我的
    onlyMeHandler(){
      this.getTreeData()

			this.public_page = 1;
			this.$refs.listRef.scrollTop = 0;
      this.getPublicList();
    },
		//懒加载el-tree
		getLazyTreeData(node,resolve,maxLevel=3){
			if(node.level===0){
					resolve(this.treeData)
				}
				if(node.level>0&&node.level<=maxLevel){
					//获取对应层级的Child
					resolve(node.data.Children||[])
				}
				if(node.level===maxLevel){
					//调接口获取该分类下图表的数据
					preDictEdbInterface.classifyChartList({
						ClassifyId:node.data.ClassifyId,
						IsShowMe:this.isOnlyMe
					}).then(res=>{
						if(res.Ret===200){
							let arr=res.Data.EdbInfoList||[]
							arr=arr.map(item=>{
								return {
									...item,
									isLeaf:true
								}
							})
							resolve(arr)
						}else{
							resolve([])
						}
						this.changeTreeNode()
					})
				}
				if(node.level>maxLevel){
					resolve([])
				}
		},
		changeTreeNode(){
			this.$refs.treeRef.setCurrentKey(this.select_node);
			this.$nextTick(()=>{
				const _node = this.$refs.treeRef.getNode(this.select_node)
				this.dynamicNode = _node;
				this.dynamicNode&&this.resetNodeStyle(this.dynamicNode)
			})
		}
	},
	mounted() {
		const obj=sessionStorage.getItem('predictEdbTreeData')
		if(obj||this.$route.query.code){
			let code=obj?JSON.parse(obj).code:this.$route.query.code
			let id=obj?JSON.parse(obj).id:this.$route.query.id
			let classifyId=obj?JSON.parse(obj).classifyId:this.$route.query.classifyId
			this.getTreeData({code: code,id: Number(id),classifyId:Number(classifyId)})
		}else{
			this.getTreeData()
		}

		// 清除缓存数据
		setTimeout(() => {
			sessionStorage.setItem('predictEdbTreeData','')
		}, 1000);
		 
		this.getPublicList();

		window.addEventListener('resize', this.reloadRightWid);
	},
	destroyed() {
		window.removeEventListener('resize', this.reloadRightWid);
	}
}
</script>
<style lang='scss' scoped>
*{ box-sizing: border-box;}
$mini-font: 12px; $normal-font: 14px;
.predictEdb-container {
	.slide-icon {
		padding: 20px 0;
		/* display: block; */
		box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
		border-radius: 5px;
		cursor: pointer;
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		z-index: 99;
		&:hover {
			background-color: rgba(0, 0, 0, 0.05);
		}
		&.slide-left {
			right: 0;
		}
		&.slide-right {
			left: 0;
		}
	}
	.predict-edb-main {
		display: flex;

		.main-left {
			width: 400px;
			min-width: 380px;
			background: #fff;
			margin-right: 20px;
			border: 1px solid #ececec;
			border-radius: 4px;
			box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
			height: calc(100vh - 120px);
			overflow: hidden;
			position: relative;
			box-sizing: border-box;

			.datasheet_top {
				padding: 20px;
				background: #fff;
				border: 1px solid #ececec;
				box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
				margin-bottom: 20px;
				display: flex;
				align-items: center;
			}
			.search-cont {
				padding: 0 20px;
			}



			.tree-cont {
				padding: 0 20px 30px 20px;
				max-height: calc(100vh - 280px);
				overflow: auto;
			}
			.target_tree {
				color: #333;
				.custom-tree-node {
					display: flex !important;
					justify-content: space-between;
					align-items: center;
					display: block;
					flex: 1;
					.node_label {
						margin-right: 2px;
					}
					.el-icon-view {
						color: #409EFF;
						font-size: 18px;
						margin-left: 5px;
					}
				}
			}
			.noDepart {
				margin: 60px 0;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #409eff;
				font-size: 16px;
				cursor: pointer;
			}
			.move-btn {
				height: 100%;
				width: 4px;
				/* opacity: 0; */
				position: absolute;
				right: 0px;
				top: 0;
				&:hover {
				cursor: col-resize;
					/* background-color: orange */
				}
			}
		}

		.main-right {
			width: 80%;
			.edb-detail-wrapper {
				height: 100%;
				border: 1px solid #ececec;
				border-radius: 4px;
				box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
				overflow: auto;
				background: #fff;
				.detail-top {
					padding: 20px;
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 1px solid #ececec;
					.title { 
						font-size: 16px;
						&.disabled { color: #ccc; }
					}
					.action-ul {
						display: flex;
						li { margin: 0 10px; }
					}
				}
				.detail-wrap {
					position: relative;
					padding: 30px 20px;
					height: calc(100vh - 190px);
					.toggle-text {
						position: absolute;
						right: 20px;
						top: 40px;
						z-index: 2;
						display: flex;
						align-items: center;
					}
					/* min-height: 500px; */
				}
			}

			.sheet-list-cont {
				color: #333;
				.el-card .el-card__header,
				.el-card__body {
					padding: 10px;
				}
				.list-top {
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				.edbChartList-wrapper {
					margin-top: 10px;
					display: flex;
					flex-wrap: wrap;
					max-height: calc(100vh - 143px);
					overflow: hidden;
					overflow-y: auto;
					.drag-cont {
						width: 100%;
						display: flex;
						flex-wrap: wrap;
					}
					.dragShdow {
						box-shadow: 0 1px 8px rgba(64, 158, 255, 0.8);
						opacity: 0.5;
					}
					.sheet-item {
						.item-top {
							display: flex;
							justify-content: space-between;
							align-items: center;
							font-size: 16px;
							font-weight: 600;
						}
						.chart-img {
							width: 100%;
							height: 230px;
							object-fit: cover !important;
							cursor: pointer;
						}
						.item-bottom {
							margin-top: 10px;
							display: flex;
							justify-content: space-between;
							font-size: 12px;
							color: #666;
							.collected {
								color: #f00;
								cursor: pointer;
							}
							.join_txt {
								color: #409eff;
								cursor: pointer;
							}
						}
					}
				}
				.nodata {
					text-align: center;
				}
			}
		}

	}

	.computed-ul {
		max-height: 600px;
		overflow-y: auto;
		padding: 40px 92px;
		display: flex;
		flex-wrap: wrap;
		.cpmputed-li {
			width: 180px;
			padding: 19px 0;
			color: #409EFF;
			font-size: 16px;
			background:#ECF5FF;
			border-radius: 8px;
			border: 1px solid #B3D8FF;
			text-align: center;
			cursor: pointer;
			margin-right: 65px;
			margin-bottom: 55px;
			&:nth-child(3n) {
				margin-right:0;
			}
			&:hover {
				background: #409EFF;
				color: #fff;
			}
			&.act {
				background: #409EFF;
				color: #fff;
			}
		}
	}
}	
</style>

<style lang="scss">
.predictEdb-container {
	.label-input .el-input__inner {
		height: 25px;
		line-height: 25px;
		padding: 0 10px;
	}

	.el-dialog--center .el-dialog__body {
		padding: 40px 20px 30px 60px;
	}

	.el-tree__drop-indicator{
		height:3px;
		background-color:#409EFF;
	}
	.el-tree-node__content {
		margin-bottom: 14px !important;
	}
	.el-tree-node__children {
		.el-tree-node {
			/* margin-bottom: 8px !important; */
			margin-bottom: 0px !important;
			padding-left: 18px;
		}
		.el-tree-node__content {
			margin-bottom: 5px !important;
			padding-left: 0 !important;
		}
	}
	.expanded.el-icon-caret-right:before {
		content: url('../../assets/img/set_m/down.png') !important;
	}
	.el-icon-caret-right:before {
		content: url('../../assets/img/set_m/slide.png') !important;
	}
	.el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
		content: '' !important;
	}
	.el-tree-node__expand-icon.expanded {
		-webkit-transform: rotate(0deg);
		transform: rotate(0deg);
	}
	.el-tree-node.is-current > .el-tree-node__content {
		background-color: #f0f4ff !important;
	}
	.el-tree-node__content {
		padding-right: 10px !important;
	}

	.dialog-computed {
		.el-dialog__header {
			background-color: #fff;
			.el-dialog__close {
				color: #333;
			}
		}
	}	
}
</style>