<template>
  <div class="app-container">
    <div style="color: red">
      点击小组编辑小组岗位和人员；鼠标悬浮查看部门和人员;
    </div>
    <el-row :gutter="10" class="mb8" type="flex" justify="end">
      <el-col :span="1.5">
        <el-date-picker
          v-model="value3"
          type="year"
          placeholder="选择年"
          value-format="yyyy"
          @change="getList"
        >
        </el-date-picker>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="copy">复制组织架构至剪切板</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            @click="handleUpdate"
            v-hasPermi="['system:post:add']"
            >编辑</el-button
          >
        </el-col> -->
    </el-row>
    <div>
      <charts-components
        ref="chartsRef"
        :chart-data-options="xychartOption"
        style="height: calc(100vh - 140px)"
        echarts-type="bar1"
        @get-params="getParams"
      />
    </div>
  </div>
</template>

<script>
import {
  listTeam,
  getTeamUserByTeamId,
} from "@/api/postInspectionPlanning/teamManagement.js";
export default {
  data() {
    let _now = new Date();
    let currentYear = _now.getFullYear();
    return {
      value3: `${currentYear}`,
      xychartOption: {
        tooltip: {
          trigger: "item",
          triggerOn: "mousemove",
          formatter: function (params) {
            const { childrenDept, childrenUser, type } = params.data;
            let one = childrenUser
              .filter((item) => item.type === 1)
              .map((item) => item.nickName)
              .join("，");
            let two = childrenUser
              .filter((item) => item.type === 2)
              .map((item) => item.nickName)
              .join("，");
            const oneDept = childrenDept
              .filter((item) => item.type === 1)
              .map((item) => item.deptName)
              .join("，");
            const twoDept = childrenDept
              .filter((item) => item.type === 2)
              .map((item) => item.deptName)
              .join("，");
            const deptName = childrenDept
              .map((item) => item.deptName)
              .join("，");
            let name1 = "";
            let name2 = "";
            switch (type) {
              case 0:
                name1 = "组长：";
                name2 = "副组长：";
                break;
              case 1:
                name1 = "主任：";
                name2 = "副主任：";
                break;
              case 3:
               one = childrenUser
              .filter((item) => item.type === 1)
              .map((item) => (`${item.deptName}--${item.nickName}`))
              .join("，");
               two = childrenUser
              .filter((item) => item.type === 2)
              .map((item) => (`${item.deptName}--${item.nickName}`))
              .join("，");
                name1 = "组长：";
                name2 = "成员：";
                break;
              default:
                break;
            }
            const oneHtml = `<div style="display: flex"><p>${name1}</p><p style="min-width: 100px; max-width: 200px;white-space: pre-wrap;word-wrap: break-word;">${one}</p></div>`;
            const twoHtml = `<div style="display: flex"><p>${name2}</p><p style="min-width: 100px; max-width: 200px;white-space: pre-wrap;word-wrap: break-word;">${two}</p></div>`;
            const oneDeptHtml = `<div style="display: flex"><p>牵头部门：</p><p style="min-width: 100px; max-width: 200px;white-space: pre-wrap;word-wrap: break-word;">${oneDept}</p></div>`;
            const twoDeptHtml = `<div style="display: flex"><p>成员部门：</p><p style="min-width: 100px; max-width: 200px;white-space: pre-wrap;word-wrap: break-word;">${twoDept}</p></div>`;
            const deptNameHtml = `<div style="display: flex"><p>部门：</p><p style="min-width: 100px; max-width: 200px;white-space: pre-wrap;word-wrap: break-word;">${deptName}</p></div>`;
            let userHtml = childrenUser.length > 0 ? oneHtml + twoHtml : "";
            let deptHtml = ``;
            switch (type) {
              case 1:
                deptHtml = childrenDept.length > 0 ? deptNameHtml : "";
                break;
              case 2:
                deptHtml =
                  childrenDept.length > 0 ? oneDeptHtml + twoDeptHtml : "";
                break;
              default:
                break;
            }
            return userHtml + deptHtml;
          },
        },
        series: [
          {
            type: "tree",
            id: 0,
            name: "tree1",
            data: [],
            top: "10%",
            left: "10%",
            bottom: "20%",
            right: "10%",
            avoidLabelOverlap: true, //防止标签重叠
            roam: true, //移动+缩放  'scale' 或 'zoom'：只能够缩放。 'move' 或 'pan'：只能够平移。
            scaleLimit: {
              //缩放比例
              min: 0.7, //最小的缩放值
              max: 4, //最大的缩放值
            },
            // layout: "orthogonal", //树图布局，orthogonal水平垂直方向，radial径向布局 是指以根节点为圆心，每一层节点为环，一层层向外
            orient: "TB", //树形方向  TB为上下结构  LR为左右结构
            // nodePadding: 100,//结点间距 （发现没用）
            //layerPadding: 30,//连接线长度 （发现没用）
            // symbol: "circle", //图形形状  rect方形  roundRect圆角 emptyCircle圆形 circle实心圆
            // symbolSize: 14, //状态大小
            edgeShape: "polyline", //线条类型  curve曲线
            initialTreeDepth: 10, //初始展开的层级
            expandAndCollapse: false, //子树折叠和展开的交互，默认打开
            lineStyle: {
              //结构线条样式
              width: 0.7,
              color: "#1E9FFF",
              type: "broken",
            },
            label: {
              //节点文本样式
              normal: {
                backgroundColor: "#81c5f7",
                position: "bottom",
                verticalAlign: "middle", //文字垂直对齐方式
                align: "center",
                borderColor: "#1E9FFF",
                color: "#fff",
                borderWidth: 1,
                borderRadius: 5,
                padding: 5,
                height: 40,
                width: 120,
                offset: [0, 30], //节点文字与圆圈之间的距离
                fontSize: 15,
                // 节点文本阴影
                shadowBlur: 10,
                shadowColor: "rgba(0,0,0,0.25)",
                shadowOffsetX: 0,
                shadowOffsetY: 2,
                overflow: "break", //break为文字折行，  truncate为文字超出部分省略号显示
                lineOverflow: "truncate", //文字超出高度后 直接截取
              },
            },
            leaves: {
              //叶子节点文本样式
              label: {
                //backgroundColor: '#81c5f7',
                backgroundColor: "#fff",
                color: "#333",
                position: "bottom",
                rotate: 0, //标签旋转。
                verticalAlign: "middle",
                align: "center",
                //文本框内文字超过6个字折行
                // formatter: function (val) {
                //   let strs = val.name.split(""); //字符串数组
                //   let str = "";
                //   for (let i = 0, s; (s = strs[i++]); ) {
                //     //遍历字符串数组
                //     str += s;
                //     if (!(i % 6)) str += "\n"; //按需要求余，目前是一个字换一行
                //   }
                //   return str;
                // },
                //或者
                overflow: "break", //break为文字折行，  truncate为文字超出部分省略号显示
                lineOverflow: "truncate", //文字超出高度后 直接截取
              },
            },
            expandAndCollapse: false, //默认展开树形结构
            animationDuration: 550,
            animationDurationUpdate: 750,
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getParams(params) {
      const { id, type } = params.data;
      console.log(params, "params");
      let path = "";
      switch (type) {
        case 0:
          path = "/postInspectionPlanning/teamManagement/guideGroup";
          break;

        case 1:
          path = "/postInspectionPlanning/teamManagement/jointOffice";
          break;

        case 2:
          path = "/postInspectionPlanning/teamManagement/workingGroup";
          break;

        case 3:
          path = "/postInspectionPlanning/teamManagement/teamMembers";
          break;

        default:
          break;
      }
      this.$router.push({
        path,
        query: { id },
      });
    },
    // copy() {
    //   const pic = this.$refs.chartsRef.getDataURL();
    //   console.log(pic, "pic", this.$refs.chartsRef);
    //   const base64Data = pic.split(",")[1];
    //   const blobInput = this.convertBase64ToBlob(base64Data, "image/png");
    //   const clipboardItemInput = new ClipboardItem({ "image/png": blobInput });
    //   navigator.clipboard.write([clipboardItemInput]).then(() => {
    //     console.log("success"); // 做一个弹窗提示
    //   });
    // },
    // convertBase64ToBlob(base64, type) {
    //   var bytes = window.atob(base64);
    //   var ab = new ArrayBuffer(bytes.length);
    //   var ia = new Uint8Array(ab);
    //   for (var i = 0; i < bytes.length; i++) {
    //     ia[i] = bytes.charCodeAt(i);
    //   }
    //   return new Blob([ab], { type: type });
    // },
    copy() {
      try {
        const textarea = document.createElement("textarea");
        const text = this.getTeamUser(
          this.xychartOption.series[0].data,
          []
        ).join(",");
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
        this.$modal.msgSuccess("复制成功");
      } catch (error) {}
    },
    handleUpdate() {
      this.$router.push("/postInspectionPlanning/teamManagement/teamMembers");
    },
    getList() {
      const dateRange = [`${this.value3}-01-01`, `${this.value3}-12-31`];
      listTeam(this.addDateRange({}, dateRange)).then((response) => {
        this.xychartOption.series[0].data = response.rows;
      });
    },
    getTeamUserByTeamId(data) {
      if (data) {
        data.map((item) => {
          if (item.type === 3) {
            getTeamUserByTeamId(item.id).then((res) => {
              res.data.forEach((d) => {
                item.children.push({
                  id: d.id,
                  name: d.type === 1 ? `${d.nickName}（组长）` : d.nickName,
                });
              });
            });
          }
          if (item.children && item.children.length > 0) {
            this.getTeamUserByTeamId(item.children);
          }
        });
        return data;
      }
    },
    getTeamUser(data, arr) {
      if (data) {
        data.map((item) => {
          arr.push(item.name);
          if (item.children && item.children.length > 0) {
            this.getTeamUser(item.children, arr);
          }
        });
        return arr;
      }
    },
  },
};
</script>

<style></style>
