<template>
  <div class="grid-content bg-purple tree_group" :style="{'height': treeHeight + 'px'}">
    <a-card title="分工节点" style="height: 100%">
      <!-- 左侧树 -->
      <div :style="{'height': (treeHeight - 70) + 'px','overflow':'auto'}">
        <a-tree
          :tree-data="treeData"
          @expand="treeOpened"
          @select="treeNodeClickHandler"
          :fieldNames="{children: 'children', title: 'pnm', key: 'id'}"
          :auto-expand-parent="true"
          :expanded-keys="expandedKeys" @update:expandedKeys="expandedKeys = $event"
          ref="jigou_tree">
          <template #title="{ dataRef }">
            <span style="float:left; position: relative;" :title="dataRef.pnm">
              <span v-if="dataRef.id && dataRef.id.length >= 12 && userInThisGroup(dataRef)">
                <img src="../../../assets/images/choucha.png" v-if="dataRef.chkType == '0'" style="width: 25px; height:20px; margin-top: 3px; float: left;"/>
                <img src="../../../assets/images/zicha.png" v-if="dataRef.chkType=='1'" style="width: 25px; height:20px; margin-top: 3px; float: left;"/>
                &nbsp;
              </span>
              {{ dataRef.pnm ? (dataRef.pnm.length > 12 ? (dataRef.pnm.substring(0, 10)) + "..." : dataRef.pnm) : "" }}
              <a-button
                v-if="dataRef.id && dataRef.id.length > 6 && userInThisGroup(dataRef)"
                type="danger"
                icon="close-circle"
                ghost
                size="small"
                shape="circle"
                @click="() => deletePICI(dataRef)"
                style="border: 0;"></a-button>
            </span>
            <div style="float:right; display: flex; justify-content: flex-end; align-items: center; width:50%;">
              <span style="color:blue;width:60px;">
                <a-button
                  v-if="dataRef.id && dataRef.id.length < 10"
                  type="primary"
                  icon="plus-circle"
                  ghost
                  size="small"
                  @click="() => addPICI(dataRef, '批次')"
                  style="border: 0;">新建</a-button>
              </span>
              <span style="width:30px;color: #009fff;">
                <EditOutlined @click="modifyPICI(dataRef,'批次')" style="color: #009fff;"/>
              </span>
            </div>
          </template>
        </a-tree>
      </div>
      <!-- 添加批次、添加组弹窗 -->
      <a-modal title="新建" :open="addPICIDialogVisible" @ok="appendPICI" @cancel="addPICIDialogVisible = false">
        <a-form :model="piciForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-form-item label="名称">
            <a-input v-model:value="piciForm.name" placeholder="请输入内容"/>
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 修改批次、组信息弹窗 -->
      <a-modal title="信息修改" :open="modifyPICIDialogVisible" @ok="modifyPICIInfo" @cancel="modifyPICIDialogVisible = false">
        <a-form :model="piciForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-form-item label="名称">
            <a-input v-model:value="piciForm.name" placeholder="请输入内容"/>
          </a-form-item>
          <a-form-item label="是否门户展示" v-if="isShowPortal">
            <a-switch v-model="piciForm.isPortalBool" checked-children="是" un-checked-children="否" @click="getIsPortal" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import request from '@/utils/gw_ajax_request';
import { dateFormat } from '@/utils/gw_date';
import { getTrees } from '@/utils/gw_formatTree';
import { EditOutlined } from '@ant-design/icons-vue';
export default {
  components: { EditOutlined },
  data() {
    return {
      treeHeight: window.innerHeight - 110,
      treeData: [],
      expandedKeys: [],
      treeInfoOrigin: null, // 原始后台返回的树数据结构
      currentSelectTreeNode: {
        currentSelectTreeNodeName: '',
        currentSelectTreeNodeCode: '',
        currentSelectTreeNodeType: '',
        currentSelectTreeNodeId: '',
      },
      deleteFlag: false,
      plnaTreeCode: '',
      plnaTreeName: '',
      plnaTreeType: '',
      addPICITreeNode: '',
      addPICIDialogVisible: false,
      isShowPortal: null,
      piciForm: {
        name: '',
        isPortal: '',
        isPortalBool: false,
      },
      modifyPICIDialogVisible: false,
    };
  },
  computed: {
    userInAllNode() {
      // 当前登录用户所在的所有组信息
      return JSON.parse(localStorage.getItem('allNode'))
        ? JSON.parse(localStorage.getItem('allNode'))
        : [];
    },
    persId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '';
    },
  },
  created() {
    this.getLeftTreeData();
  },
  mounted() {},
  methods: {
    getLeftTreeData() {
      // 根据用户id获取左侧树
      this.expandedKeys = [];
      request
        .get('/dc/organization/base/getAllNode', {
          params: { userId: this.persId, orgType: '112', groupType: '1' },
        })
        .then((res) => {
          let data = res.data;
          this.treeInfoOrigin = res.data;
          data.forEach((ele) => {
            if (!ele.sttm) {
              ele.sttm = '';
            } else if (!isNaN(ele.sttm)) {
              ele.sttmstamp = ele.sttm;
              ele.sttm = dateFormat(ele.sttm, 'yyyy-MM-dd');
            }
            if (!ele.entm) {
              ele.entm = '';
            } else if (!isNaN(ele.entm)) {
              ele.entmstamp = ele.entm;
              ele.entm = dateFormat(ele.entm, 'yyyy-MM-dd');
            }
          });
          data = getTrees(data);

          const scopedSlots = {
            title: 'custom',
          };
          data.forEach((dataRef) => {
            dataRef.scopedSlots = scopedSlots;
            if (dataRef.children && dataRef.children.length > 0) {
              dataRef.children.forEach((item1) => {
                item1.scopedSlots = scopedSlots;
                if (item1.children && item1.children.length > 0) {
                  item1.children.forEach((item2) => {
                    item2.scopedSlots = scopedSlots;
                  });
                }
              });
            }
          });

          this.treeData = data;
          if (this.treeData.length) {
            this.expandedKeys.push(data[0].id);
            this.currentSelectTreeNode.currentSelectTreeNodeId =
              this.treeData[0].id;
          }
          this.$emit('sendCurrentNodeinfo', this.currentSelectTreeNode);
        });
    },
    userInThisGroup(dataRef) {
      // 判断当前用户 是否在该节点下   在 则没有删除权限
      if (this.userInAllNode && this.userInAllNode.length > 0) {
        for (var i = 0; i < this.userInAllNode.length; i++) {
          console.log(
            this.userInAllNode[i].id,
            this.userInAllNode[i].id.substring(0, 3),
            dataRef.id.length,
          );
          if (this.userInAllNode[i].id.substring(0, 3) == '001') {
            if (dataRef.id.length >= this.userInAllNode[i].id.length) {
              return true;
            } else {
              return false;
            }
          } else {
            return true;
          }
        }
      } else {
        return true;
      }
    },
    treeNodeClickHandler(selectedKeys, e) {
      const { dataRef: data } = e.node;
      if (this.deleteFlag) {
        // 如果点击删除节点   则不更新节点id
        this.deleteFlag = false;
        return;
      }
      // this.duChaType = data.id.substring(2,3);
      this.currentSelectTreeNode.currentSelectTreeNodeName = data.name;
      this.currentSelectTreeNode.currentSelectTreeNodeCode = data.code;
      this.currentSelectTreeNode.currentSelectTreeNodeType = data.type;
      this.currentSelectTreeNode.currentSelectTreeNodeId = data.id;
      this.currentSelectTreeNode.currentSelectTreeNodePsn = data.psn;
      this.$emit('sendCurrentNodeinfo', this.currentSelectTreeNode);
      if (data.type == '3') {
        this.plnaTreeCode = data.code;
        this.plnaTreeName = data.name;
        this.plnaTreeType = data.type;
      }
    },
    treeOpened(expandedKeys, e) {
      const { dataRef: data } = e.node;
      this.currentSelectTreeNode.currentSelectTreeNodeName = data.name;
      this.currentSelectTreeNode.currentSelectTreeNodeCode = data.code;
      this.currentSelectTreeNode.currentSelectTreeNodeType = data.type;
      this.currentSelectTreeNode.currentSelectTreeNodeId = data.id;
      this.$emit('sendCurrentNodeinfo', this.currentSelectTreeNode);
      if (data.type == '3') {
        this.plnaTreeCode = data.code;
        this.plnaTreeName = data.name;
        this.plnaTreeType = data.type;
      }
    },
    deletePICI(data) {
      this.deleteFlag = true;
      this.$confirm({
        title: '提示',
        content: '是否删除批次' + data.pnm + '及关联督查组?',
        okType: 'info',
        onOk: () => {
          request.post(`/dc/insp/plan/${data.id}`).then((res) => {
            if (res.success) {
              if (res.message == '请先删除人员或对象') {
                this.$message.warning('请先删除组内人员、对象及区域!');
              } else {
                this.$message.success('删除成功!');
                this.getLeftTreeData();
              }
            }
          });
        },
        onCancel: () => {
          this.$message.info('已取消删除');
        },
      });
    },
    addPICI(nodeData) {
      this.addPICITreeNode = nodeData;
      this.isShowPortal = this.addPICITreeNode.id.length == 6;
      this.piciForm.name = '';
      this.piciForm.isPortal = '0';
      this.piciForm.isPortalBool = false;
      // 默认继承父节点的时间属性
      this.addPICIDialogVisible = true;
    },
    appendPICI() {
      if (!this.piciForm.name) {
        return this.$message.info('名称不能为空!');
      }
      const params = {
        prsnTitle: this.piciForm.name,
        guid: this.addPICITreeNode.id,
        isPortal: this.piciForm.isPortal,
        groupType: '1',
      };
      request.post('/dc/insp/plan/addBisInspPlan', params).then((res) => {
        if (res.success) {
          const newChild = {
            id: res.data.code,
            pid: this.addPICITreeNode.id,
            pnm: this.piciForm.name,
            children: [],
            isPortal: this.piciForm.isPortal,
            isPortalBool: this.piciForm.isPortal === '1',
          };
          newChild.scopedSlots = { title: 'custom' };
          newChild.key = res.data.code;

          if (!this.addPICITreeNode.children) {
            this.addPICITreeNode.children = [];
          }

          // to-do wxcwater 改这里。
          this.addPICITreeNode.children.push(newChild);
          this.addPICIDialogVisible = false;
          this.getLeftTreeData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    modifyPICI(nodeData) {
      this.addPICITreeNode = nodeData;
      this.isShowPortal = this.addPICITreeNode.id.length == 9;
      this.piciForm.isPortal = nodeData.isPortal;
      this.piciForm.isPortalBool = nodeData.isPortal === '1';
      this.piciForm.name = this.addPICITreeNode.pnm;
      this.modifyPICIDialogVisible = true;
    },
    modifyPICIInfo() {
      const params = {
        pnm: this.piciForm.name,
        id: this.addPICITreeNode.id,
        isPortal: this.piciForm.isPortal,
        groupType: '1',
      };
      request.post('/dc/insp/plan/updateBisInspAll', params).then((res) => {
        if (res.success) {
          if (this.treeInfoOrigin.length) {
            // 修改时间后遍历更新当前节点时间信息
            this.treeInfoOrigin.forEach((ele) => {
              if (ele.id == this.addPICITreeNode.id) {
                ele.pnm = this.piciForm.name;
                ele.isPortal = this.piciForm.isPortal;
                ele.isPortalBool = this.piciForm.isPortal === '1';
              }
            });
            this.$message.success('修改成功');
          }
          this.modifyPICIDialogVisible = false;
          this.getLeftTreeData();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getIsPortal(checked, e) {
      this.piciForm.isPortal = checked === true ? '1' : '0';
      this.piciForm.isPortalBool = checked;
    },
  },
};
</script>

<style lang='less' scoped>
.tree_group{
  .custom-tree-node{
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
    padding-right: 8px;
  }
}
</style>
