<template>
  <!-- 只查部门 -->
  <div>
    <el-dialog title="组织机构选择" width="900px" :close-on-click-modal="false" v-model="props.showDdld" @close="closeDialog"
      :show-close="false">
      <div class="search" v-if="!props.Single">
        <el-input></el-input>
        <el-button type="primary">
          <el-icon>
            <Search />
          </el-icon>
          <span>搜索</span>
        </el-button>
      </div>
      <!-- <el-form :model="listQuery" :rules="rules" label-width="100px" class="demo-ruleForm" :size="formSize" status-icon>
      </el-form> -->
      <!-- 组织机构信息 -->
      <div :class="props.Single ? 'box' : 'box border'">
        <div :class="props.Single ? 'treeBox' : 'treeBox with'">
          <el-tree ref="singleTableRef" class="filter-tree" :props="endProps" node-key="id" accordion
            :default-expanded-keys="treemrData" check-strictly @node-click="nodeClick" :filter-node-method="filterNode"
            @check-change="checkChange" :data="treeData" show-checkbox @check="handleCheck"
            :default-checked-keys="ids" />
        </div>

        <div class="listbox" v-if="!props.Single">
          <!-- 选中的组员 -->
          <ul>
            <li class="bm-list-item" :class="item.active ? 'activ' : ''" v-for="(item, index) in rightList" :key="item"
              @click="clicklist(item, index)">
              <span>{{ item.orgName }}</span>
              <span class="del-btn" @click="delRow(item)">删除</span>
            </li>
          </ul>
        </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" v-if="!props.Single">
            <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,
  watch,
  onMounted,
  ref,
  defineEmits,
  watchEffect,
  nextTick
} from "vue";

import {
  getDept
} from "@/api/user-manage";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
const treeData = ref([]); // 树的数据
const node_had = ref([]);
const treemrData = ref([]);
const singleTableRef = ref();
const rightList = ref([]); //右边列表数据
const diIndex = ref(); //点击右边列表数据
const leftList = ref([]); //存放右边被点击的数据
const currentRow = ref(-1); //选中的数据
const emits = defineEmits(["closezzjg", "listdata"]);
const resolve_had = ref([]);
const props = defineProps({
  showDdld: {
    type: Boolean,
    default: true
  },
  zzlx: String,
  // 单位回显
  formInfo: {
    type: Array,
    default: []
  },
  //单选/多选 （目前仅多选用，）
  Single: {
    type: Boolean,
    default: false
  },
  parentId: {
    type: String,
    default: ""
  },
  // orgLevels省部门：11，市部门：21，县部门：31,s市部门-县部门：21，30
  orgLevels: {
    type: String,
    default: ""
  },
  Isstrictly: {
    type: Boolean,
    default: true
  },
});
const listQuery = ref({
  orgLevels: '',
  parentId: getItem('deptId').ssdwid
});
const ids = ref([])
watch(
  () => props.showDdld,
  (newVal) => {
    if (newVal) {
      ids.value = []
      currentRow.value = []
      rightList.value = []
      // listQuery.value.parentId = props.parentId;
      listQuery.value.orgLevels = props.orgLevels;
      getTreeData();
    }
  },
  { deep: true, immediate: true }
);



onMounted(() => {
  // getTreeData();

});
watchEffect(() => {
  if (props.orgLevels) {
    listQuery.value.orgLevels = props.orgLevels;
  }

})
const endProps = {
  children: "children",
  value: "id",
  label: "orgName",
  isLeaf: "leaf"
};
// 获取部门树的数据
function getTreeData() {
  // orgLevels省部门：11，市部门：21，县部门：31
  // orgLevels市部门-县部门：21，30
  postApi(listQuery.value, "/mosty-base/deptFeign/getOrgList").then((res) => {
    if (res.length == 1) {
      res.forEach((element) => {
        element.orgname = element.orgName
        treemrData.value.push(element.id);
        emits("getdeptData", element);
      });
    }
    for (let i = 0; i < res.length; i++) {
      res[i].leaf = !res[i].hasChildren;
    }
    if (res.length > 0) {
      treeData.value = res;
    }
    if (props.formInfo && props.formInfo.length > 0) {
      multipleUser(props.formInfo);
    }
  });
}

//懒加载方法
async function loadNode(node, resolve) {
  listQuery.value.parentid = node.data.id;
  if (node.level === 0) {
    node_had.value = node;
    resolve_had.value = resolve;
    getTreeData();
  }
  if (node.level >= 1) {
    getDept(listQuery.value).then((res) => {
      for (let i = 0; i < res.length; i++) {
        res[i].leaf = !res[i].hasChildren;
      }
      resolve(res);
    });
  }
}
const filterNode = (value, data) => {
  if (!value) return true;
  return data.orgName.includes(value);
};
//获取复选框中被选中的值
function handleCheck(data, checkedData) {
  //
  //
  // let arr = checkedData.checkedNodes;
  // for (let i = 0; i < arr.length; i++) {
  //   const e = arr[i];
  //   // if (e.hasChildren == true) {
  //   //   arr.splice(i, 1);
  //   // }
  // }
  // currentRow.value = data;
  // currentRow.value.zzlx = props.zzlx?props.zzlx:null;
}
/**初始化右边已选 */
function initRightData() {
  let checkedNodes = singleTableRef.value.getCheckedNodes()
  rightList.value = checkedNodes.map(item => {
    return {
      ...item,
      children: undefined
    }
  })

}
/** 选择改变
 * @param {Object} data 当前改变的项目
 * @param {Boolean} checkedData 当前改变的选中状态
 */
function checkChange(data, checkedData) {
  if (props.Single) {
    if (checkedData) singleTableRef.value.setCheckedKeys([data.id])
  } else {
    initRightData()
  }
}
function nodeClick(data, checkedData) {

  /** 是否不能选中 */
  // const isCantCheck = !props.Isstrictly && data.children?.length > 0;
  // if (isCantCheck) return

  if (props.Single) {
    singleTableRef.value.setCheckedKeys([data.id]);
  } else {
    /** 是否已选 （能找到就已选） */
    const findRow = rightList.value.find(it => { return it.id == data.id })
    singleTableRef.value.setChecked(data.id, !findRow);

  }

}

//点击右边列表的每一项
function clicklist(item, index) {
  // item.active = !item.active;
  // diIndex.value = index;
  // if (item.active) {
  //   leftList.value.push(item);
  // } else {
  //   for (let i = 0; i < leftList.value.length; i++) {
  //     const element = leftList.value[i];
  //     if (element.id == item.id) {
  //       leftList.value.splice(i, 1);
  //     }
  //   }
  // }
}
//   //处理回显问题
function multipleUser(row) {

  // 左右清除历史缓存
  rightList.value = []
  let idsArr = Array.isArray(row) ? [...row] : []
  if (!Array.isArray(row) && props.Single) idsArr = row?.id ? [row.id] : [row]
  ids.value = idsArr
  singleTableRef.value.setCheckedKeys(idsArr);
  nextTick(() => {
    initRightData()
  })
  // if (row) {
  //   ids.value = row
  //   row.forEach((item) => {
  //     treeData.value.forEach((val) => {
  //       if (item == val.id) {
  //         singleTableRef.value.setChecked(val.id, true);
  //       }
  //     });
  //     //获取部门详情
  //     getApi({}, `/mosty-base/deptFeign/getDeptById/${item}`).then(res => {
  //       rightList.value.push(res)
  //     })
  //   })
  // }
}
//点击清空列表
function clearlist() {
  leftList.value = [];
  rightList.value = [];
  ids.value = []
  currentRow.value = [];
  singleTableRef.value.setCheckedKeys([], false);
}
const closeDialog = () => {
  emits("closezzjg", false);
};
const delRow = (row) => {
  singleTableRef.value.setChecked(row.id, false);
};
const handleSave = () => {

  emits("closezzjg", false);
  if (props.Single) {
    let checkedNodes = singleTableRef.value.getCheckedNodes()
    const data = checkedNodes?.[0] || {}
    data.zzlx = props.zzlx ? props.zzlx : null;
    emits("listdata", { ...data });
  } else {
    emits("listdata", rightList.value);
  }


};
const handleClose = () => {
  emits("closezzjg", false);
};

</script>

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

::v-deep .el-overlay-dialog {
  overflow: hidden !important;
}

:v-deep .el-checkbox .el-checkbox__inner {
  display: none;
}

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

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

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

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

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

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

.box {
  width: 100%;
  height: calc(84vh - 200px);
  overflow-y: hidden;
  display: flex;
  justify-content: space-between;
}

.border {
  border: 1px solid var(--el-color-primary);
}

.treeBox {
  width: 100%;
  overflow: auto;
}

.with {
  width: 50%;
}

.cskbox {
  width: 40px;
  padding: 107px 0;

  .el-icon {
    width: 4em !important;
    height: 6em !important;
  }

  .el-icon svg {
    width: 3em !important;
    height: 3em !important;
  }
}

.listbox {
  border: 1px solid var(--el-color-primary);
  width: calc(50% - 20px);
  height: 100%;
  overflow-y: scroll;

  .bm-list-item {
    display: flex;
    justify-content: space-between;
    padding: 4px 10px;
    box-sizing: border-box;

    .del-btn {
      color: rgb(240, 47, 21);
      cursor: pointer;

      &:hover {
        transform: scale(1.1);
      }
    }
  }

  .activ {
    background-color: var(--el-color-primary);
  }
}

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

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