<template>
	<div class="database_container">
		<div class="database_top">
			<div>
				<el-button v-permission="permissionBtn.edbDataPermission.edbData_addEdb"
					type="primary" @click="addHandler">添加指标</el-button>
				<el-button v-permission="permissionBtn.edbDataPermission.edbData_calcuEdb"
					type="primary" @click="addComputedHandler">计算指标</el-button>
				<el-button v-permission="permissionBtn.edbDataPermission.edbData_replaceEdb"
					type="primary" @click="replaceEdbHandler">替换指标</el-button>
				<el-button v-permission="permissionBtn.edbDataPermission.edbData_codeRun"
					type="primary" @click="$router.push({path: '/codecount'})">代码运算</el-button>
				<el-button v-permission="permissionBtn.edbDataPermission.edbData_dataAdjust"
					type="primary" @click="$router.push({path: '/adjustdata'})">数据调整</el-button>
				<el-button v-permission="permissionBtn.edbDataPermission.edbData_batchUpdate"
					type="primary" plain @click="updateHandler">一键更新</el-button>
			</div>
			<div class="top-right">

				<change-lang v-permission="permissionBtn.edbDataPermission.edbData_switchEn"
					:lang="currentLang" style="height: 32px;" @changeLang="changeLanguage"/>

				<el-select
					v-model="search_txt"
					v-loadMore="searchLoad"
					ref="searchRef"
					:filterable="!search_txt"
					remote
					clearable
					placeholder="指标ID/指标名称"
					style="width: 400px;margin-left:10px;"
					:remote-method="searchHandle"
					@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="currentLang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
						:value="item.EdbInfoId"
					>
					</el-option>
				</el-select>
			</div>
		</div>
		<div class="database-label">
			<edb-label-list 
				:currentLang="currentLang"
				:labelList="labelList"
				:activeLabelId="select_node"
				@clickLabel="changeCurrentLabel"
				@deleteLabel="deleteLabel"
				@moveLabel="({oldIndex,newIndex})=>{labelList[oldIndex] = labelList.splice(newIndex, 1, labelList[oldIndex])[0];}"
				/>
		</div>
		<div class="database_main box" id="box" v-if="showData">
			<div class="main-left left" id="left">
				<div class="tree-cont">
					<el-tree
						ref="menuTree"
						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(node, data)"
							/>
							<span 
								@dblclick.stop="editNodeLabel(node, data)" 
								v-else 
								class="text_oneLine node_label" 
								:style="`width:${(select_node === data.UniqueCode && node.Nodewidth) || ''}`"
								:id="`node${data.UniqueCode}`"
							>
								<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.Button.OpButton不变；如果是指标，再加上checkPermissionBtn判断-->
								<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.EdbCode
										?(data.Button.OpButton&&permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_edit))
										:(data.Button.OpButton)"
								/>
								<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"
								/>
								<i class="el-icon-view" v-if="data.EdbType===2&&![58,59,67,68].includes(data.Source)" @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="CanOpClassify">
						<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>
			</div>
			<!-- 指标关联图模块 -->
			<div class="main-right right" id="right" style="background:transparent;border:none;box-shadow:none" v-if="showAssociateChart">
				<dataAssociateChart :edbInfoId="selected_edbid"></dataAssociateChart>
			</div>
			<div class="main-right right" id="right" style="background:transparent;border:none;box-shadow:none" v-if="showAssociateComputeData">
				<dataAssociateComputeData :edbInfoId="selected_edbid"></dataAssociateComputeData>
			</div>
			<!-- <div class="main-right right" id="right" v-show="!showAssociateChart&&!showAssociateComputeData">
				<el-table
				:data="tableData"
				style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);"
				class="firstColumTable"
				border>
					<el-table-column
						v-for="item in tableColumsOne"
						:key="item.label"
						:width="item.widthsty"
						:min-width="item.minwidthsty"
						align="center"
					>
						<template slot="header" slot-scope="scope">
							<div class="chartEn-mark" style="top: -10px;" v-show="scope.$index ==0 && tableData[0] && tableData[0].IsEnEdb" >En</div>
							<span>{{item.label}}</span>
						</template>	
						<template slot-scope="scope">
							<span v-show="currentLang=='ch'">{{ scope.row[item.key] }}</span> 
							<span v-show="currentLang=='en'">{{scope.row[item.enKey||item.key] || scope.row[item.key]}}</span>
						</template>
					</el-table-column>
				</el-table>
				<el-table
				:data="tableData"
				style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);"
				border>
					<el-table-column
						v-for="item in tableColumsTwo"
						:key="item.label"
						:label="item.label"
						:width="item.widthsty"
						:min-width="item.minwidthsty"
						align="center"
					>
						<template #header>
							<span>{{ item.label }}</span>
						</template>
						<template slot-scope="scope">
							<span>{{ scope.row[item.key] }}</span>
						</template>
					</el-table-column>
					<el-table-column
						width="260"
						align="center"
						label="操作"
					>
						<template slot-scope="scope">
							<el-button v-permission="permissionBtn.edbDataPermission.edbData_update"
								size="mini" type="text" @click="refreshTargetHandle" >更新</el-button>
							<el-button 
								v-permission="permissionBtn.edbDataPermission.edbData_edit"
								size="mini" 
								type="text" 
								:disabled="!scope.row.Button.OpButton"
								@click="editNode({
									level: 4,
									parent: {
										data: { ClassifyId:edb_levels[2].ClassifyId },
										parent:{
											data: { ClassifyId:edb_levels[1].ClassifyId },
											parent:{
												data: { ClassifyId:edb_levels[0].ClassifyId },
											}
										},
									}
								},scope.row)"
								>编辑</el-button>
							<el-button size="mini" type="text" @click.stop="reCalculateHandler" v-if="scope.row.EdbType===2" :loading="calculateLoading">重新计算</el-button>
							<el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_toImgs)"
								size="mini" type="text" @click.stop="createChartHandle(scope.row.EdbInfoId)">一键成图</el-button>
							<el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_copyData)"
								size="mini" type="text" @click="copyCode">复制数据</el-button>
							<el-button size="mini" type="text"
							v-if="scope.row.EdbType===2&&permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_edbSource)" @click="isLookHistory=true;lookEdbId=selected_edbid">指标溯源</el-button>
							
							<el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_enNameSetting)"
								size="mini" type="text" @click="openEnNameDia">设置英文名称</el-button>
							<el-button size="mini" type="text" @click.stop="updateNewestDataHandle" 
							v-if="scope.row.Button.InsertNewDataButton&&permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_newestValue)" >{{scope.row.DataInsertConfig.Date?'编辑最新值':'添加最新值'}}</el-button>
							<el-button size="mini" type="text" @click.stop="refreshBaseHandler" 
								v-if="scope.row.EdbType===1&&permissionBtn.checkPermissionBtn(permissionBtn.edbDataPermission.edbData_refreshAll)" :loading="refreshLoading">全部刷新</el-button>
						</template>
					</el-table-column>
					<div slot="empty" style="padding: 50px 0 320px;">
						 <tableNoData :text="defaultWarn"/>
					</div>
				</el-table>
				<ul 
				class="value-ul" 
				ref="valueUl" 
				@scroll="scrollHandle" 
				v-show="showTable&&dataList.length">
					<li
						class="value-item"
						v-for="item in dataList"
						:key="item.EdbDataId"
					>
						<span class="value-label">
							<i class="new-tag" v-if="tableData[0].LatestDate===item.DataTime"></i>
							{{item.DataTime}}
						</span>
						<span :class="['value-label',{'predict-act': tableData[0].DataInsertConfig.Date===item.DataTime}]" style="min-width:200px;text-align:center;">{{item.Value}}</span>
					</li>
					<li class="nodata value-item" v-if="!dataList.length">暂无数据</li>
				</ul>
			</div> -->
			<!-- 指标图表列表 -->
			<div class="main-right right list" id="right" v-show="!showAssociateChart&&!showAssociateComputeData&&!selected_edbid">
				<p>共{{Total||0}}个指标</p>
				<div class="list-wrap" ref="listRef" @scroll="loadMoreHandle" v-if="Total">
					<div class="list-item" v-for="item in chartList" :key="item.EdbInfoId">
						<div class="header">
							<span v-show="currentLang=='ch'">{{ item.EdbName }}</span> 
							<span v-show="currentLang=='en'">{{ item.EdbNameEn || item.EdbName }}</span>
						</div>
						<div class="image" @click="selected_edbid = item.EdbInfoId">
							<img :src="item.ChartImage" alt=""/>
						</div>
						<div class="info">
							创建时间：{{item.CreateTime.substring(0,10)}}
						</div>
					</div>
					<p style="height: 40px;line-height:40px;width: 100%;"></p>
				</div>
				<div v-if="!Total" class="nodata">
					<tableNoData text="暂无指标"/>
				</div>
			</div>
			<!-- 指标详情 -->
			<div class="main-right right detail" id="right" v-show="!showAssociateChart&&!showAssociateComputeData&&selected_edbid">
				<div class="header">
					<el-tabs v-model="activeTab">
						<el-tab-pane label="走势图" name="走势图"></el-tab-pane>
						<el-tab-pane label="数据详情" name="数据详情"></el-tab-pane>
					</el-tabs>
					<div class="edb-tool">
						<el-button v-if="isEdbBtnShow('update')"
							size="mini" type="text" @click="refreshTargetHandle" >刷新</el-button>
						<el-button v-if="isEdbBtnShow('edit')"
								size="mini" 
								type="text" 
								:disabled="!tableData[0]?tableData[0].Button.OpButton:false"
								@click="editNode({
									level: 4,
									parent: {
										data: { ClassifyId:edb_levels[2].ClassifyId },
										parent:{
											data: { ClassifyId:edb_levels[1].ClassifyId },
											parent:{
												data: { ClassifyId:edb_levels[0].ClassifyId },
											}
										},
									}
								},tableData[0])"
							>编辑</el-button>
						<el-button v-if="tableData[0]?tableData[0].EdbType===2:false"
							size="mini" type="text" @click.stop="reCalculateHandler" :loading="calculateLoading">重新计算</el-button>
						<!-- 走势图本身就是一键成图 -->
						<!-- <el-button v-if="isEdbBtnShow('toImg')"
							size="mini" type="text" @click.stop="createChartHandle(scope.row.EdbInfoId)">一键成图</el-button> -->
						<el-button v-if="isEdbBtnShow('copyData')"
							size="mini" type="text" @click="copyCode">复制数据</el-button>
						<el-button v-if="tableData[0]?tableData[0].EdbType===2:false&&isEdbBtnShow('toSource')"
							size="mini" type="text" @click="isLookHistory=true;lookEdbId=selected_edbid">指标溯源</el-button>
						<el-button v-if="isEdbBtnShow('setEn')"
							size="mini" type="text" @click="openEnNameDia">设置英文名称</el-button>
						<el-button v-if="tableData[0]?tableData[0].Button.InsertNewDataButton:false&&isEdbBtnShow('newValue')"
							size="mini" type="text" @click.stop="updateNewestDataHandle" >{{tableData[0]?tableData[0].DataInsertConfig.Date:''?'编辑最新值':'添加最新值'}}</el-button>
						<el-button v-if="tableData[0]?tableData[0].EdbType===1:false&&isEdbBtnShow('refreshAll')"
							size="mini" type="text" @click.stop="refreshBaseHandler"  :loading="refreshLoading">全部刷新</el-button>
					</div>
				</div>
			</div>
		</div>
		<!-- 输入英文指标弹窗 -->
		<set-en-name-dia :isOpenDialog="setEnName" @cancel="setEnName=false" 
		:formData="formItemArray" @updateEnName="updateEnName" cType="ebd" />

		<!-- 目录弹窗 -->
		<openDialog 
			:isOpenDialog="isOpenDialog"
			:title="dialog_title"
			:formData="dialogForm"
			@closeDia="isOpenDialog=false"
			@sucessCallback="sucessCallback"
		/>
		<!-- 指标弹窗 -->
		<addTargetDiaBase
			ref="addTargetDiaBase"
			:isAddTarget="isAddTarget"
			@cancelHandle="isAddTarget = false"
		/>
		<!-- 完善指标信息 -->
		<completeTargetDia
			:isOpenDialog="isComplete"
			@cancel="cacelCompleteCallback"
			:params="add_params"
			@addTargetCallback="addTargetCallback"
		/>
		<!-- 计算指标弹窗 -->
		<computedDialog
			:isOpenComputed="computed_type === 4"
			:title="computedTit"
			:calulateForm="calulateForm"
			:calulateList="calulateList"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
			@lookHistory="id => {isLookHistory=true;lookEdbId=id;}"
		/>
		<!-- 计算弹窗控制 -->
		<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="920px"
		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>
		<!-- 转月值 同比 同差 平均值弹窗 -->
		<operationDialog
			:isOperation="([5,6,7,8,12,13,14,22,35,51,52,61,62,63].includes(computed_type) || (computed_type===40&&operationForm.view)) && 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"
		/>
		<!-- 一键成图弹窗 -->
		<create-chart
			:isCreateChart="isCreateChart"
			:edbid="selected_edbid"
			:chartLang="currentLang"
			ref="createChart"
			@close="isCreateChart = false"
			@editEnName="openEnNameDia"
		/>

		<!-- 一键更新弹窗 -->
		<update-dialog
			:isUpdate="isUpdate"
			@cancel="isUpdate = false"
		/>

		<!-- 替换指标弹窗 -->
		<replace-dialog
			:isShow="isReplaceDia"
			@cancel="isReplaceDia = false"
		/>

		<!-- 拼接弹窗 -->
		<joint-target-dia
			:isShow="computed_type === 'joint'"
			:params="operationForm"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
		/>

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

		<!-- 批量计算弹窗 -->
		<batchComputedDialog
			:isBatchComputed="[6,7,8,12,13,14,5,61,62,63].includes(computed_type) && computed_source===2"
			:type="computed_type"
			@cancel="computed_type=0"
			@addCallBack="addComputedCallBack"
			@openPrev="isOpenComputed=true"
			@lookHistory="id => {isLookHistory=true;lookEdbId=id;}"
			@changeSource="changeComputedType"
		/>

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

		<!-- 添加最新值弹窗 -->
		<updateNewestDataDia
			:isShow.sync="isUpdateNewestData"
			:edbinfo="tableData[0]"
			:dataList="dataList"
			@success="initGetData"
		/>

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

	</div>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import { computedTypes,computedBatchTypes,formulaTip } from './databaseComponents/util';

import openDialog from './databaseComponents/openDialog';
import addTargetDiaBase from './databaseComponents/addTargetDiaBase';
import completeTargetDia from './databaseComponents/completeTargetDia'
import computedDialog from './databaseComponents/computedDialog';
import operationDialog from './databaseComponents/operationDialog';
import createChart from './databaseComponents/createChart';
import updateDialog from './databaseComponents/updateDialog';
import replaceDialog from './databaseComponents/replaceDialog';
import jointTargetDia from './databaseComponents/jointTargetDia';
import changeLang from "./components/changeLang.vue"
import setEnNameDia from "./components/setEnNameDia.vue"
import dataAssociateChart from './databaseComponents/dataAssociateChart.vue'
import dataAssociateComputeData from './databaseComponents/dataAssociateComputeData.vue'
import fittingResidueDia from './databaseComponents/fittingResidueDia.vue';
import batchComputedDialog from './databaseComponents/batchComptedDialog.vue';
import diffusionIndexDialog from './databaseComponents/diffusionIndexDia.vue';
import updateNewestDataDia from './databaseComponents/updateNewestDia.vue';
import EdbLabelList from '@/components/edbLabelList.vue';
export default {
	name: '',
	components: { 
		openDialog, 
		addTargetDiaBase,
		completeTargetDia,
		computedDialog,
		operationDialog,
		createChart,
		updateDialog,
		replaceDialog,
		jointTargetDia,
		changeLang,
		setEnNameDia,
		dataAssociateChart,
		dataAssociateComputeData,
		fittingResidueDia,
		batchComputedDialog,
		diffusionIndexDialog,
		updateNewestDataDia,
		EdbLabelList
	},
	directives: {
    drag(el, bindings) {
      el.onmousedown = function(e) {
				var init = e.clientX;
				// console.log(init);
				var box = $("#box")[0]
				// console.log(box.clientWidth)
				let total_wid = box.offsetWidth
        var left = $("#left")[0];
        var right = $("#right")[0];
        var initWidth = left.offsetWidth;
        document.onmousemove = function(e) {
          var end = e.clientX;
					// console.log(total_wid,initWidth,end);
					if(end > 310){
            var newWidth = end - init + initWidth;
						// right.style.width = total_wid-end+80 +'px'
						right.style.width = total_wid - newWidth + 'px'
            left.style.width = newWidth + "px";
          }else{
            end = 350;
            // 最小宽度300
            left.style.width = 300 + "px";
						// right.style.width = total_wid-300-20 +'px'
          }
        };
        document.onmouseup = function() {
          document.onmousemove = document.onmouseup = null;
					e.releaseCapture && e.releaseCapture();
        };
				e.setCapture && e.setCapture();
				return false;
      };
    }
  },
	data() {
		return {
			showData: false,
			search_txt: '', //搜索词
			searchOptions:[],//搜索到的筛选列表
			treeData: [], //树形数据
			defaultShowNodes:[], //默认展开的节点
			defaultProp: {
				label: 'ClassifyName',
				children: 'Children',
				isLeaf:'isLeaf'
			},//树结构配置项
			tableData: [],
			loading:null,
			showTable:false,
			page_no: 1,
			/*表格列 */
			tableColumsOne: [
				{
					label: '指标ID',
					key: 'EdbCode',
					minwidthsty: '150px'
				},
				{
					label: '指标名称',
					key: 'EdbName',
					enKey:'EdbNameEn',
					inputTip:'点击输入英文指标名称',
					minwidthsty: '200px'
				},
				{
					label: '频度',
					key: 'Frequency',
					enKey:'FrequencyEn',
					widthsty: '100px'
				},
				{
					label: '单位',
					key: 'Unit',
					enKey:'UnitEn',
					inputTip:'英文单位',
					// minwidthsty: '50px'
					widthsty: '100px'
				},
				{
					label: '数据来源',
					key: 'SourceName',
					widthsty: '160px'
				},
			],
			tableColumsTwo: [
				{
					label: '指标目录',
					key: 'Menu',
					minwidthsty: '117px',
				},
				{
					label: '起始时间',
					key: 'StartDate',
					minwidthsty: '115px',
				},
				{
					label: '更新时间',
					key: 'ModifyTime',
					minwidthsty: '118px',
				},
				{
					label: '添加人',
					key: 'SysUserRealName',
					widthsty: '100px',
				}
			],
			haveMore: true,
			selected_edbid: 0,//选中的指标id
			dataList: [],//指标数值
			new_label: '',//新的节点label值
			select_node:'',//当前选中的节点
			/* 新增编辑目录弹窗 */
			isOpenDialog:false,
			dialog_title: '',
			dialogForm:{
				level:''
			},
			/* 新增指标弹窗 */
			isAddTarget: false,
			/* 完善信息 */
			isComplete:false,
			add_params:{},
			defaultWarn:'请在左侧选择指标',//缺省文字
			/* 计算指标弹窗 */
			isOpenComputed:false,
			computedTit:'',
			calulateForm:{},
			calulateList:[],
			computed_type:0,//打开弹窗的类型
			operationForm:{},
			dynamicNode:null,
		
			edb_source:0,//指标来源 显示计算按钮
			calculateLoading: false,//计算指标刷新loading
			refreshLoading: false,//基础指标刷新loading
			/* 一键成图弹窗 */
			isCreateChart: false,
			/* 一键更新弹窗 */
			isUpdate:false,
			/* 替换指标弹窗 */
			isReplaceDia: false,
			/* 拼接指标弹窗 */
			isJoint: false,

			search_page: 1,
			search_have_more: false,
			current_search:'',
			currentLang:'ch', // 语言 ch 中文 en 英文
			// -----------------设置英文指标弹窗
			setEnName:false,
			// 传入的formItem所需内容
			formItemArray:[],
			// 在哪里更新的英文指标 table(表格上) chart(图表里)
			updateType:'table',
			// ----------------------
			edb_levels:[],//指标的父级分类id

			showAssociateChart:false,//显示指标关联的图
			showAssociateComputeData:false,//显示指标关联的引用计算指标

			tips: formulaTip,//公式说明

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

			//添加最新值弹窗
			isUpdateNewestData: false,

			/* 查看历史弹窗 */
			isLookHistory: false,
			lookEdbId: 0,
			labelList:[],//标签列表

			CanOpClassify: false,

			select_classifyId:0,//指标分类id
			PageSize:15,
			CurrentIndex:1,
			Total:0,
			IsListEnd:false,//是不是到底了
			chartList:[],

			activeTab:'走势图'
		};
	},
	watch: {
		selected_edbid(newval) {
			if(!newval) {
				this.tableData = [];
				this.dataList = [];
				this.defaultWarn = '请在左侧选择指标';
			}else {
				this.initGetData();
			}
		},
		/* 选中搜索指标 展开目录 选中指标 展示数据 */
		search_txt(newval) {
			if (newval) {
				let [search_obj] = this.searchOptions.filter(
					(item) => item.EdbInfoId === newval
				);
				
				this.page_no = 1;
				this.$refs.valueUl&&(this.$refs.valueUl.scrollTop = 0);
				// 查找图表的父级code
				//this.defaultShowNodes = this.findParentNodeHandle(this.treeData,search_obj.ClassifyId);
				this.select_node = search_obj.UniqueCode;
				this.selected_edbid = newval;

				//滚动到高亮节点位置
				/* setTimeout(() => {
					this.$refs.menuTree.setCurrentKey(this.select_node);
					let node = document.getElementById(`node${this.select_node}`);
					let parent = document.getElementsByClassName('tree-cont')[0];

					if(node.offsetTop > parent.offsetHeight) {
						parent.scrollTop =  node.offsetTop - parent.offsetHeight/2
					}
				},400) */
			}
		},
		select_classifyId(newval){
			if(this.$refs.listRef) this.$refs.listRef.scrollTop = 0;
			if(newval){
				this.CurrentIndex = 1
				this.getEdbChartList()
			}
		}
	},
	computed: {
			/* 计算弹窗控制 */
		computedTypes() {
			return this.computed_source===1 ? computedTypes : computedBatchTypes;
		},
		role() {
			let role = localStorage.getItem('Role') || '';
			if (['rai_researcher', 'ficc_researcher', 'researcher','ficc_seller','rai_seller','seller'].includes(role)) {
				return 'researcher'
			}else if(['rai_admin','ficc_admin'].includes(role)) {
				return 'admin'
			}
			else {
				return role;
			}
		},
		/* 登录角色id */
		roleId() {
			let id = parseInt(localStorage.getItem('AdminId'));
			return id;
		},
	},
	methods: {
		//控制指标详情操作按钮
		isEdbBtnShow(type){
			const {edbDataPermission,checkPermissionBtn}=this.permissionBtn
			const BtnMap = {
				'update':edbDataPermission.edbData_update,
				'edit':edbDataPermission.dbData_edit,
				'toImg':edbDataPermission.edbData_toImgs,
				'copyData':edbDataPermission.edbData_copyData,
				'toSource':edbDataPermission.edbData_edbSource,
				'setEn':edbDataPermission.edbData_enNameSetting,
				'newValue':edbDataPermission.edbData_newestValue,
				'refreshAll':edbDataPermission.edbData_refreshAll,
			}
			return checkPermissionBtn(BtnMap[type])
		},
		/* 获取树分类数据 */
		getTreeData(params) {
			
			dataBaseInterface.menuListV3().then(res=>{
				if(res.Ret===200){
					const arr=res.Data.AllNodes || []
					this.treeData=arr.map(item=>{
						return {
							...item,
							isLeaf:item.Children.length?false:true
						}
					})
					this.CanOpClassify = res.Data.CanOpClassify;
					this.currentLang = res.Data.Language === 'EN' ? 'en' : 'ch';
					this.setLangIntoStore()
					this.showData = true;
					/* 处理树展开和选中图表 */
					params && this.selectCurrentNode(params);
					!params && this.select_node && this.$refs.menuTree.setCurrentKey(this.select_node);
				}
			})
		},
		/* 获取最新的指标 默认展示 */
		getNewTargetList: _.throttle(function() {
			dataBaseInterface.targetNew().then(res => {
				if(res.Ret === 200) {
					/* 默认选中 默认指标id */
						this.select_node = res.Data ? res.Data.UniqueCode : '';
						this.selected_edbid = res.Data ? res.Data.EdbInfoId : 0;
						this.getTreeData();
				}
			})
		}),
		/* 获取指标数据 */
		getDataList: _.throttle(function(type) {
			dataBaseInterface.targetList({
				PageSize: 20,
				CurrentIndex: this.page_no,
				EdbInfoId: this.selected_edbid,
				// KeyWord: this.search_txt,
			}).then(res => {
				if(res.Ret === 200) {
					this.showTable = true;
					if(res.Data) {
						// res.Data.Item.ModifyTime = res.Data.Item.ModifyTime.substr(0,10);
						let classify_arr = res.Data.ClassifyList || [];
						let str = '';
						classify_arr.length && classify_arr.reverse().map((item) => str += item.ClassifyName + '/');
						this.edb_levels = classify_arr;
						this.$set(res.Data.Item,'Menu',str);
						this.tableData = [res.Data.Item] || [];
						this.edb_source = res.Data.Item.Source;
						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);
						
						//将指标添加进标签列表中
						const {EdbNameEn,EdbName,EdbInfoId,UniqueCode,ClassifyId}=res.Data.Item
						this.addLabel({code:UniqueCode,id:EdbInfoId,classifyId:ClassifyId,EdbName,EdbNameEn})
						this.defaultShowNodes=this.findParentNodeHandle(this.treeData,ClassifyId)
						//设置tree高亮
						this.$refs.menuTree.setCurrentKey(UniqueCode);

					}else {
						this.tableData = [];
						this.dataList = [];
						this.defaultWarn = type=== 'search' ? '未搜索到该指标' : '请在左侧选择指标'

						this.$refs.menuTree.setCurrentKey(null)
					}
					if(type==='refresh') {
						this.$refs.valueUl.scrollTop = 0;
					}
					this.$nextTick(()=>{
						const _node = this.$refs.menuTree.getNode(this.select_node)
						this.dynamicNode = _node;
						this.dynamicNode&&this.resetNodeStyle(this.dynamicNode)
						//滚动到高亮位置
						setTimeout(() => {
							let node = document.getElementById(`node${this.select_node}`)||{}
							let parent = document.getElementsByClassName('tree-cont')[0];
							if(node.offsetTop > parent.offsetHeight) {
								parent.scrollTop =  node.offsetTop - parent.offsetHeight/2
							}
						},400)
					})
					
				}
			})
		}),
		//获取指标图表列表
		getEdbChartList(){
			dataBaseInterface.getEdbChartList({
				PageSize:this.PageSize,
				CurrentIndex:this.CurrentIndex,
				ClassifyId:this.select_classifyId,
			}).then(res=>{
				if(res.Ret!==200) return
				if(res.Data){
					this.chartList = this.CurrentIndex===1?res.Data.List:[...this.chartList,...res.Data.List]
					this.Total = res.Data.Paging.Totals||0
					this.IsListEnd = !(this.CurrentIndex<res.Data.Paging.pages)
				}


			})
		},
		//指标图表列表-加载更多
		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.IsListEnd){
				this.CurrentIndex++;
				this.getEdbChartList();
			}
			},300),
		/* 搜索 */
		searchHandle(query) {
			this.search_page = 1;
			this.current_search = query;
			this.searchApi(this.current_search)
		},

		searchApi(query,page=1) {
			dataBaseInterface.targetSearchByPage({
				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);
					
			})
		},

		/* 聚焦获取当前检索 */
		inputFocusHandle(e) {
			this.search_page = 1;
			this.current_search = e.target.value;
			this.searchApi(this.current_search);
		},

		searchLoad() {
			if(!this.search_have_more) return;
			this.searchApi(this.current_search,++this.search_page);
		},

		/* 存储中英文状态 */
		setLangIntoStore() {
			this.$store.commit('edb/SET_LANG',this.currentLang)
		},

		/* 数值滚动加载 */
		scrollHandle: _.throttle(function() {
			let scrollTop = this.$refs.valueUl.scrollTop;
      let clientHeight = this.$refs.valueUl.clientHeight;
      let scrollHeight = this.$refs.valueUl.scrollHeight;
      console.log('scrollTop:',scrollTop)
      console.log('clientHeight:',clientHeight)
      console.log('scrollHeight:',scrollHeight)
			if(scrollTop + clientHeight >= scrollHeight-10 && this.haveMore){
				this.page_no ++;
				this.getDataList();
			}
		},200),
		/* 切换中英文 */
		changeLanguage: _.debounce(async function (lang){
			this.search_txt = '';
			this.currentLang = lang;
			await dataBaseInterface.setUserLang({
				ConfigCode: 'edb_language',
				ConfigValue: lang === 'en' ? 'EN' : 'CN'
			})

			this.setLangIntoStore()
		},200),
		// 打开 编辑英文名称弹窗
		openEnNameDia(type='table'){
			this.updateType = type
			this.formItemArray=[{
				label:'指标名称',
				value:this.tableData[0].EdbName,
				key:'EdbName',
				notEdit:true
			}]
			// 中文单位有 才能编辑英文单位
			if(this.tableData[0].Unit && this.tableData[0].Unit!='无'){
				this.formItemArray.push({
					label:'单位',
					value:this.tableData[0].Unit,
					key:'Unit',
					notEdit:true
				},
				{
					label:'英文指标名称',
					value:this.tableData[0].EdbNameEn,
					key:'EdbNameEn',
					placeholder:'请输入英文指标名称'
				},
				{
					label:'英文单位',
					value:this.tableData[0].UnitEn,
					key:'UnitEn',
					placeholder:'请输入英文单位'
				})
			}else{
				this.formItemArray.push({
					label:'英文指标名称',
					value:this.tableData[0].EdbNameEn,
					key:'EdbNameEn',
					placeholder:'请输入英文指标名称'
				})
			}

			this.setEnName = true
		},
		updateEnName(item){
			let params={
				EdbInfoId: Number(this.selected_edbid),
				...item
			}
			dataBaseInterface.edbInfoEditEn(params).then(res=>{
				if(res.Ret ==200){
					this.$message({
						message:res.Msg,
						type:"success"
					})
					/* this.tableData[0].EdbNameEn = params.EdbNameEn
					this.tableData[0].UnitEn = params.UnitEn
					// 判断图表英文名称和英文单位是否都有，都有需要打上 英文标记
					console.log(this.tableData[0].EdbNameEn,this.tableData[0].UnitEn);
					if(this.tableData[0].EdbNameEn && (this.tableData[0].UnitEn || this.tableData[0].Unit == '无')){
						this.tableData[0].IsEnEdb=true
					}else{
						this.tableData[0].IsEnEdb=false
					} */
					this.getTreeData()
					this.getDataList()
					if(this.updateType=='chart'){
						// 重绘图表，刷新数据
						this.$refs.createChart.getEdbData()
					}
					this.setEnName = false
				}
			})
		},
		/* 新增指标 */
		addHandler() {
			this.isAddTarget = true;
		},
		/* 完善指标信息 */
		completeTargetHandle(params) {
			this.add_params = params;
			this.isComplete = true;
		},
		/* 新增指标成功回调 */
		addTargetCallback(params) {
			this.$refs.addTargetDiaBase.init();
			this.isComplete = false;
			this.isAddTarget = false;
			this.getTreeData(params);
			this.changeTreeNode()
			// this.getNewTargetList();
		},
		/* 取消新增回调 */
		cacelCompleteCallback() {
			this.isComplete = false
			this.add_params = {}
		},
		/* 节点变化时 */
		nodeChange(data,node) {
			this.dynamicNode = node;
			this.search_txt = '';
			this.showAssociateChart=false
			this.showAssociateComputeData=false
			// this.page_no = 1;
			// this.$refs.valueUl.scrollTop = 0;
			this.select_classifyId = !data.EdbInfoId?data.ClassifyId:0;
			this.select_node = data.UniqueCode;
			this.selected_edbid = data.EdbInfoId;
			this.resetNodeStyle(node);
			
			
		},
		resetNodeStyle: _.debounce(function(node) {
			const tree = $('.target_tree')[0];
			let width = tree.offsetWidth;
			console.log(width)
			// let label_wid = width > 500 ? 'auto' : (width <= 300 && width < 360) ?  100 : 0.7*width;
			let label_wid =
				width > 500
					? 'auto'
					: width <= 260
					? 80
					: 0.5 * width;
			this.$set(node, 'Nodewidth', label_wid + 'px');
		},200),
		/* 双击label出现input修改框 */
		editNodeLabel(node, data) {
			//目录名称可以双击修改 指标不能
			if(!data.EdbCode && this.role === 'admin') {
				this.$set(data,'isEdit',true)
				this.new_label = data.ClassifyName;
				this.$nextTick(() => {
					this.$refs.editVal.focus();
				});
			}
		},
		/* input失去焦点恢复node 修改最新的值*/
		changeValue(node, data) {
			if(this.new_label) {
				this.$set(data,'isEdit',false)
				this.new_label !== data.ClassifyName && dataBaseInterface.nodeEdit({
						ClassifyId: data.ClassifyId,
						ClassifyName: this.new_label
					}).then(res => {
						if(res.Ret === 200) {
							this.getTreeData();
						}
					})
			}else {
				this.$message.warning('名称不能为空')
			}
		},
		/* 添加一级目录 */
		addLevelOneHandle() {
			this.dialog_title = '添加';
			this.dialogForm = {
				level_1: '',
				parent_id: '',
				level: 0
			}
			this.isOpenDialog = true;
		},
		/* 添加节点 */
		addNode(node,data) {
			// console.log(node,data);
			this.dialog_title = '添加';
				/* 添加目录 */
			this.dialogForm = {
				level_1: node.level === 1 
				? data.ClassifyName
				:node.level === 2
				? node.parent.data.ClassifyName
				: node.parent.parent.data.ClassifyName,
				level_2: node.level === 1 
				? ''
				:node.level === 2
				? data.ClassifyName
				: node.parent.data.ClassifyName,
				// level_3: node.level === 3
				// ? data.ClassifyName
				// : '',
				parent_id: data.ClassifyId,
				level: node.level
			}
			//存储当前要新增子级的目录code
			sessionStorage.setItem('expandCode', data.UniqueCode);
			this.isOpenDialog = true;
		},
		/* 编辑节点 */
		editNode(node,data) {
			this.dialog_title = '编辑';
			if(data.EdbCode) {
				/* 编辑指标 */
				
				(data.EdbType===1 || [58,59,67,68].includes(data.Source)) && dataBaseInterface.targetDetail({
					EdbInfoId: data.EdbInfoId
				}).then(res => {
					if(res.Ret === 200) {
						this.dialogForm = {
							level: node.level,
							level_4: res.Data.EdbName,
							level_menu:[
								node.parent.parent.parent.data.ClassifyId,
								node.parent.parent.data.ClassifyId,
								node.parent.data.ClassifyId
							],
							edbinfo_id: res.Data.EdbInfoId,
							frequency:res.Data.Frequency,
							unit:res.Data.Unit
						}
						this.isOpenDialog = true;
					}
				});

				/* 编辑计算指标 同比同差转月 */
				(data.EdbType === 2 && ![27,40,58,59].includes(data.Source)) && dataBaseInterface.calculateDetail({
					EdbInfoId: data.EdbInfoId
				}).then(res => {
					if(res.Ret === 200) {
						this.setComputedDialogForm(data.Source,node,data,res.Data);
						this.computed_type = [23,24].includes(data.Source) ? 'joint' : data.Source;
					}
				})

				/* 代码运算 */
				data.Source === 27 && this.$router.push({
					path: '/codecount',
					query: {
						edbid: data.EdbInfoId
					}
				})

				/* 数据调整 */
				data.Source === 40 && this.$router.push({
					path: '/adjustdata',
					query: {
						edbid: data.EdbInfoId,
					}
				})


			}else {
				/* 编辑目录 */
				this.dialogForm = {
					level_1: node.level === 1 
					? data.ClassifyName
					:node.level === 2
					? node.parent.data.ClassifyName
					: node.parent.parent.data.ClassifyName,
					level_2: node.level === 1 
					? ''
					:node.level === 2
					? data.ClassifyName
					: node.parent.data.ClassifyName,
					level_3: node.level === 3
					? data.ClassifyName
					: '',
					classify_id: data.ClassifyId,
					level: node.level
				}
				this.isOpenDialog = true;
			}
		},
		/* 保存成功 */
		sucessCallback(type) {
			this.isOpenDialog = false;
			this.getTreeData();
			type==='update' && this.getDataList();
			if(type === 'add') {
				//新增分类完成之后，展开父节点显示刚新增的分类，若已展开节点则不做处理
				let code = sessionStorage.getItem('expandCode');
				let flag = 	this.defaultShowNodes.some((item) => {
					return item === code
				});
				// console.log(flag)
				!flag &&code&& this.defaultShowNodes.push(code);
				sessionStorage.removeItem('expandCode');
			}
		},
		/* 刷新获取指标最新数据 */
		refreshTargetHandle: _.debounce(function() {
			if(this.selected_edbid) {
				this.loading = this.$loading({
					lock: true,
					target:'.main-right',
					text: '刷新数据中...',
					spinner: 'el-icon-loading',
					background: 'rgba(255, 255, 255, 0.8)'
				});
				dataBaseInterface.targetRefresh({
					EdbInfoId: this.selected_edbid
				}).then(res => {
					if(res.Ret === 200) {
						this.loading.close();
						this.$message.success(res.Msg);

						this.page_no = 1;
						this.getDataList('refresh')
					}else{
						this.loading.close();
					}
				})
			}
		},500), 
		/* 删除节点校验 */
		removeNode(node,data) {
			dataBaseInterface.nodeDelCheck({
				ClassifyId: data.ClassifyId,
				EdbInfoId: data.EdbInfoId
			}).then(res => {
				if(res.Ret === 200) {
					/**
					 * 0 可删除
					 * 1 关联指标
					 * 2 有子目录无指标
					*/
					const deleteLabelMap = {
						1: '该目录关联指标不可删除',
						2: '确认删除当前目录及包含的子目录吗？',
						3: '当前指标已用作画图，不可删除',
						4: res.Data.TipsMsg
					}

					if([1,3,4].includes(res.Data.DeleteStatus)) this.$confirm(
							deleteLabelMap[res.Data.DeleteStatus],
							'删除失败',
							{
							confirmButtonText: '知道了',
							showCancelButton:false,
							type: 'error'
						})
					else if([0,2].includes(res.Data.DeleteStatus)) this.$confirm(
							res.Data.DeleteStatus === 2 
							? deleteLabelMap[res.Data.DeleteStatus]
							: data.EdbCode?'删除后指标和指标值均不可使用，确认删除吗？':'确定删除当前目录吗?', 
							'提示',
							{
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							this.delHandle(data.ClassifyId,data.EdbInfoId);
						}).catch(() => {         
						});
				}
			})

		},
		/* 删除方法 */
		delHandle(ClassifyId,EdbInfoId) {
			dataBaseInterface.nodeDelete({
				ClassifyId,
				EdbInfoId
			}).then(res => {
				if(res.Ret === 200) {
					this.$message.success(res.Msg);
					this.getTreeData();
					this.selected_edbid = 0;
					this.deleteLabel({code:this.select_node,id:EdbInfoId,classifyId:ClassifyId})
					// this.getNewTargetList();
				}
			})
		},
		/* 判断节点是否能被拖拽 */
		canDragHandle({data}) {
      return data.Button.MoveButton;
		},
		/* 判断节点是否能被拖入 */
		canDropHandle(draggingNode, dropNode, type) {
			let canDrop=false
			// 移动的是一级目录
			if(draggingNode.level===1&&dropNode.level===1&&type!=='inner') {
				canDrop=true
			} 

			// 二级目录
			if(draggingNode.level===2){
				if((dropNode.level===1&&type==='inner')||(dropNode.level===2&&type!=='inner')){
					canDrop=true
				}
			}

			//三级目录
			if(draggingNode.level===3){
				if((dropNode.level===2&&type==='inner')||(dropNode.level===3&&type!=='inner')){
					canDrop=true
				}
			}
			//四级指标
			if(draggingNode.level===4){
				if((dropNode.level===3&&type==='inner')||(dropNode.level===4&&type!=='inner')){
					canDrop=true
				}
			}
			
			return canDrop
		},
		/* 拖拽完成 */
		dropOverHandle(b,a,i,e) {
			// 被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置
			if(b.level===1||b.level===2||b.level===3){
				this.handleMoveCatalogue(b,a,i,e)
			}

			// 指标层
			if(b.level===4){
				this.handleMoveEdb(b,a,i,e)
			}
		},

		// 移动的为一、二、三级目录
		handleMoveCatalogue(b,a,i,e){
			let list=a.parent.childNodes,targetIndex=0,PrevClassifyId=0,NextClassifyId=0,ParentClassifyId=0;

			list.forEach((item,index)=>{
				if(item.data.ClassifyId===b.data.ClassifyId){
					targetIndex=index
					return
				}
			})

			if(targetIndex===0){
				PrevClassifyId=0
				NextClassifyId=list[targetIndex+1].data.ClassifyId
			}else if(targetIndex===list.length-1){
				PrevClassifyId=list[targetIndex-1].data.ClassifyId
				NextClassifyId=0
			}else{
				PrevClassifyId=list[targetIndex-1].data.ClassifyId
				NextClassifyId=list[targetIndex+1].data.ClassifyId
			}

			if(b.level===2){
				if(i==='inner'){
					ParentClassifyId=a.data.ClassifyId
					PrevClassifyId=0
					NextClassifyId=a.data.Children.length>1?a.data.Children[1].ClassifyId:0
				}else{
					ParentClassifyId=a.data.ParentId
				}
			}

			if(b.level===3){
				if(i==='inner'){
					ParentClassifyId=a.data.ClassifyId
					PrevClassifyId=0
					NextClassifyId=a.data.Children.length>1?a.data.Children[1].ClassifyId:0
				}else{
					ParentClassifyId=a.data.ParentId
				}
			}

			dataBaseInterface.classifyMove({
				ClassifyId:b.data.ClassifyId,
				ParentClassifyId:ParentClassifyId,
				PrevClassifyId:PrevClassifyId,
				NextClassifyId:NextClassifyId
			}).then(res=>{
				if(res.Ret===200){
					this.$message.success('移动成功!')
				}
				this.getTreeData();
			})
		},

		// 移动的为指标层 四级
		handleMoveEdb(b,a,i,e){
			let PrevEdbInfoId=0,NextEdbInfoId=0,targetIndex=0,list=a.parent.childNodes.map(_ => _.data)
			if(i==='inner'){
				PrevEdbInfoId=0
				NextEdbInfoId=a.data.Children.length>1?a.data.Children[1].EdbInfoId:0
			}else{
				list.forEach((item,index)=>{
					if(item.EdbInfoId===b.data.EdbInfoId){
						targetIndex=index
						return
					}
				})

				if(targetIndex===0){
					PrevEdbInfoId=0
					NextEdbInfoId=list[targetIndex+1].EdbInfoId
				}else if(targetIndex===list.length-1){
					PrevEdbInfoId=list[targetIndex-1].EdbInfoId
					NextEdbInfoId=0
				}else{
					PrevEdbInfoId=list[targetIndex-1].EdbInfoId
					NextEdbInfoId=list[targetIndex+1].EdbInfoId
				}
			}	
			
			dataBaseInterface.targetMove({
				ClassifyId: a.data.ClassifyId,
				EdbInfoId: b.data.EdbInfoId,
				PrevEdbInfoId:PrevEdbInfoId,
				NextEdbInfoId:NextEdbInfoId
			}).then(res => {
				if(res.Ret === 200) {
					this.$message.success('移动成功!')
				}
				this.getTreeData();
			})
		},

		/* 拖拽覆盖添加背景色 */
		dropMouseOver(node1,node2,e) {
			// 被拖拽节点对应的 Node、所进入节点对应的 Node、event
			if(((node1.level===2&&node2.level === 1)||(node1.level===3&&node2.level === 2)) && (e.target.childNodes[0].className.includes('el-tree-node__content') 
			|| e.target.className.includes('el-tree-node__content'))) {
				// console.log(e.target.childNodes[0])
				e.target.childNodes[0].className.includes('el-tree-node__content') 
				? e.target.childNodes[0].style.backgroundColor = '#409eff' 
				: e.target.style.backgroundColor = '#409eff';
			}
		},
		/* 拖拽离开/拖拽完成重置背景色 */
		dropMouseLeave(node1,node2,e) {
			let arrs = $('.el-tree-node__content');
			for( let a of arrs ) {
				a.style.backgroundColor = 'transparent';
			}
		},
		// 树节点展开
		handleNodeExpand (data) {
			// 保存当前展开的节点
			let flag = false
			this.defaultShowNodes.some(item => {
				if (item === data.UniqueCode) { // 判断当前节点是否存在， 存在不做处理
					flag = true
					return true
				}
			})
			if (!flag) { // 不存在则存到数组里
				this.defaultShowNodes.push(data.UniqueCode)
			}
		},
		// 树节点关闭
		handleNodeCollapse (data) {
			this.defaultShowNodes.some((item, index) => {
				if (item === data.UniqueCode) {
					// 删除关闭节点
					this.defaultShowNodes.length = index
				}
			})
		},
		/* 根据unicode展开树结构并选中指标 */
		selectCurrentNode({ code, id,classifyId }) {
			console.log(code, id,classifyId);
			this.select_node = code;
			this.selected_edbid = id;

			//this.defaultShowNodes=this.findParentNodeForClassifyId(classifyId,code)
			
			 //滚动到高亮节点位置
			this.$nextTick(()=>{
				setTimeout(() => {
					let node = document.getElementById(`node${this.select_node}`)||{}
					let parent = document.getElementsByClassName('tree-cont')[0];
					//console.log('滚动',node,parent);
					if(node.offsetTop > parent.offsetHeight) {
						parent.scrollTop =  node.offsetTop - parent.offsetHeight/2
					}
				},400)
			})
		},
		// 查找树节点所有父节点
		findParentNodeHandle(arr, id) {
			// 遍历取父级code push数组
			for (let i of arr) {
				if (i.ClassifyId === id) {
					return [i.UniqueCode];
				}
				if (i.Children) {
					let node = this.findParentNodeHandle(i.Children, id);
					if (node) {
						return node.concat(i.UniqueCode);
					}
				}
			}
		},
		// 通过分类id找到指标所属的分类
		findParentNodeForClassifyId(id,code){
			let arr=[]
			this.treeData.forEach(item=>{
				if(item.Children){
					item.Children.forEach(_item=>{
						if(_item.ClassifyId==id){
							arr=[item.UniqueCode,_item.UniqueCode]
						}
					})
				}
			})
			return [...arr,code]
		},
		// 懒加载tree
		handleTreeLoad(node,resolve){
			if(node.level===0){
				resolve(this.treeData)
			}
			if(node.level===1){
				let arr=[]
				this.treeData.forEach(item=>{
					if(item.UniqueCode===node.data.UniqueCode){
						arr=item.Children
					}
				})
				resolve(arr)
			}
			if(node.level===2){
				dataBaseInterface.getEdbListForClassify({ClassifyId:node.data.ClassifyId}).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>2){
				resolve([])
			}
		},
		/* 添加计算指标 */
		addComputedHandler() {
			this.computedTit = '计算指标';
			this.calulateList = [];
			this.calulateForm = {};
			this.operationForm = {};
			this.isOpenComputed = true;
		},
		/* 新增计算指标回调 */
		addComputedCallBack(type, params) {
			this.computed_type = 0;
			this.computed_source = 1;
			this.showAssociateChart=false
			this.showAssociateComputeData=false
			// this.getTreeData();
			type === 'add' ? this.getTreeData(params) : this.getTreeData();
			type === 'edit' && this.initGetData()
		},

		initGetData() {
			this.page_no = 1;
			if(this.$refs.valueUl){
				this.$refs.valueUl.scrollTop = 0;
			}
			this.getDataList();
		},

		/* 选择计算类型 */
		changeComputedType(type) {
			//保证source的对应关系
			let typeMapSource = {
				'toMonthSeason': 5,
				'accumulate': 62
			}
			this.computed_type = typeMapSource[type] || type;
			this.isOpenComputed = false;
		},
		/* 重新计算 */
		reCalculateHandler() {
			this.calculateLoading = true;
			dataBaseInterface.reCalculateTarget({
				EdbInfoId: Number(this.selected_edbid)
			}).then(res => {
				this.calculateLoading = false;
				if(res.Ret !== 200) return;
				this.$message.success(res.Msg);
				this.initDataStatus();
			}).catch(() => {
				this.calculateLoading = false;
			})
		},

		/* 查看计算公式 打开弹窗 */
		viewNode(node,data) {
			const { EdbInfoId,Source } = data;

			//代码运算指标
			if( Source === 27 ) return this.$router.push({
				path: '/codecount',
				query: {
					edbid: EdbInfoId,
					isView: true
				}
			})

			dataBaseInterface.calculateDetail({
				EdbInfoId,
			}).then(res => {
				if(res.Ret !== 200) return
				this.setComputedDialogForm(Source,node,data,res.Data,true);
				this.computed_type = [23,24].includes(Source) ? 'joint' : Source;
			})
		},

		/* 设置回显计算指标的表单 */
		setComputedDialogForm(type,node,data,res,view=false) {
			//指标运算 or 其他计算类型指标
			if( type === 4 ) {
				/* 回显指标和表单 */
				const list = res.CalculateList;
				this.computedTit = view ? '查看计算指标' : '编辑计算指标';
				/* 依赖的指标列表 */
				this.calulateList = list.map(item => {
					return {
						tag: item.FromTag,
						edb_name: item.FromEdbName,
						target: item.FromEdbInfoId,
						start_date: item.StartDate,
						end_date: item.EndDate
					}
				})
				/* 公式和表单 */
				this.calulateForm =  {
					edb_id:res.EdbInfoDetail.EdbInfoId,
					formula: res.EdbInfoDetail.CalculateFormula,
					menu: [
						node.parent.parent.parent.data.ClassifyId,
						node.parent.parent.data.ClassifyId,
						data.ClassifyId
					],
					targetName: res.EdbInfoDetail.EdbName,
					unit: res.EdbInfoDetail.Unit,
					frequency: res.EdbInfoDetail.Frequency,
					view
				};
			} else  {
				let dataInfo = res.EdbInfoDetail;
				let old_edb = res.CalculateList;

				let public_params = {
					edb_id: dataInfo.EdbInfoId,
					targetName: dataInfo.EdbName,
					frequency: dataInfo.Frequency,
					unit: dataInfo.Unit,
					menu: [
						node.parent.parent.parent.data.ClassifyId,
						node.parent.parent.data.ClassifyId,
						data.ClassifyId
					],
					view
				}

				this.operationForm = [23,24,37,53].includes(type)
					? {
							...public_params,
							source: dataInfo.Source,
							date: dataInfo.CalculateFormula,
							pre_edb: type === 23 ? old_edb.find(item => item.FromTag === 'A').FromEdbInfoId : '', //俺也不懂为什么这么定义都是江西老表的锅
							after_edb: type === 23 ? old_edb.find(item => item.FromTag === 'B').FromEdbInfoId : '',
							old_stay_edb: type === 24 ? old_edb.find(item => item.FromTag === 'A').FromEdbInfoId : '',
							concat_edb: type === 24 ? old_edb.find(item => item.FromTag === 'B').FromEdbInfoId : '',
							from_arr: old_edb,
						} 
					: {
							...public_params,
							oldedb_id: old_edb[0].FromEdbInfoId,
							oldEdb_name: old_edb[0].FromEdbName,
							formula: dataInfo.CalculateFormula || '',
							moveType: dataInfo.MoveType,
							moveUnit: dataInfo.MoveFrequency,
							moveVal: type === 22 ? dataInfo.CalculateFormula : '',
							calendar_type: type === 35 ? dataInfo.Calendar : '',
					}
			}
		},

		/* 基础指标刷新 */
		refreshBaseHandler() {
			this.refreshLoading = true;
			dataBaseInterface.refreshBaseTarget({
				EdbInfoId: Number(this.selected_edbid)
			}).then(res => {
				this.refreshLoading = false;
				if(res.Ret !== 200) return;
				this.$message.success(res.Msg);
				this.initDataStatus();
			}).catch(() => {
				this.refreshLoading = false;
			})
		},

		/* 	一键成图 */
		createChartHandle() {
			this.isCreateChart = true;
		},
		
		/* 重新刷新 重新计算后重置刷数据 */
		initDataStatus() {
			this.page_no = 1;
			this.$refs.valueUl.scrollTop = 0;
			this.getDataList();
		},
		/* 用于复制指标 */
		async copyCode(){
			const res = await dataBaseInterface.targetList({
				PageSize: 100000,
				CurrentIndex: 1,
				EdbInfoId: this.selected_edbid,
			})
			if (res.Ret===200){
				let arr = res.Data.Item.DataList ||[]
				let str = '日期\t 值\n'
				arr.forEach((item=> str += `${item.DataTime}\t${item.Value}\n`))
				this.$copyText(str).then(
		        res => {
		          this.$message.success("已成功复制!");
		        },
		        err => {
		         this.$message.error("复制失败!");
		        } )
		 	}
		},

		/* 一键更新 */
		updateHandler() {
			this.isUpdate = true;
		},

		/* 替换指标 */
		async replaceEdbHandler () {

			const { Data } = await dataBaseInterface.replaceCheck();
      Data === 2 
      ? this.isReplaceDia = true
      : await this.$confirm('当前正在替换中，请耐心等待', '提示', {
          type: 'warning',
          showCancelButton: false,
        })
		},

		/* 添加最新值 */
		updateNewestDataHandle() {
			this.isUpdateNewestData = true;
		},

		/* 获取标签列表 */
		getlabelList(){
			const List = JSON.parse(sessionStorage.getItem('database'))||[]
			this.labelList = List
		},
		/* 添加标签  params :{code,id,classifyId,EdbName,EdbNameEn}*/
		addLabel(params){
			const index = this.labelList.findIndex(i=>i.code===params.code)
			//标签已存在列表中,更新标签的值
			if(index!==-1){
				this.labelList.splice(index,1,params)
				return
			}
			//根据页面宽度 判断标签数量是否达到上限
			const listWidth = document.querySelector('.database-label').offsetWidth
			const minWidth=170+20
			const maxNum = Math.floor(listWidth/minWidth)
			if(this.labelList.length>=maxNum){
				//达到上限则挤出第一个,再添加
				this.labelList.shift()
			}
			this.labelList.push(params)
			sessionStorage.setItem('database',JSON.stringify(this.labelList))
		},
		//改变选中标签,
		changeCurrentLabel(params){
			if(params.code!==this.select_node){
				this.selectCurrentNode(params)
			}
		},
		//删除标签
		deleteLabel(params){
			const index = this.labelList.findIndex(i=>i.code===params.code)
			//如果删除的标签是选中状态
			if(this.select_node===params.code){
				//删除的是唯一一个标签
				if(this.labelList.length===1){
					this.selected_edbid=0
					this.select_node = ''
					this.$refs.menuTree.setCurrentKey(null)
				//不是唯一的标签,则默认选中上一个/下一个
				}else{
					index===0&&this.changeCurrentLabel(this.labelList[1])
					index!==0&&index!==-1&&this.changeCurrentLabel(this.labelList[index-1])
				}
			}
			index!==-1&&this.labelList.splice(index,1)
			sessionStorage.setItem('database',JSON.stringify(this.labelList))
		},
		changeTreeNode(){
			this.$refs.menuTree.setCurrentKey(this.select_node);
			this.$nextTick(()=>{
				const _node = this.$refs.menuTree.getNode(this.select_node)
				this.dynamicNode = _node;
				this.dynamicNode&&this.resetNodeStyle(this.dynamicNode)
			})
		},
		//绑定el-tree的load属性
		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){
				//调接口获取该分类下指标的数据
				dataBaseInterface.getEdbListForClassify({ClassifyId:node.data.ClassifyId}).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([])
			}
		}
		},
	//离开页面时保存标签
	beforeRouteLeave(to,from,next){
		sessionStorage.setItem('database',JSON.stringify(this.labelList))
		next()
	},
	mounted() {
		this.getlabelList()

		this.$route.query.code 
		? this.getTreeData({code: this.$route.query.code,id: this.$route.query.id,classifyId:this.$route.query.classifyId})
		: this.getTreeData();

		//离开页面时保存标签
		window.onbeforeunload = ()=>{
			sessionStorage.setItem('database',JSON.stringify(this.labelList))
		}
	},
	destroyed(){
		window.onbeforeunload = null
	}
};
</script>
<style lang="scss">
@import "~@/styles/theme-vars.scss";
.database_container {
	$mini_font: 12px;
	$normal_font: 14px;
	.firstColumTable .el-table__empty-block {
		display: none;
	}
	.firstColumTable .el-table__header th:first-child .cell{
		overflow: visible;
	}
	.el-table td,.el-table th {
		padding: 10px 0;
	}

	.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
		background-color: $theme-color !important;
		border-color: $theme-color;
	}
	.el-checkbox__input.is-disabled.is-indeterminate .el-checkbox__inner {
		background-color: $theme-color !important;
		border-color: $theme-color;
	}
	.el-icon-refresh {
		font-size: 17px;
		margin-left: 5px;
		cursor: pointer;
	}
	@media screen and (min-width: 1711px) {
		.target_tree { 
			font-size: $normal_font; 
		}
	}
	@media screen and (max-width: 1710px) {
		.target_tree { 
			font-size: $mini_font; 
		}
	}

	.database_top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 20px 30px;
		background: #fff;
		border: 1px solid #ececec;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
		.top-right {
			display: flex;
			align-items: center;
		}
	}
	.database_main {
		display: flex;
		margin-top: 20px;
		div::-webkit-scrollbar {
			width: 5px !important;
		}
		.main-left {
			width: 500px;
			min-width: 300px;
			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 - 225px);
			overflow: hidden;
			position: relative;
			box-sizing: border-box;
			.tree-cont {
				padding: 30px;
				height: calc(100vh - 290px);
				overflow: auto;
			}
			.target_tree {
				color: #333;
				.label-input .el-input__inner {
					height: 25px;
					line-height: 25px;
				}
				.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;
					}
				}
				.el-tree__drop-indicator{
					/* position:absolute; */
					/* left:0;
					right:0; */
					height:3px;
					// margin-top: 8px;
					background-color:$theme-color;
				}
				.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;
				}
			}
			.noDepart {
				margin: 60px 0;
				display: flex;
				align-items: center;
				justify-content: center;
				color: $theme-color;
				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 {
			flex: 1;
			/* width:70%; */
			height: calc(100vh - 225px);
			background: #fff;
			border: 1px solid #ececec;
			border-radius: 4px;
			box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
			overflow: hidden;
			.value-ul {
				margin-top: 10px;
				border-bottom: 1px solid #dcdfe6;
				max-height: calc(100vh - 560px);
				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;
					}
					.predict-act {
						color: orange;
					}
					.new-tag {
						width: 6px;
						height: 6px;
						display: inline-block;
						position: absolute;
						left: -12px;
						top: 50%;
						transform: translateY(-50%);
						border-radius: 50%;
						background: #f00;
					}
				}
				.nodata {
					text-align: center;
					padding: 40px 0;
					color: #999;
				}
			}
			&.list{
				background-color: transparent;
				box-shadow: none;
				border:none;
				padding:0 30px;
				.list-wrap{
					margin-top: 20px;
					display: flex;
					gap: 20px 4%;
					flex-wrap: wrap;
					max-height: calc(100vh - 225px);
					overflow-x: hidden;
					overflow-y: auto;
					.list-item{
						width:22%;
						height:280px;
						background-color: #fff;
						display: flex;
						flex-direction: column;
						box-sizing: border-box;
						padding: 0 10px;
						border-radius: 4px;
						border:1px solid #DCDFE6;
						.header,.info{
							height: 40px;
							line-height: 40px;
							text-align: left;
						}
						.header{
							border-bottom: 1px solid #DCDFE6;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}
						.image{
							flex: 1;
							cursor: pointer;
						}
					}
				}
			}
			&.detail{
				.header{
					display: flex;
					border-bottom: 1px solid #E4E7ED;
					.el-tabs{
						width:200px;
						.el-tabs__header{
							margin-bottom: 0;
						}
						.el-tabs__nav{
							display: flex;
							width: 100%;
							.el-tabs__item{
								flex: 1;
								text-align: center;
							}
						}
					}
					.edb-tool{
						flex: 1;
						/* background-color: #666; */
						border-bottom: 1px solid #E4E7ED;
					}
				}
			}

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