<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"
          :field-names="{children: 'children', title: 'pnm', key: 'id'}"
          :auto-expand-parent="true"
          :expanded-keys="expandedKeys"
          @update:expandedKeys="expandedKeys = $event"
          v-model:selectedKeys="selectedKeys"
          ref="jigou_tree">
          <template #title="{ dataRef }">
            <span v-if="!dataRef" style="display:flex; align-items:center;"></span>
            <span v-else style="display:flex; align-items:center; justify-content:space-between; width:100%;">
              <span style="display:flex; align-items:center; min-width:0; flex:1;">
                <span v-if="dataRef.id && dataRef.id.length >= 12 && userInThisGroup(dataRef) && ownPriv('manage')" style="flex-shrink:0;">
                  <img src="../../../assets/images/choucha.png" v-if="dataRef.chkType == '0'" style="width:25px; height:20px;"/>
                  <img src="../../../assets/images/zicha.png" v-if="dataRef.chkType=='1'" style="width:25px; height:20px;"/>
                </span>
                <span v-if="orgType == '1110'" :style="{color: dataRef.colour, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}">{{ dataRef.pnm ? (dataRef.pnm.length > 12 ? (dataRef.pnm.substring(0, 10)) + '...' : dataRef.pnm) : '' }}</span>
                <span v-else style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">{{ dataRef.pnm ? (dataRef.pnm.length > 12 ? (dataRef.pnm.substring(0, 10)) + '...' : dataRef.pnm) : '' }}</span>
                <a-button
                  v-if="dataRef.id && dataRef.id.length > 6 && userInThisGroup(dataRef) && ownPriv('manage')"
                  type="danger"
                  ghost
                  size="small"
                  shape="circle"
                  @click="() => deletePICI(dataRef)"
                  style="border:0; margin-left:4px; flex-shrink:0;"><CloseCircleOutlined /></a-button>
              </span>
              <span style="display:flex; align-items:center; gap:4px; flex-shrink:0; margin-left:8px;">
                <a-button
                  v-if="dataRef.id && dataRef.id.length < 10"
                  type="primary"
                  ghost
                  size="small"
                  @click="() => addPICI(dataRef, '批次')"
                  style="border:0;">新建</a-button>
                <EditOutlined @click="modifyPICI(dataRef,'批次')" style="color:#009fff; cursor:pointer;"/>
                <a-tooltip>
                  <template #title>
                    <div v-if="dataRef.sttm">{{ dataRef.sttm }} ~ {{ dataRef.entm }}</div>
                    <div v-else>无</div>
                  </template>
                  <ClockCircleOutlined style="cursor:pointer;"/>
                </a-tooltip>
              </span>
            </span>
          </template>
        </a-tree>
      </div>
      <!-- 添加批次、添加组弹窗 -->
      <a-modal :title="'新建' + addTypeText" :open="addPICIDialogVisible" @ok="appendPICI" @cancel="addPICIDialogVisible = false">
        <a-form :model="piciForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-form-item :label="addTypeText + '名称'">
            <a-input v-model:value="piciForm.name" placeholder="请输入内容"/>
          </a-form-item>
          <a-form-item label="时间范围" v-if="currentSelectTreeNodeId.length > 3">
            <a-range-picker :value="createValue" format="YYYY-MM-DD" separator="至" @change="onChange"/>
          </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="addTypeText + '名称'">
            <a-input v-model:value="piciForm.name" placeholder="请输入内容"/>
          </a-form-item>
          <a-form-item label="时间范围" v-if="currentSelectTreeNodeId.length > 3">
            <a-range-picker :value="createValue" format="YYYY-MM-DD" separator="至" @change="onChange"/>
          </a-form-item>
          <a-form-item label="是否门户展示" v-if="isShowPortal && (orgType == '111' || orgType == '1110')">
            <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 moment from 'moment';
import request from '@/utils/gw_ajax_request';
import { Modal } from 'ant-design-vue';
import { dateFormat } from '@/utils/gw_date';
import { getTrees } from '@/utils/gw_formatTree';
import { EditOutlined, ClockCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue';
export default {
  emits: ['sendCurrentNodeinfo'],
  props: ['orgType'],
  components: { EditOutlined, ClockCircleOutlined, CloseCircleOutlined },
  data() {
    return {
      treeHeight: window.innerHeight - 190,
      treeData: [],
      expandedKeys: [],
      selectedKeys: [],
      treeInfoOrigin: null, // 原始后台返回的树数据结构
      currentSelectTreeNode: {
        currentSelectTreeNodeName: '',
        currentSelectTreeNodeCode: '',
        currentSelectTreeNodeType: '',
        currentSelectTreeNodeId: '',
      },
      deleteFlag: false,
      plnaTreeCode: '',
      plnaTreeName: '',
      plnaTreeType: '',
      addPICITreeNode: '',
      addPICIDialogVisible: false,
      isShowPortal: null,
      createValue: [],
      piciForm: {
        name: '',
        startDate: '',
        endDate: '',
        isPortal: '',
        isPortalBool: false,
      },
      addTypeText: '',
      moment,
      modifyPICIDialogVisible: false,
      addType: '',
      addZUTreeNode: '',
      addZuDialogVisible: false,
    };
  },
  computed: {
    userInAllNode() {
      // 当前登录用户所在的所有组信息
      return JSON.parse(localStorage.getItem('allNode'))
        ? JSON.parse(localStorage.getItem('allNode'))
        : [];
    },
    orgId() {
      return localStorage.getItem('guid') ? localStorage.getItem('guid') : '';
    },
    persId() {
      return localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '';
    },
    currentSelectTreeNodeId() {
       return this.currentSelectTreeNode.currentSelectTreeNodeId;
    },
  },
  created() {},
  mounted() {
    if (this.orgType) {
      this.getLeftTreeData();
    }
  },
  methods: {
    searchOption(option, arr) {
      for (let s = 0; s < arr.length; s++) {
        if (arr[s].key === option.key) {
          arr.splice(s, 1);
          this.$message.success('删除成功!');
          break;
        } else if (arr[s].children && arr[s].children.length > 0) {
          // 递归条件
          this.searchOption(option, arr[s].children);
        } else {
        }
      }
    },
    hasPriv1(item) {
      return this.ownPriv(item);
    },
    getLeftTreeData() {
      // 根据用户id获取左侧树
      this.expandedKeys = [];
      const type = this.orgType == '1110' ? '111' : this.orgType;
      request
        .get('/dc/organization/base/getAllNode', {
          params: { userId: this.persId, orgType: type },
        })
        .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((item) => {
            item.scopedSlots = scopedSlots;
            if (item.children && item.children.length > 0) {
              item.children.forEach((item1) => {
                item1.scopedSlots = scopedSlots;
                if (item1.children && item1.children.length > 0) {
                  item1.children.forEach((item2) => {
                    item2.scopedSlots = scopedSlots;
                  });
                }
              });
            }
          });

          this.treeData = data;
          this.expandedKeys.push(data[0].id);
          this.currentSelectTreeNode.currentSelectTreeNodeId =
            this.treeData[0].id;
          this.$emit('sendCurrentNodeinfo', { ...this.currentSelectTreeNode });
        });
    },
    userInThisGroup(item) {
      // 判断当前用户 是否在该节点下   在 则没有删除权限
      if (this.userInAllNode && this.userInAllNode.length > 0) {
        for (var i = 0; i < this.userInAllNode.length; i++) {
          if (this.userInAllNode[i].id.substring(0, 3) == '001') {
            if (item.id.length > this.userInAllNode[i].id.length) {
              return true;
            } else {
              return false;
            }
          } else {
            return true;
          }
        }
      } else {
        return true;
      }
    },
    treeNodeClickHandler(selectedKeys, e) {
      //debugger
      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;
      Modal.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();
              }
            }
          });
          return Promise.resolve();
        },
        onCancel: () => {
          this.$message.info('已取消删除');
        },
      });
    },
    addPICI(nodeData, addType) {
      this.addPICITreeNode = nodeData;
      this.isShowPortal = this.addPICITreeNode.id.length == 6;
      this.piciForm.name = '';
      this.piciForm.isPortal = '0';
      this.piciForm.isPortalBool = false;
      this.createValue = [];
      // 默认继承父节点的时间属性
      this.piciForm.startDate = [];
      if (!nodeData.sttm || !nodeData.entm) {
        this.piciForm.startDate = [];
      } else {
        this.piciForm.startDate = [nodeData.sttm, nodeData.entm];
      }
      this.addPICIDialogVisible = true;
    },
    appendPICI() {
      const params = {
        prsnTitle: this.piciForm.name,
        guid: this.addPICITreeNode.id,
        palnSttm: this.piciForm.startDate[0],
        palnEntm: this.piciForm.startDate[1],
        isPortal: this.piciForm.isPortal,
      };
      if (!this.piciForm.startDate.length) {
        this.$message.warning('请选择开始和结束时间');
        return;
      }
      request.post('/dc/insp/plan/addBisInspPlan', params).then((res) => {
        const sttmstamp =
          moment(params.palnSttm, 'YYYY-MM-DD').startOf('day').format('x') * 1;
        const entmstamp =
          moment(params.palnEntm, 'YYYY-MM-DD').startOf('day').format('x') * 1;
        const newChild = {
          id: res.data.code,
          pid: this.addPICITreeNode.id,
          pnm: this.piciForm.name,
          sttm: params.palnSttm,
          entm: params.palnEntm,
          sttmstamp: sttmstamp,
          entmstamp: entmstamp,
          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);
        // _self.$refs['jigou_tree'].append(newChild, _self.addPICITreeNode.id)
        this.addPICIDialogVisible = false;
        this.getLeftTreeData();
      });
    },
    onChange(date, dateString) {
      this.createValue = date;
      this.piciForm.startDate = dateString;
    },
    modifyPICI(nodeData, addType) {
      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.piciForm.startDate = [
        this.addPICITreeNode.sttmstamp,
        this.addPICITreeNode.entmstamp,
      ];
      this.createValue = [
        moment(this.addPICITreeNode.sttmstamp),
        moment(this.addPICITreeNode.entmstamp),
      ];
      this.modifyPICIDialogVisible = true;
    },
    modifyPICIInfo() {
      const params = {
        pnm: this.piciForm.name,
        id: this.addPICITreeNode.id,
        sttm:
          moment(this.piciForm.startDate[0], 'YYYY-MM-DD')
            .startOf('day')
            .format('x') * 1,
        entm:
          moment(this.piciForm.startDate[1], 'YYYY-MM-DD')
            .startOf('day')
            .format('x') * 1,
        isPortal: this.piciForm.isPortal,
      };
      if (!this.piciForm.startDate.length) {
        this.$message.warning('请选择开始和结束时间');
        return;
      }
      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.sttm = !isNaN(params.sttm)
                  ? dateFormat(params.sttm, 'yyyy-MM-dd')
                  : params.sttm;
                ele.entm = !isNaN(params.entm)
                  ? dateFormat(params.entm, 'yyyy-MM-dd')
                  : params.entm;
                ele.pnm = this.piciForm.name;
                ele.isPortal = this.piciForm.isPortal;
                ele.isPortalBool = this.piciForm.isPortal === '1';
              }
            });
            this.$message.success('修改成功');
          }
          this.modifyPICIDialogVisible = false;
          this.getLeftTreeData();
        }
      });
    },
    getIsPortal(checked, e) {
      this.piciForm.isPortal = checked === true ? '1' : '0';
      this.piciForm.isPortalBool = checked;
    },
    addZU(node, nodeData) {
      this.addZUTreeNode = node.data;
      this.addZuDialogVisible = true;
    },
    appendZU() {
      const params = {
        guid: this.orgId,
        headmanId: this.groupLeaderId,
        inspGroupName: this.zuForm.name,
        memberId: this.memberId,
        plnaId: this.addZUTreeNode.code,
        downStat: 2,
        note: '备注',
      };
      request.post('/dc/insp/group/insertGroup', params).then((res) => {
        const newChild = {
          code: res.data.code,
          type: res.data.type,
          name: res.data.name,
        };
        // to-do 改这里
        this.$refs['jigou_tree'].append(newChild, this.addZUTreeNode.code);
        this.addZuDialogVisible = false;
        this.isGroupLeader = '';
        this.zuForm.name = '';
      });
    },
    deleteZU(node, data) {
      this.$confirm('是否删除督查组:' + data.name + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          request
            .post(`/dc/insp/group/delete?id=${node.data.code}`)
            .then((res) => {
              // this.$refs.jigou_tree.remove(node)
              this.$message.success('删除成功');
            });
        })
        .catch(() => {
          this.$message.info('已取消删除');
        });
    },
  },
  watch: {
    orgType(val) {
      if (val) {
        this.getLeftTreeData();
      }
    },
  },
};
</script>

<style scoped>
.tree_group{
  .custom-tree-node{
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 15px;
    padding-right: 8px;
  }
}
::v-deep .ant-tree-node-content-wrapper.ant-tree-node-selected {
  background-color: #e6f7ff !important;
}
::v-deep .ant-tree-treenode-selected {
  background-color: #e6f7ff !important;
}
</style>
