import chartRelevanceApi from '@/api/modules/chartRelevanceApi.js';
import { fittingEquationInterface,statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';
import { dataBaseInterface } from '@/api/api.js';

export default {
  data() {
    return {};
  },
  watch: {
    /* 设置动态右侧区域宽度 */
    isSlideLeft(newval) {
      this.$nextTick(() => {
        this.reloadRightWid();
      });
    },
    /* 图表id */
    select_id(newval) {
      if (newval) {
        this.currentLang = "ch";
        this.getDetailHandle();
      } else {
        this.chartInfo = {};
      }
    },

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

    /* 搜索关键词 */
    search_txt(newval) {
      if (newval) {
        let search_obj = this.searchOptions.find(
          (_) => _.ChartInfoId === newval
        );
        let deep_arr = _.cloneDeep(this.treeData);
        // 查找图表的分类父级id

        let arr = this.findParentNodeHandle(deep_arr, search_obj.UniqueCode)
          .slice(1)
          .reverse(); // 父的父的父-父的父-父
        this.defaultShowNodes = arr;
        this.select_node = search_obj.UniqueCode;
        this.$refs.treeRef.setCurrentKey(this.select_node);
        // 重置筛选状态
        this.select_id = newval;
      }
    },
  },
  directives: {
    drag(el, bindings) {
      el.onmousedown = function(e) {
				var init = e.clientX;
				var box = $("#box")[0]
				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;
					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;
      };
    }
  },

  methods: {
    /* 根据unicode展开树结构并选中当前图表 重置图表配置 日期区间 */
    selectCurrentNode({ code, id, type }) {
      let deep_arr = _.cloneDeep(this.treeData);
      // 查找图表的分类父级id
      let arr = this.findParentNodeHandle(deep_arr, code).slice(1).reverse(); // 父的父的父-父的父-父
      this.defaultShowNodes = arr;
      this.select_node = code;
      this.$refs.treeRef.setCurrentKey(this.select_node);
      // // 重置筛选状态
      this.select_id = id;
    },

    // 查找树节点所有父节点
    findParentNodeHandle(arr, id) {
      // 遍历取父级code push数组
      for (let i of arr) {
        if (i.UniqueCode === id) {
          return [i.UniqueCode];
        }
        if (i.Children) {
          let node = this.findParentNodeHandle(i.Children, id);
          if (node) {
            return node.concat(i.UniqueCode);
          }
        }
      }
    },

    /* 拖动时node宽度跟随变化 */
    resetNodeStyle: _.debounce(function(node) {
			const tree = $('.target_tree')[0];
			let width = tree.offsetWidth;
			// let label_wid = width > 500 ? 'auto' : (width <= 300 && width < 360) ?  100 : 0.7*width;
			let label_wid =
				width > 500
					? 'auto'
					: width <= 260
					? 90
					: 0.7 * width;
			this.$set(node, 'Nodewidth', label_wid + 'px');
		},200),

    	/* 双击label出现input修改框 */
		editNodeLabel(data,type='') {
        //目录名称可以双击修改
        if(data.ChartInfoId) return
        this.$set(data,'isEdit',true)
        this.new_label = data.ChartClassifyName;
        this.$nextTick(() => {
          this.$refs.editVal.focus();
        });
		},

    /* input失去焦点恢复node 修改最新的值*/
		async changeValue(data) {
      if(!this.new_label) return this.$message.warning('名称不能为空');
      this.$set(data,'isEdit',false)

      if(this.new_label !== data.ClassifyName) {
        let res = this.$route.path === '/fittingEquationList'
          ? await fittingEquationInterface.classifyEdit({
              ChartClassifyId: data.ChartClassifyId,
              ChartClassifyName: this.new_label
            })
          : this.$route.path === '/statisticFeatureList'
          ? await statisticFeatureInterface.classifyEdit({
              ChartClassifyId: data.ChartClassifyId,
              ChartClassifyName: this.new_label
            })
          :await chartRelevanceApi.classifyEdit({
              ChartClassifyId: data.ChartClassifyId,
              ChartClassifyName: this.new_label
            })

        if(res.Ret !== 200) return
  
        this.getTreeData();
      }
    },

    /* 拖拽完成 */
    dropOverHandle(b, a, i, e) {
      // console.log(i, a);
      // 被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置
      // 一/二级目录
      if ([1].includes(b.level)) this.handleMoveCatalogue(b, a, i, e);

      // 指标层
      if (b.level === 2) this.handleMoveSheet(b, a, i, e);
    },

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

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

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

      let params = {
        ClassifyId: b.data.ChartClassifyId,
        PrevClassifyId: PrevClassifyId,
        NextClassifyId: NextClassifyId,
      }

      let res;
      if(this.$route.path === '/chartrelevance') {
        res=await chartRelevanceApi.classifyMove(params)
      }else if(this.$route.path === '/fittingEquationList') {
        res=await fittingEquationInterface.classifyMove(params)
      }else if(this.$route.path === '/statisticFeatureList') {
        res=await statisticFeatureInterface.classifyMove(params)
      }

      if (res.Ret !== 200) return;
      this.$message.success("移动成功!");
      this.getTreeData();
    },

    // 移动的为图表
    async handleMoveSheet(b, a, i, e) {
      let PrevChartId = 0,
        NextChartId = 0,
        targetIndex = 0,
        list = a.parent.data.Children;
      if (i === "inner") {
        PrevChartId = 0;
        NextChartId =
          a.data.Children.length > 1 ? a.data.Children[1].ChartInfoId : 0;
      } else {
        list.forEach((item, index) => {
          if (item.ChartInfoId === b.data.ChartInfoId) {
            targetIndex = index;
            return;
          }
        });

        if (targetIndex === 0) {
          PrevChartId = 0;
          NextChartId = list[targetIndex + 1].ChartInfoId;
        } else if (targetIndex === list.length - 1) {
          PrevChartId = list[targetIndex - 1].ChartInfoId;
          NextChartId = 0;
        } else {
          PrevChartId = list[targetIndex - 1].ChartInfoId;
          NextChartId = list[targetIndex + 1].ChartInfoId;
        }
      }
      let params = {
        ChartClassifyId: a.data.ChartClassifyId,
        ChartInfoId: b.data.ChartInfoId,
        PrevChartInfoId: PrevChartId,
        NextChartInfoId: NextChartId,
      }

      let res;
      if(this.$route.path === '/chartrelevance') {
        res=await chartRelevanceApi.chartMove(params)
      }else if(this.$route.path === '/fittingEquationList') {
        res=await fittingEquationInterface.chartMove(params)
      }else if(this.$route.path === '/statisticFeatureList') {
        res=await statisticFeatureInterface.chartMove(params)
      }
      
      if (res.Ret !== 200) return;
      this.$message.success("移动成功!");
      this.getTreeData();

    },

    /* 拖拽覆盖添加背景色 */
    dropMouseOver(node1, node2, e) {
      if (
        (node1.level === 2 && node2.level === 1) &&
        (e.target.childNodes[0].className.includes("el-tree-node__content") ||
          e.target.className.includes("el-tree-node__content"))
      ) {
        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 = this.defaultShowNodes.some((item) => item === data.UniqueCode);

      if (!flag) {
        // 不存在则存到数组里
        this.defaultShowNodes.push(data.UniqueCode);
      }
    },

    // 树节点关闭
    handleNodeCollapse(data) {
      this.defaultShowNodes.some((item, index) => {
        if (item === data.UniqueCode) {
          // 删除关闭节点
          this.defaultShowNodes.length = index;
        }
      });
    },

    /* 判断节点是否能被拖拽 */
    canDragHandle(node) {
      let canMove = true;
      return canMove;
    },

    /* 判断节点是否能被拖入 */
    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;
        }
      }

      return canDrop;
    },

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

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

    /* 加入我的图库 */
    addMychartHandle(item) {
      this.add_chart_id = item.ChartInfoId;
      //已有的分类ids
      this.add_ids = item.MyChartClassifyId
        ? item.MyChartClassifyId.split(",").map((item) => Number(item))
        : [];
      this.isAddMyChart = true;
    },

    /* 加入我的图库成功 */
    addMySuccess(params) {
      this.isAddMyChart = false;

      /* 判断是详情还是图库列表 */
      if (this.select_id) {
        this.chartInfo.IsAdd = true;
        this.chartInfo.MyChartId = params.MyChartInfoId;
        this.chartInfo.MyChartClassifyId = params.MyChartClassifyId;
      } else {
        this.chartList.forEach((item) => {
          if (item.ChartInfoId === this.add_chart_id) {
            item.IsAdd = true;
            item.MyChartId = params.MyChartInfoId;
            item.MyChartClassifyId = params.MyChartClassifyId;
          }
        });
      }
    },

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

    },

    /* 点击保存时关联图表和截取的图片 */
    setChartImage() {
      let svg = this.$refs.chartRef.chart.getSVG({
        chart: {
          width: this.$refs.chartRef.chart.chartWidth,
          height: this.$refs.chartRef.chart.chartHeight,
        },
      });
      let form = new FormData();
      form.append("Img", svg);
      this.setImageHandle(form);
    },

    async setImageHandle(form) {
      let { Data } = await dataBaseInterface.uploadImgSvg(form);

      await dataBaseInterface.setChartImage({
        ChartInfoId: this.select_id,
        ImageUrl: Data.ResourceUrl,
      });
    },

    copyChartConfirm(type) {
      type !== "url" && this.copyChartHandle(type);
      
      type == "url" && this.shareUrl();
    },

    /* 分享图表 */
    shareUrl() {
      var clipboard = new this.Clipboard(".shareLink");
      clipboard.on("success", (e) => {
        console.log(e);
        this.$message.success("复制链接成功");
        e.clearSelection(); // 释放内存
        clipboard.destroy();
      });
      // // 浏览器不支持
      clipboard.on("error", (e) => {
        this.$message.warning("浏览器暂不支持");
        // 释放内存
        clipboard.destroy();
      });
    },
  },
};
