<template>
  <!-- 查询单位包含本级（多选） -->
  <div>
    <el-dialog title="组织机构部门选择" width="50%" v-model="props.showDdld" @close="closeDialog"
               :close-on-click-modal="false"
               :show-close="false">
<!--      <div class="search">-->
<!--        <el-input style="max-width: 400px;"></el-input>-->
<!--        <el-button type="primary" style="margin-left: 10px;">-->
<!--          <el-icon>-->
<!--            <Search />-->
<!--          </el-icon>-->
<!--          <span>搜索</span>-->
<!--        </el-button>-->
<!--      </div>-->
      <!-- 组织机构信息 -->
      <div class="box">
        <div class="treeBox">
          <el-tree ref="singleTableRef" :data="treeData" :props="endProps" @node-click="handleNodeClicks" node-key="id"
                   show-checkbox @check-change="checkChange" :check-strictly="props.Isstrictly" @check="handleCheck"
                   :default-expanded-keys="treemrData" :default-checked-keys="checkedKeys" />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSave">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>确定</span>
          </el-button>
          <el-button type="primary" @click="clearlist(true)">
            <el-icon>
              <DocumentRemove />
            </el-icon>
            <span>清空</span>
          </el-button>
          <el-button @click="handleClose" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>


        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import {
  defineProps,
  reactive,
  watch,
  onMounted,
  ref,
  defineEmits,
  onBeforeUnmount,
  watchEffect,
  nextTick
} from "vue"
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js"
import { getDept } from "@/api/user-manage"
import { getItem } from "@/utils/storage";

const singleTableRef = ref()
const endProps = {
  children: "children",
  value: "id",
  label: "orgname",
  isLeaf: "leaf",
  disabled: function(data, node) {//带子级的节点不能选中
    return !props.Isstrictly && data.children.length;
  }

}
const treemrData = ref([])
/** 选择的ids */
const checkedKeys = ref([])
const node_had = ref([])
const resolve_had = ref([])
const treeData = ref([]) // 树的数据
const props = defineProps({
  /** 选择的数据 */
  modelValue: {
    type: Array,
    default: []
  },
  showDdld: {
    type: Boolean,
    default: false
  },
  //是否可选择本级true：可以  false:不可以
  Isstrictly: {
    type: Boolean,
    default: false
  },
  zzlx: String,
  formInfo: {
    type: Object,
    default: {}
  },
  // 查询层级 01.查询所有层级(默认) 02.查询所有省、市公司 03.查询所有省、市、县公司
  searchType: {
    type: String,
    default: "02"
  },
  // 查询当前部门下的人员
  deptId: {
    type: String,
    default: null
  },
  //查询单位下的安全部门
  isAqbm: {
    type: Boolean,
    default: false
  },
  isMult: {
    type: Boolean,
    default: true
  }
  /** 选择的数据 */
  // selectData: {
  //   type: Array,
  //   default: []
  // }
})
const listQuery = ref({
  deptcode: getItem("deptId").ssdwid,
  type: props.searchType
})
const treemrs = ref(null)
const currentRow = ref(-1) //选中的数据
const checkedData = ref([])
/** 选中的多个id */
const checkedIds = ref([])
/** 曾选中的对象 方便找数据用 */
const checkObj = ref({})
const emits = defineEmits(["closezzjg", "listdata", "update:modelValue"])
onMounted(() => {
  // getTreeData()
  if (props.showDdld) {
    listQuery.value.type = props.searchType
    getTreeData()
  }
})
onBeforeUnmount(() => {
  // clearTimeout(treemrs.value)
  treemrs.value = null
})
// watch(
//   () => props.searchType,
//   (val) => {
//     listQuery.value.type = val
//     getTreeData()
//   }
// )

watch(
  () => props.showDdld,
  (val) => {
    if (val == true) {
      listQuery.value.type = props.searchType
      getTreeData()
      // checkedData.value = props.selectData
      nextTick(() => {
        if (props.isMult) {
          singleTableRef.value.setCheckedKeys(props.modelValue)
          checkedIds.value = props.modelValue
        }
        // checkedKeys.value = props.modelValue
      })
      //
    }
  }
)

// 获取部门树的数据
const getTreeData = () => {

  treeData.value = []
  treemrData.value = []
  getApi(listQuery.value, "/mosty-base/deptFeign/getDeptAndJgbm").then((res) => {
    if (res.length == 1) {
      res.forEach((element) => {
        //  treemrs.value = setTimeout(() => { singleTableRef.value.setCurrentKey(element.id) }, 200)
        // treemrData.value.push(element.id);
        treemrData.value = [element.id]
      })
    }
    for (let i = 0; i < res.length; i++) {
      res[i].leaf = res[i].children.length > 0 ? false : true
    }
    let arr = []
    if (res.length) {
      res[0].children.forEach((element) => {
        if (element.orgname.indexOf('本级') !== -1){
          arr.push(element)
          element.disabled = true
        }else {
          element.disabled = false
          element.children = []
          arr.push(element)
        }
      })
    }
    if (res.length > 0) treeData.value = arr
  })
  const filterNode = (value, data) => {
    if (!value) return true
    return data.orgname.includes(value)
  }
}

//懒加载方法
async function loadNode(node, resolve) {
  // listQuery.value.parentid = node.data.id ? node.data.id : props.deptId;
  if (node.level === 0) {
    node_had.value = node
    resolve_had.value = resolve
    getTreeData()
  }
  if (node.level >= 1) {
    getApi(listQuery.value, "/mosty-base/deptFeign/getDeptAndJgbm").then((res) => {
      for (let i = 0; i < res.length; i++) {
        res[i].leaf = res[i].children ? false : true
      }
      resolve(res)
    })
  }
}

const checkChange = (data, isChecked) => {
  checkObj.value[data.id] = {
    id: data.id,
    orgName: data.orgname, // 名称
    orgCode: data.orgcode, // 编码
    orgLevel: data.orglevel, // 级别
    parentid: data.parentid // 上级id
  }
}

//获取复选框中被选中的值
function handleCheck(data, checkedData) {
  // 这是选中的节点数组
  currentRow.value = checkedData.checkedNodes[0]
  // currentRow.value.zzlx = props.zzlx?props.zzlx:null;
  if (props.isMult) {
    checkedIds.value = checkedData.checkedKeys // checkedKeys

    const arr = [...checkedData.checkedKeys]
    emits("update:modelValue", arr)
  }

}

const handleNodeClicks = (node) => {
  if (!props.Isstrictly && node.hasChildren) {
    return
  } else {
    const checked = [node.id] // id为tree的node-key属性
    if (props.isMult) {
      checkedIds.value = [node.id]
      emits("update:modelValue", checkedIds.value)
      singleTableRef.value.setCheckedKeys(checked)
    } else {
      singleTableRef.value.setCheckedKeys(checked)
      currentRow.value = node
    }
  }
}

/**
 * 清空
 * @param {Boolean} isBtn 是否是点击按钮清空
 */
function clearlist(isBtn) {
  id.value = null
  currentRow.value = []
  singleTableRef.value.setCheckedKeys([], false)
  if (props.isMult) {
    checkedIds.value = []
    if (isBtn) emits("update:modelValue", checkedIds.value)
  }
}

const handleNodeClick = (value) => {
  listQuery.value.deptId = value[value.length - 1]
}
const id = ref("")
watch(
  () => [props.formInfo, props.zzlx],
  (val) => {
    if (props.zzlx == "01") {
      id.value = props.formInfo.leaderid
    } else {
      id.value = props.formInfo.zzid ? props.formInfo.zzid : null
    }
  }
)

const closeDialog = () => {
  emits("closezzjg", false)
  // clearlist()
}
/** 根据ids找数据数组 */
const findData = (ids) => {
  let arr = []
  ids.forEach(item => {
    arr.push(checkObj.value[item])
  })
  return arr
}
const handleSave = () => {
  // currentRow.value.orgName = currentRow.value.orgname
  emits("closezzjg", false)
  if (props.isMult) {
    let data = findData(checkedIds.value)
    emits("listdata", data)
  } else {
    emits("listdata", currentRow.value)
  }
  clearlist()
}
const handleClose = () => {
  emits("closezzjg", false)
  clearlist()
}
// // 表格多选
// const handleSelectionChange = (val) => {
//   currentRow.value = val;
// };
// //选中
// const handleCurrentChange = (val) => {
//   currentRow.value = val;
//   currentRow.value.zzlx = props.zzlx;
// };
</script>

<style lang="scss" scoped>
::v-deep .is-leaf + .el-checkbox .el-checkbox__input .el-checkbox__inner {
  display: inline-block !important;
}

::v-deep .el-tree-node__content .el-tree-node__expand-icon {
  display: black;
}

// ::v-deep .el-checkbox .el-checkbox__input .el-checkbox__inner {
//   display: none !important;
// }

// :v-deep .el-tree-node {
//   .el-checkbox .el-checkbox__inner {
//     display: none !important;
//     background: red !important;
//   }
// }

// :v-deep .wrap .el-checkbox__input.is-disabled {
//   display: none;
// }

// ::v-deep .el-tree-node__expand-icon {
//   display: block !important;
// }

.el-form {
  margin-top: 10px;
  display: flex;
  //   flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  text-align: center;
  width: 400px;
}

.flx {
  display: flex;
  width: 100%;

  .el-button {
    margin-left: 10px;
  }
}

.box {
  width: 100%;
  height: 400px;
  overflow-y: scroll;
  border: 1px solid var(--el-color-primary);
}

.bot_font {
  width: 100%;
  text-align: center;
  font-size: 16px;
  color: #ffff;
  margin-top: 10px;
}

.search {
  //width: 300px;
  display: flex;
  margin-bottom: 10px;
  justify-content: flex-end;
  // margin-left: 65%;
}

.fenye {
  margin-top: 10px;
}
</style>
