<template>
  <div class="app-container">
    <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="handleUpdate"
          v-hasPermi="['postCheck:team:edit']"
          >编辑</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>

    <el-dialog
      title="编辑"
      :visible="editTreeDialog"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="updateTree"
    >
      <el-tree
        :data="deptOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        ref="tree"
        node-key="id"
        default-expand-all
        highlight-current
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              v-show="[0, 1, 2].includes(data.type)"
              type="text"
              style="color: #67c23a"
              icon="el-icon-plus"
              @click="() => append(data)"
            >
            </el-button>
            <el-button
              v-if="[1, 2, 3].includes(data.type)"
              type="text"
              icon="el-icon-minus"
              style="color: #f56c6c"
              @click="() => remove(data)"
            >
            </el-button>
            <el-button
              v-if="[0, 1, 2, 3].includes(data.type)"
              type="text"
              style="color: #909399"
              icon="el-icon-edit"
              @click="() => edit(data)"
            >
            </el-button>
          </span>
        </span>
      </el-tree>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible="editDialog"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="reset"
    >
      <el-form
        ref="treeForm"
        :model="treeForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="名称：" prop="name">
          <el-input v-model="treeForm.name" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="batch-dialog-footer">
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
        <el-button @click="reset"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTeam,
  getTeamUserByTeamId,
  delTeam,
  addTeam,
  updateTeam,
} from "@/api/postInspectionPlanning/teamManagement.js";
export default {
  data() {
    let _now = new Date();
    let currentYear = _now.getFullYear();
    return {
      treeData: {},
      value3: `${currentYear}`,
      // 部门树选项
      title: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      deptOptions: [],
      treeForm: {
        name: "",
      },
      editDialog: false,
      editTreeDialog: false,
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
      },
      xychartOption: {
        tooltip: {
          trigger: "item",
          triggerOn: "mousemove",
          formatter: function (params) {
            // console.log(params, "params");
          }
        },
        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.getDeptTree();
  },
  methods: {
    updateTree() {
      this.editTreeDialog = false;
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      const dateRange = [`${this.value3}-01-01`, `${this.value3}-12-31`];
      listTeam(this.addDateRange({}, dateRange)).then((response) => {
        if (response.rows.length === 0) {
          const params = {
            name: "岗检领导小组",
            parentId: 0,
            type: 0,
          };
          addTeam(params).then((response) => {
            this.getList();
          });
        } else {
          this.deptOptions = response.rows;
          this.xychartOption.series[0].data = response.rows;
        }
      });
    },
    append(data) {
      this.editDialog = true;
      this.treeData = data;
      this.title = "新增";
    },

    remove(data) {
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delTeam(data.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    edit(data) {
      this.editDialog = true;
      this.treeData = data;
      this.treeForm.name = data.name;
      this.title = "修改";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["treeForm"].validate((valid) => {
        if (valid) {
          if (this.title === "修改") {
            updateTeam({
              name: this.treeForm.name,
              type: this.treeData.type,
              id: this.treeData.id,
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.editDialog = false;
              this.reset();
              this.getList();
            });
          } else {
            const params = {
              name: this.treeForm.name,
              parentId: this.treeData.id,
              type: this.treeData.type + 1,
            };
            addTeam(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.editDialog = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    getParams(params) {
      console.log(params, "params");
    },
    // 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.editTreeDialog = true;
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.treeForm.name = "";
      this.resetForm("treeForm");
      this.editDialog = false;
    },
    getList() {
      const dateRange = [`${this.value3}-01-01`, `${this.value3}-12-31`];
      listTeam(this.addDateRange({}, dateRange)).then((response) => {
        this.deptOptions = response.rows;
        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 lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
