<template>
	<div class="fittingEquation-chart-container" v-if="showData">
		<span
			class="slide-icon slide-right"
			@click="isSlideLeft = !isSlideLeft"
			v-show="isSlideLeft"
		>
			<i class="el-icon-d-arrow-right"></i>
		</span>

		<div class="data-sheet-main" id="box">
      <div class="main-left left" id="left" v-show="!isSlideLeft">
				<div class="datasheet_top">
						<el-button v-permission="permissionBtn.statisticPermission.statisticFeature_addChart"
							 type="primary" @click="goAddChart">添加图表</el-button>
				</div>

				<div class="search-cont">
					<el-checkbox v-model="isShowMe"  @change="() => { getTreeData();getPublicList() }">只看我的</el-checkbox>
					<el-select
						v-model="search_txt"
						v-loadMore="searchLoad"
						:filterable="!search_txt"
						remote
						clearable
						placeholder="请输入图表名称"
						style="width: 100%; margin-top: 20px"
						: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.ChartInfoId"
							:label="item.ChartName"
							:value="item.ChartInfoId"
						>
						</el-option>
					</el-select>
				</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="暂无分类"
						@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>{{ data.ChartClassifyName }}</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"
								/>
								<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.ChartInfoId"
								/>
								<img
									slot="reference"
									src="~@/assets/img/set_m/del.png"
									alt=""
									style="width: 14px; height: 14px"
									@click.stop="removeNode(node, data)"
									v-if="!data.ChartInfoId"
								/>
							</span>
						</span>
					</el-tree>
					<div
						class="noDepart"
						@click="addLevelOneHandle"
					>
						<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="chart-detail-wrapper" v-if="chartInfo.ChartInfoId">
					<el-row class="bottom-min">
              <el-col
                :span="21"
                style="padding: 20px 0;"
              >
                <div class="chartEn-mark" v-show="chartInfo.IsEnChart" style="top: 0;left: 0;">En</div>
                <div class="chart-show-cont"  v-if="!chartInfo.WarnMsg">
                  <div class="chartWrapper" id="chartWrapper">
                    <h2 class="chart-title">{{ chartInfo.ChartName }}</h2>
                    <Chart 
											:options="options"
											minHeight="440px" 
											height="500px"
											ref="chartRef"
										/>
                  </div>
                  <span class="chart-author">作者:{{ chartInfo.SysUserRealName}}</span>
                </div>

                <!-- 异常显示 -->
                <p class="error-tip" style="min-height: 400px;" v-if="chartInfo.WarnMsg">{{chartInfo.WarnMsg}}</p>
              </el-col>
              <el-col :span="3" style="position: absolute;height: 100%;right: 0;">
								<!-- 操作 -->
								<chartHandlesWrap
									:chartInfo="chartInfo"
									:linkUrl="linkUrl"
									@copyChartConfirm="copyChartConfirm"
									@addMychartHandle="addMychartHandle"
									@refreshHandle="refreshHandle"
									@saveChartOtherHandle="saveChartOtherHandle"
									@editChartHandle="editChartHandle"
									@openEnNameDia="openEnNameDia"
									@delChartHandle="delChartHandle"
								/>
              </el-col>
          </el-row>
				</div>
				<!-- 列表 -->
				<chartListWrap
          v-else 
          :total="chart_total"
          :list="chartList" 
          @loadMoreHandle="loadMoreHandle"
          @detailShowHandle="detailShowHandle"
          @addMychartHandle="addMychartHandle"
          ref="chartListWrap"
        />
			</div>
		</div>


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

		 <!-- 加入我的图库弹窗 -->
    <addMyClassifyDia
      :isAddMyDialog="isAddMyChart"
      :add_id="add_chart_id"
      :add_ids="add_ids"
      @cancel="isAddMyChart = false"
      @addSuccess="addMySuccess"
    />

		 <!-- 图表另存 -->
    <SaveChartOther 
      :show.sync="isShowSaveOther" 
      fromType="chartsetting"
			source="statistic_feature"
      :data="chartInfo"
      @ensure="getTreeData"
    />

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

	</div>
</template>

<script>

import { statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';
import leftMixin from './mixins/classifyMixin';
import Chart from '@/views/dataEntry_manage/components/chart';
import classifyDia from '@/views/datasheet_manage/components/sheetClassifyDia.vue';
import addMyClassifyDia from '@/views/dataEntry_manage/components/addMyClassifyDia';
import SaveChartOther from '@/views/dataEntry_manage/components/SaveChartOther';
import setEnNameDia from '@/views/dataEntry_manage/components/setEnNameDia.vue'
import { chartSetMixin } from '@/views/dataEntry_manage/mixins/chartPublic';
import { copyOtherOptions } from '@/utils/defaultOptions';
export default {
	components: {
		classifyDia,
		Chart,
		addMyClassifyDia,
		SaveChartOther,
		setEnNameDia
	},
	mixins:[ leftMixin,chartSetMixin ],
	computed: {
		/* 分享地址 */
    linkUrl() {
      const LINK_CHART_URL = this.$setting.ChartViewUrl+'/chartshow';
      return `${LINK_CHART_URL}?code=${this.chartInfo.UniqueCode}&fromType=share?&lang=${this.currentLang}`
    }
	},
	data () {
		return {
			showData: false,
			refreshLoading: false,
			isShowMe: false,
			search_txt: '',
			searchOptions:[],
			isSlideLeft: false,//左侧分类收起

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

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

			select_id: '',//选中的图表id
			chartInfo: {},
			chart_title:'',//图表标题 双击标题修改时来存储最新值

			isAddMyChart: false, //加入图库弹窗
      add_chart_id: 0, //要加入的图表
			add_ids:[],//加入时已有的分类

			/* 图表列表 */
			publicHaveMove: true,//是否还有列表数据
			chartList: [],
			chart_total: 0,
			chart_page: 1,
			chart_pages_size: 16,

			search_page: 1,
			search_have_more: false,
			current_search:'',
		};
	},
	methods: {

		/* 添加图表 */
		goAddChart() {
			if(!this.treeData.length) return this.$message.warning('请先添加分类');
			this.$router.push({ path: '/statisticFeatureChartEditor' });
		},

		/* 获取分类 */
		getTreeData(params=null) {
			statisticFeatureInterface.classifyList({IsShowMe:this.isShowMe}).then(res => {
				const { Ret,Data } = res;
				if(Ret !== 200) return

				this.showData = true;
				this.treeData = Data.AllNodes || [];
				this.$nextTick(() => {
					/* 新增完成后 处理树展开和选中 */
					params && this.selectCurrentNode(params);
				});

			})
		},

		/* 搜索 */
		searchHandle(query) {
			this.search_page = 1;
			this.current_search = query;
			this.searchApi(this.current_search)
		},

		searchApi(query,page=1) {
      /* 查找列表 */
      statisticFeatureInterface
        .searchChart({
          Keyword: query,
          IsShowMe:this.isShowMe,
          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,...List];
        });
		},

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

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

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

		/* 添加一级目录 */
		addLevelOneHandle() {
			this.dialog_title = '添加';
			this.classifyForm = {
				classify_name: '',
			}
			this.classifyDia = true;
		},

    /* 编辑节点 */
    editNode(node, { ChartClassifyName,ChartClassifyId }) {

      this.dialog_title = '编辑';
      /* 编辑目录 */
      this.classifyForm = {
        classify_name: ChartClassifyName,
        classify_id: ChartClassifyId,
      };
      this.classifyDia = true;
    },

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

			const { Data } = await statisticFeatureInterface.classifyDelCheck({ ChartClassifyId })

			const { DeleteStatus } = Data;

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

    },

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

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

					//删除自动显示下一张
					type=='del_chart' && res.Data.ChartInfoId
						? this.getTreeData({
								code: res.Data.UniqueCode,
								id: res.Data.ChartInfoId
							})
						: this.getTreeData();
        });
    },

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

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

      }
		},

		/* 获取图表列表 */
		getPublicList() {
			statisticFeatureInterface.getChartList({
				CurrentIndex: this.chart_page,
				PageSize: this.chart_pages_size,
        ChartClassifyId: this.select_classify || 0,
				IsShowMe: this.isShowMe
			}).then(res => {
				if(res.Ret !== 200) return

				this.publicHaveMove = res.Data
            ? this.chart_page < res.Data.Paging.Pages
            : false;
          this.chartList = res.Data
            ? this.chart_page === 1
              ? res.Data.List
              : [...this.chartList, ...res.Data.List]
            : [];
        this.chart_total = res.Data ? res.Data.Paging.Totals : 0;
			})
		},

		getChartInfo() {
			this.getDetailHandle();
		},

		/* 获取图表详情 */
		getDetailHandle() {
			statisticFeatureInterface.chartDetail({
				ChartInfoId: this.select_id
			}).then(res => {
				if(res.Ret !== 200) return

				const { ChartInfo,DataResp } = res.Data;
				this.chartInfo = ChartInfo;
				if(ChartInfo.Source===9) {
          this.statisticFrequencyData = DataResp;
          this.setStatisticFrequency();
				}else {
					this.setDefaultChart([DataResp])
				}

				!ChartInfo.ChartImage && this.$nextTick(() => {
					//关联图表和图片
					 this.setChartImage();
				})
			})
		},

		/* 删除图表 */
		delChartHandle() {
			const { ChartClassifyId,ChartInfoId } = this.chartInfo;
			this.$confirm('删除后该图表将不能再引用，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delApi(ChartClassifyId,ChartInfoId,'del_chart');
        })
        .catch(() => {});
		},

		/* 刷新图表 */
		refreshHandle() {
			this.refreshLoading = this.$loading({
        lock: true,
        target: '.main-right',
        text: '刷新图表中...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.8)',
      });
      statisticFeatureInterface
        .refreshChart({
          ChartInfoId: this.chartInfo.ChartInfoId,
        })
        .then((res) => {
          this.refreshLoading.close();
          if (res.Ret === 200) {
            this.getDetailHandle();
            this.$message.success(res.Msg);
          }
        });
		},

		/* 编辑图表 */
		editChartHandle() {
			this.$router.push({
        path: '/statisticFeatureChartEditor',
        query: {
          code: this.chartInfo.UniqueCode,
					id: this.chartInfo.ChartInfoId
        }
      })
		},

		copyChartHandle:_.debounce(function(type){
      let chartsName = this.currentLang=='ch'?this.chartInfo.ChartName:this.chartInfo.ChartNameEn
      let { heightNum, widthNum , newTitle , dynamic_copyOptions} = this.dynamicWidthAndHeight(type,this.chartInfo.ChartType,chartsName,1)
      const chartType = 'seasonLegend';
      // 英文转SVG设置变动
      if(this.currentLang == 'en'){
        // 如果竖轴坐标单位为'英文单位'，表示客户没填，转成svg时置为空
        this.$refs.chartRef.chart.options.yAxis.forEach(it => {
          if(it.title.text == '英文单位') it.title.text='' 
        });
      }
      let svg = this.$refs.chartRef.chart.getSVG({
        chart:{
          width:widthNum,
          height:heightNum,
          backgroundColor:"rgba(255, 255, 255, 0)",
        },
        title: {
          text: newTitle,
          margin: 10,
          style: {
            fontSize: '18px'
          }
        },
        legend:{
          ...copyOtherOptions[chartType],
          ...dynamic_copyOptions[chartType]
          }
      });
      this.copyBlobItem(widthNum,heightNum,svg,type);
    },500),
	},
	mounted() {

		if(this.$route.query.code) {
      this.getTreeData({code: this.$route.query.code,id: Number(this.$route.query.id)})
    } else {
      this.getTreeData();
      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;
.fittingEquation-chart-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;
		}
	}
	.data-sheet-main {
		display: flex;

		.main-left {
			width: 400px;
			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 - 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;
			}
			.search-cont {
				padding: 0 20px;
			}



			.tree-cont {
				padding: 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%;
			.chart-detail-wrapper {
				height: calc(100vh - 120px);
				border: 1px solid #ececec;
				border-radius: 4px;
				box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
				overflow: auto;
				background: #fff;
				padding: 30px;
				.bottom-min {
					border: 1px solid #DCDFE6;
					margin-bottom: 20px;
					.chart-show-cont {
              padding: 0 160px 0 120px;
              position: relative;
							min-height: 400px;
              .chart-title {
                font-size: 16px;
                font-weight: normal;
                text-align: center;
                margin-bottom: 10px;
              }
              .chart-author {
                font-size: 14px;
                color: #333;
                position: absolute;
                bottom: 0;
                right: 50px;
              }
              .chartWrapper {
                position: relative;
                .range-cont {
                  position: absolute;
                  top: 13%;
                  .min-data-input {
                    width: 60px;
                    display: block;
                  }
                  &.left {
                    left: -80px;
                  }
                  &.right {
                    right: -65px;
                  }
                  &.rightTwo {
                    right: -130px;
                  }
                }
              }
          }
				}
			}
		}
		
		@media screen and (min-width: 1711px){
			.min-data-input {
				margin-top: 360px;
			}
		}
		@media screen and (max-width: 1710px){
			.min-data-input {
				margin-top: 290px;
			}
		}
	}
}
</style>

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

	.range-cont .el-input__inner {
		padding: 0 3px;
	}

	.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;
	}
}
</style>