<template>
  <div style="width:208px">
    <div style="margin:2px 2px 2px 2px;display: flex;">
      <el-tooltip content="勾选时，可对子单位进行查询" placement="top">
        <el-checkbox style="margin-top: 6px;" v-model="cusQuery.haveSunCus" true-label="Y" false-label="N" size="small">
          含子单位
        </el-checkbox>
      </el-tooltip>
      <el-input placeholder="输入关键字进行过滤" v-model="filterText" size="small" />
    </div>
    <div>
      <el-tree
        :style="'overflow: scroll;height:' + (window.pageHeight < 600 ? 465 : window.pageHeight - 135) + 'px;width:200px;'"
        :data="customerOrgTreeAll" :props="treeprops" node-key="id" @node-contextmenu="nodeContextmenu"
        :filter-node-method="filterNode" @node-click="treeclick" highlight-current ref="customerOrgTree"
        :load="loadNode" lazy>
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <div>
            <span class="treeicons">
              <!-- <i
                class="el-icon-document-remove"
                v-if="data.parentId == null"
              ></i> -->
              <img style="width:20px;height:20px;vertical-align: sub;" src="@/assets/images/order.png"
                v-if="!data.parentId" />
            </span>
            <span :class="!data.parentId ? 'maxtitle' : 'mintitle'">{{ node.label }}
            </span>
          </div>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { tcdate, deepCopy, reMadeOrgTree, arrayExistObj, updateDBCom, getDBCom } from "../../utlis/proFunc";


import { madeTree, getTreeAllChildIdsById, getTreeNode } from "@/utlis/tree";
import { now } from "moment";
export default {
  components: {},
  data() {
    return {
      filterText: '',
      treeprops: {
        label: "label",
        value: "id",
        id: "id",
        children: "treeChildren",
        isLeaf: "isLeaf"
      }, //树形组件的数据结构
      LocalConfig: {
        patientRegister: {
          dispCustomerOrgCode: 'N', // 人员登记列表--单位树是否显示 customerOrgCode
        }
      },
      customerOrgTreeAll: [],  //显示的
      orgDatas: [],  // 最初获取的

      //作用于子单位查询
      cusQuery: {
        treeDataAll: [],  //所有单位节点数据
        treeDataTop1: [], // 顶级单位
        haveSunCus: 'Y', // 默认查询不包含子单位
        times: 0,  // 如果 times > 0 之后，来回勾选（含子单位查询时，不在查全部单位）
      }

    };
  },

  computed: {
    ...mapState(["window", "dict", "dataTransOpts", "customerOrg", "patientRegister"]),
  },
  //创建组件后
  created() {
    this.patientRegister.customerOrgs = []
    try {
      let LocalConfig = JSON.parse(window.localStorage.getItem('LocalConfig'))
      if (LocalConfig && LocalConfig.patientRegister) {
        if (LocalConfig.patientRegister.dispCustomerOrgCode) this.LocalConfig.patientRegister.dispCustomerOrgCode = LocalConfig.patientRegister.dispCustomerOrgCode
      }
    } catch (error) {
      console.log("window.localStorage.getItem('LocalConfig')", error)
    }
  },

  //挂载组件完成
  mounted() {
    //获取体检单位列表树信息 (Y:查所有单位，N：仅查顶级单位)     
    //从性能考滤 默认只查顶级单位  
    if (this.cusQuery.haveSunCus == 'Y') {
      this.getCustomerOrgAll()
        .then(res => {
          this.customerOrgTreeAll = res
          this.patientRegister.customerOrgTreeAll = res
          // console.log('this.customerOrgTreeAll', this.customerOrgTreeAll)
        })
    } else {
      //console.log('new Date()1', now())
      this.getCustomerOrgChild(null)
        .then(res => {
          this.customerOrgTreeAll = res //.slice(0,3)
          this.patientRegister.customerOrgTreeAll = res
          // console.log('this.customerOrgTreeAll', this.customerOrgTreeAll)
          //console.log('new Date()2', now())
        })
    }

  },

  methods: {

    // 后续代完善
    getOrgDatas() {
      return new Promise((resolve, reject) => {
        let url = '/api/app/CustomerOrg/GetSimpleByCodeAll'
        if (this.LocalConfig.patientRegister.dispCustomerOrgCode == 'Y') {
          url = "/api/app/customerorg/getbycodeall"
          getapi(url)
            .then((res) => {
              if (res.code > -1) {
                this.orgDatas = res.data
                updateDBCom('orgDatas',res.data) //存本地
                resolve()
              } else {
                reject(res.message)
              }
            })
            .catch(err => {
              reject(err)
            })
        } else {
          postapi(url)
            .then((res) => {
              if (res.code > -1) {
                this.orgDatas = res.data
                updateDBCom('orgDatas',res.data)
                resolve()
              } else {
                reject(res.message)
              }
            })
            .catch(err => {
              reject(err)
            })
        }

      })
    },

    // 查所有单位
    getCustomerOrgAll() {
      return new Promise((resolve, reject) => {
        if (this.dataTransOpts.orgDatas.length > 0) {
          let treeData = reMadeOrgTree(deepCopy(this.dataTransOpts.orgDatas), this.LocalConfig.patientRegister.dispCustomerOrgCode);
          this.cusQuery.times += 1
          //console.log('getCustomerOrgAll.treeData', treeData)
          //console.log('getTreeNode', getTreeNode(treeData, "treeChildren", 'id', '3a1d3736-d7c6-a9fb-c165-675335dc0e9b').treeChildren)
          this.cusQuery.treeDataAll = treeData
          resolve(treeData)
        } else {
          this.getOrgDatas()
            .then(() => {
              let treeData = reMadeOrgTree(deepCopy(this.dataTransOpts.orgDatas), this.LocalConfig.patientRegister.dispCustomerOrgCode);
              this.cusQuery.times += 1
              //console.log('getCustomerOrgAll.treeData', treeData)
              //console.log('getTreeNode', getTreeNode(treeData, "treeChildren", 'id', '3a1d3736-d7c6-a9fb-c165-675335dc0e9b').treeChildren)
              this.cusQuery.treeDataAll = treeData
              resolve(treeData)
            })
            .catch(err => {
              reject(err)
            })
        }
      })
    },

    // 只查顶级单位
    getCustomerOrgChild(parentId) {
      return new Promise((resolve, reject) => {
        console.log('new Date()3', now())
        let url = '/api/app/CustomerOrg/GetCustomerOrgSimpleByParentId'
        if (this.LocalConfig.patientRegister.dispCustomerOrgCode == 'Y') {
          url = '/api/app/CustomerOrg/GetCustomerOrgByParentId'
        }
        postapi(url, { parentId })
          .then(res => {
            if (res.code > -1) {
              console.log('new Date()4', now())
              res.data.forEach(e => {
                e.isLeaf = e.isChild == 'Y' ? false : true
              });
              let treeData = reMadeOrgTree(deepCopy(res.data), this.LocalConfig.patientRegister.dispCustomerOrgCode);
              treeData.forEach(e => {
                if (arrayExistObj(this.patientRegister.customerOrgs, 'id', e.id) == -1) {
                  this.patientRegister.customerOrgs.push(e)
                }
              });
              //this.patientRegister.customerOrgTreeAll = madeTree(this.patientRegister.customerOrgs, 'treeChildren', 'parentId', 'id', null)
              // console.log('this.patientRegister.customerOrgTreeAll', this.patientRegister.customerOrgTreeAll)
              if (!parentId) this.cusQuery.treeDataTop1 = treeData
              resolve(treeData)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    // 树节点懒加载
    loadNode(node, resolve) {
      // console.log('node', node)
      // console.log('this.cusQuery.treeDataAll', this.cusQuery.treeDataAll)
      // console.log('this.patientRegister.customerOrgTreeAll1', this.patientRegister.customerOrgTreeAll)
      // 只显示顶级单
      if (node?.data?.id) {
        if (this.cusQuery.times == 0) {
          this.getCustomerOrgChild(node.data.id).then(res => {
            console.log('res', res)
            resolve(res)
          }).catch(err => {
            resolve([])
          })
        } else {
          let ret = getTreeNode(this.cusQuery.treeDataAll, this.treeprops.children, this.treeprops.children.id, node.data.id)[this.treeprops.children]
          ret = ret || []
          ret.forEach(e => {
            if (!e[this.treeprops.children]) e.isLeaf = true
          });
          //console.log('ret',ret)
          resolve(ret)
        }
      }
    },

    // 节点右击事件
    nodeContextmenu(event, data, node, ids) {
      console.log('event,data,node,ids', event, data, node, ids)
      if (data.id == this.dict.personOrgId) return

      let items = [
        {
          label: "置顶",
          onClick: () => {
            this.treeSort(data, 1);
          },
        },
        {
          label: "置底",
          onClick: () => {
            this.treeSort(data, 2);
          },
        }
      ] //菜单项
      this.$contextmenu({
        items,
        event,
        //x: event.clientX,
        //y: event.clientY,
        customClass: "custom-class",
        zIndex: 3,
        minWidth: 80,
      });
      return false;

    },

    // 树节点排序
    treeSort(data, sortType) {
      console.log('data', data)
      // if (data.parentId) {
      //   this.$message.warning({ showClose: true, message: "请选择一级单位" })
      //   return
      // }
      // console.log('data,sortType',data,sortType)
      putapi(`/api/app/customerorg/updatemanysort?id=${data.id}&SortType=${sortType}`).then(res => {
        if (res.code > -1) {
          //如果选的是子级排序，则只更新子级数据

          this.getCustomerOrgChild(data.parentId).then(res => {
            data.treeChildren = res
            if (data.parentId == null) {
              this.customerOrgTreeAll = res
              this.patientRegister.customerOrgTreeAll = deepCopy(res)
            }
          })
        }
      })
    },

    //顶级单位树过滤
    filterParentNode(value) {
      console.log('filterParentNode', value)
      // if (!value) return true;
      // return data['displayName'].indexOf(value) > -1 || data['simpleCode'].indexOf(value.toUpperCase()) > -1 || data['shortName'].indexOf(value) > -1 || data['customerOrgCode'].indexOf(value) > -1;
      this.customerOrgTreeAll = this.cusQuery.treeDataTop1.filter(e => {
        return e.label.indexOf(value) > -1 || e.simpleCode.indexOf(value.toUpperCase()) > -1
      })

    },

    //全树过滤
    filterNode(value, data) {
      console.log('filterNode', value, data)
      if (!value) return true;
      return data['displayName'].indexOf(value) !== -1 || data['simpleCode'].indexOf(value.toUpperCase()) !== -1;
    },

    //点击树节点
    treeclick(data) {
      // console.log('data',data)

      this.patientRegister.query.customerOrgId = data.id;
      this.patientRegister.query.customerOrgName = data.displayName;
      this.dataTransOpts.plus.PatientRegisterEditQuery++


      //获取体检单位父级ID
      // this.getCustomerOrgParentId(data.id);
      // this.patientRegister.query.times++; //用于触发查询条件
    },
  },
  watch: {
    "filterText": {
      // immediate: true,
      handler(newVal, oldVal) {
        // console.log(`watch 人员登记 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.dataTransOpts.tableS.patient_register.id}`);
        if (newVal != oldVal) {
          if (this.cusQuery.haveSunCus == 'Y') {
            //this.customerOrgTreeAll = deepCopy(this.cusQuery.treeDataAll)
            this.$refs['customerOrgTree'].filter(newVal);
          } else {
            this.filterParentNode(newVal)
          }
        }
      }
    },
    // 勾选含子单位 查询所有单位
    "cusQuery.haveSunCus": {
      // immediate: true,
      handler(newVal, oldVal) {
        // console.log(`watch 人员登记 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.dataTransOpts.tableS.patient_register.id}`);
        if (newVal != oldVal && newVal == 'Y' && this.cusQuery.times == 0) this.getCustomerOrgAll()
      }
    },

  },
};
</script>
<style scoped>
@import "../../assets/css/global_tree.css";

.treeicons {
  font-size: 20px;
  margin-right: 5px;
}

:deep .el-tree-node>.el-tree-node__children {
  overflow: visible;
}
</style>
