<template>
  <div>
    <el-dialog title="组织机构选择" width="1200px" :close-on-click-modal="false" v-model="props.showDdld" @close="closeDialog"
      :show-close="false">
      <!-- <div class="search ww100">
        <div></div>
        <div class="flex ">
          <el-input placeholder="请输入关键词"></el-input>
          <el-button type="primary">
            <el-icon>
              <Search />
            </el-icon>
            <span>搜索</span>
          </el-button>
        </div>
      </div> -->
      <!-- 组织机构信息 -->
      <div :class="props.Single ? 'box' : 'box border'" style="height: 60vh;">
        <div :class="props.Single ? 'treeBox' : 'treeBox with'">
          <el-tree ref="singleTableRef" class="filter-tree" :props="endProps" node-key="id" accordion
            :check-strictly="props.Isstrictly" :default-expanded-keys="treemrData" @node-click="nodeClick"
            :filter-node-method="filterNode" @check-change="checkChange" :data="treeData" show-checkbox
            @check="handleCheck" :default-checked-keys="ids" />
        </div>
        <div class="cskbox" v-if="!props.Single">
          <!-- 穿梭按钮 -->
          <el-icon @click="pushRight">
            <DArrowRight />
          </el-icon>
          <el-icon @click="pushLeft">
            <DArrowLeft />
          </el-icon>
        </div>

        <div class="listbox" v-if="!props.Single">
          <!-- 选中的组员 -->
          <ul>
            <li :class="item.active ? 'activ' : ''" v-for="(item, index) in rightList" :key="item"
              @click="clicklist(item, index)">
              {{ item.orgname }}
            </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
} from "vue";

import {
  getDept,
} from "@/api/user-manage";
import { getApi } from "@/api/tobAcco_api.js";

const treeData = ref([]); // 树的数据
const node_had = ref([]);
const treemrData = ref([]);
const singleTableRef = ref();
const rightList = ref([]); //右边列表数据
const diIndex = ref(); //点击右边列表数据
const leftList = ref([]); //存放右边被点击的数据
const resolve_had = ref([]);

const props = defineProps({
  showDdld: {
    type: Boolean,
    default: true
  },
  zzlx: String,
  formInfo: {
    type: Array,
    default: []
  },
  //单选/多选
  Single: {
    type: Boolean,
    default: false
  },
  deptcode: {
    type: String,
    default: ""
  },
  //是否可选择本级
  Isstrictly: {
    type: Boolean,
    default: false
  },
  // 查询层级 01.所有 02.省市 03.省市县
  searchType: {
    type: String,
    default: ""
  }
});

const listQuery = ref({
  deptcode: "",
  parentid: "",
  type: props.searchType ? props.searchType : null
});

const ids = ref([])
const currentRow = ref([]); //选中的数据
const emits = defineEmits(["closezzjg", "listdata"]);

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

watch(
  () => props.deptcode,
  (newVal) => {
    if (newVal) {
      listQuery.value.deptcode = newVal;
    }
    listQuery.value.type = props.searchType;
    getTreeData();
  },
  { deep: true, immediate: true }
);

const endProps = {
  children: "children",
  value: "id",
  label: "orgname",
  isLeaf: "leaf",
  disabled: function (data, node) {
    if (!props.Isstrictly && data.children && data.children.length > 0) {
      return true
    } else {
      return false
    }
  }
};

// 获取部门树的数据
function getTreeData() {
  getApi(listQuery.value, "/mosty-base/deptFeign/getDeptAndJgbm").then((res) => {
    if (res.length == 1) {
      treemrData.value = [res[0].id];
    }

    res.forEach(r => {
      r.leaf = r.children.length === 0;
    });

    treeData.value = res;

    // 回显
    if (props.formInfo && props.formInfo.length > 0) {
      ids.value = props.formInfo;
      treemrData.value = props.formInfo;

      ids.value.forEach(item => {
        singleTableRef.value.setChecked(item, true);
      });
    }
  });
}

// 过滤
const filterNode = (value, data) => {
  if (!value) return true;
  return data.orgname.includes(value);
};

// 多选模式下使用（单选不走）
function handleCheck(data, checkedData) {
  if (props.Single) return;
  currentRow.value = [...checkedData.checkedNodes];
}

// 单选/多选统一处理
function checkChange(val, checked) {
  if (props.Single) {
    // 如果不是叶子节点，不允许选中
    if (val.children && val.children.length > 0) {
      // 取消父节点选中
      singleTableRef.value.setChecked(val.id, false);
      return;
    }

    if (checked) {
      // 叶子节点单选
      singleTableRef.value.setCheckedKeys([val.id], false);
      currentRow.value = [val];
      rightList.value = [val];
    } else {
      currentRow.value = [];
      rightList.value = [];
    }
    return;
  }

  // 多选原逻辑
  if (checked) {
    currentRow.value.push(val);
  } else {
    currentRow.value = currentRow.value.filter(el => el.id !== val.id);
  }
}

function nodeClick(data) {
  if (props.Single) {

    // 如果点击父节点，直接 return（不允许选中）
    if (data.children && data.children.length > 0) {
      return;
    }

    singleTableRef.value.setCheckedKeys([data.id], false);
    currentRow.value = [data];
    rightList.value = [data];
    return;
  }

  // 多选原逻辑
  if (currentRow.value.some(it => it.id == data.id)) {
    singleTableRef.value.setChecked(data.id, false);
  } else {
    singleTableRef.value.setChecked(data, true);
  }
}

// 点击右箭头
function pushRight() {
  if (props.Single) {
    if (currentRow.value.length > 0) {
      rightList.value = [currentRow.value[0]];
    }
  } else {
    rightList.value = [...currentRow.value];
  }
}

// 点击左箭头（移除选项）
function pushLeft() {
  for (let i = 0; i < leftList.value.length; i++) {
    const e = leftList.value[i];

    if (e.id) {
      singleTableRef.value.setChecked(e.id, false);
    }

    rightList.value = rightList.value.filter(item => item.id !== e.id);
    currentRow.value = currentRow.value.filter(item => item.id !== e.id);
  }
}

// 右边列表点击
function clicklist(item, index) {
  item.active = !item.active;
  diIndex.value = index;

  if (item.active) {
    leftList.value.push(item);
  } else {
    leftList.value = leftList.value.filter(el => el.id !== item.id);
  }
}

// 清空
function clearlist() {
  ids.value = [];
  leftList.value = [];
  treemrData.value = [];
  rightList.value = [];
  currentRow.value = [];
  singleTableRef.value.setCheckedKeys([], false);
}

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

const handleSave = () => {
  rightList.value.forEach(item => {
    item.orgName = item.orgname;
  });

  emits("closezzjg", false);
  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 {
  display: flex;
  margin-bottom: 10px;
  justify-content: flex-end;
}

.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;
  margin-right: 15px;

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

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

.listbox {
  width: 45%;
  overflow-y: scroll;
  border: 1px solid var(--el-color-primary);

  ul>li {
    padding: 4px 10px;
    box-sizing: border-box;
  }

  .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>