<template>
  <div>
    <el-dialog :title="'组织机构人员选择'" width="1200px" v-model="props.modelValue" :before-close="closed">
      <el-form :model="listQuery" class="mosty-from-wrap" :inline="true" style="width: 960px;"><!-- v-if="!props.deptId"
        -->
        <el-form-item label="所属部门" style="width: 300px;">
          <MOSTY.Department width="250px" clearable @depitem="changedept" :searchType="props.searchType"
            :deptId="props.deptId" v-model="listQuery.deptId" />
        </el-form-item>
        <el-form-item label="用户名" style="width: 300px;">
          <el-input placeholder="请输入用户名" v-model="listQuery.loginName" clearable style="width: 250px;"></el-input>
        </el-form-item>
        <el-form-item style="width: 144px;">
          <el-button type="success" @click="handleFilter">查询</el-button>
          <el-button type="success" @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
      <!-- 组织机构信息 -->
      <div class="flex just-between treeBox2 ww100">
        <div class="tabBox" :class="Single ? 'table-box-radio' : ''" style="margin-top: 0px;height: 100%;">
          <el-table stripe ref="multipleUserRef" v-loading="tableloading" @row-click="changecoose"
            @selection-change="handleSelectionChange" :data="tableData" border :row-key="keyid" v-model="currentRow"
            height='57vh'>
            <el-table-column type="selection" width="55" :reserve-selection="true" v-if="!Single" />
            <el-table-column width="55" #default="{ row }" v-else>
              <el-radio v-model="ridioIndex" :label="row.id"></el-radio>
            </el-table-column>
            <el-table-column prop="ssdwmc" align="center" label="单位"></el-table-column>
            <el-table-column prop="deptName" align="center" label="部门"></el-table-column>
            <el-table-column prop="userName" align="center" label="用户名"></el-table-column>
            <el-table-column prop="sex" align="center" label="性别">
              <template #default="{ row }">
                <!-- <span> {{ row.sex == 1 ? "男" : "女" }}</span> -->
                <span> </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="cskbox" v-if="!Single">
          <!-- 穿梭按钮 -->
          <el-icon @click="pushRight">
            <DArrowRight />
          </el-icon>
          <el-icon @click="pushLeft">
            <DArrowLeft />
          </el-icon>
        </div>
        <div class="listbox" v-if="!Single">
          <!-- 选中的组员 -->
          <ul>
            <li :class="item.active ? 'activ' : ''" v-for="(item, index) in rightList" :key="item"
              @click="clicklist(item, index)">
              {{ item.userName }}
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <div class="flex just-between">
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="listQuery.pageNum" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
            layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
          <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="!Single">
              <el-icon>
                <DocumentRemove />
              </el-icon>
              <span>清空</span>
            </el-button>
            <el-button @click="closed" type="primary">
              <el-icon>
                <DocumentDelete />
              </el-icon>
              <span>关闭</span>
            </el-button>

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

<script setup>
// 引入
import { defineProps, watch, ref, defineEmits, nextTick } from "vue";
import { getApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { getSysUserList } from "@/api/user-manage";
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import { get } from "lodash";
const rightList = ref([]); //右边列表数据
const diIndex = ref(); //点击右边列表数据
const leftList = ref([]); //存放右边被点击的数据
const total = ref(0);
const tableData = ref([]);
const rightData=ref([])
const ridioIndex = ref(null);
const multipleUserRef = ref(null);
const tableloading = ref(false);
const listQuery = ref({
  pageNum: 1,
  pageSize: 10,
});
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  titleValue: {
    type: String,
    default: "选择用户"
  },
  // 选择成员
  data: {
    type: Array,
    default: []
  },
  LeaderType: {
    type: String,
    default: ""
  },
  //是否单选
  Single: {
    type: Boolean,
    default: true
  },
  //是否只选择相同部门下的人员
  xtbmry: {
    type: Boolean,
    default: false
  },
  // 选择领导的回显
  leaderid: {
    type: String,
    default: null
  },
  // 查询当前部门下的人员
  deptId: {
    type: String,
    default: () => getItem("deptId").ssdwid
  },
  // 选择组长的回显
  zzid: {
    type: String,
    default: ""
  },
  key: {
    type: Number,
    default: 0
  },
  // 部门树查询类型
  searchType: {
    type: String,
    defaule: "04"
  }
});
const currentRow = ref(-1); //选中的数据
const emits = defineEmits(["update:modelValue", "choosedUsers"]);
const closed = () => {
  multipleUserRef.value.clearSelection();
  leftList.value = [];
  rightList.value = [];
       rightData.value=[]
  currentRow.value = [];
  listQuery.value.loginName = []
  emits("update:modelValue", false);
};
const keyid = (row) => {
  return row.id;
};
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      multipleUserRef.value = null
      ridioIndex.value = null
           rightData.value=[]
      if (!props.deptId) {
        listQuery.value.deptId = null;
        handleFilter();
      } else {
        listQuery.value.deptId = props.deptId;
        handleFilter();
      }
    }
  }
);
watch(
  () => props.leaderid,
  (val) => {
    multipleUser(val);
  }
);
function reset() {
  listQuery.value.loginName = ''
  listQuery.value.deptId = null;
  listQuery.value.pageNum = 1;
  getListData();
}
//获取查询值
function changedept(val) {
  listQuery.value.deptId = val.orgCode;
  listQuery.value.pageNum = 1;
  getListData();
}
const handleFilter = () => {
  listQuery.value.pageNum = 1;
  getListData();
};
const getListData = async () => {
  tableData.value = [];
  tableloading.value = true;
  const params = listQuery.value;

  const res = await getSysUserList(params);
  if (res) {
    res.records.forEach(item => {
      let card = item.idEntityCard
      if (card) {
        if (card.length == 18) {
          item.sex = (card.substring(16, 17)) % 2 == 0 ? '2' : '1'
        } else {
          item.sex = '1'
        }
      } else {
        item.sex = null
      }
    })
    tableData.value = res?.records;
    total.value = Number(res.total);
    tableloading.value = false;
  }
  if (props.data && props.data.length > 0&&rightData.value.length==0) {
    multipleUser(props.data);
  }
};
// 列表回显
function multipleUser(row) {
  // 左右清除历史缓存
  rightList.value = []
  tableData.value.forEach((val) => {
    multipleUserRef.value.toggleRowSelection(val, false);
  });
  if (row) {
    if (props.Single) {
      ridioIndex.value = row;
    } else {
      row.forEach((item) => {
        getApi({ id: item }, `/mosty-base/userFeign/getUserDetail`).then(res => {
          if (res) {
            rightList.value.push(res)
            let map = new Map();
            for (let item of rightList.value) {
              map.set(item.id, item);
            }
            rightList.value = [...map.values()];
          }
        })
        tableData.value.forEach((val) => {
          if (item == val.id) {
            multipleUserRef.value.toggleRowSelection(val, true);
          }
        });
      });
    }
  } else {
    if (props.Single) {
      ridioIndex.value = null;
    }
  }
}
const handleSelectionChange = (val) => {
  currentRow.value = val;
};
function changecoose(val) {
  if (props.Single) {
    ridioIndex.value = val.id
  } else {
    if (currentRow.value && currentRow.value.length > 0) {
      let rowid = []
      rowid = currentRow.value.filter(it => { return it.id == val.id })
      if (rowid.length > 0) {
        multipleUserRef.value.toggleRowSelection(val, false);

      } else {
        multipleUserRef.value.toggleRowSelection(val, true);
      }

    } else {
      multipleUserRef.value.toggleRowSelection(val, true);
    }
  }

}
//点击右箭头
function pushRight() {
  if (rightList.value.length == 0) {
    rightList.value = currentRow.value;
  } else {
    rightList.value.push(...currentRow.value)
    let map = new Map();
    for (let item of rightList.value) {
      map.set(item.id, item);
    }
    rightList.value = [...map.values()];
  }
rightData.value=rightList.value
}
//点击左箭头
function pushLeft() {
  //遍历右边选中的数据
  for (let i = 0; i < leftList.value.length; i++) {
    const e = leftList.value[i];
    if (e.id) {
      multipleUserRef.value.toggleRowSelection(e, false);
    }
    rightList.value.forEach((item, index) => {
      if (e.id == item.id) {
        rightList.value.splice(index, 1);
      }
    });
    if (currentRow.value.length > 0) {
      currentRow.value.forEach((item, index) => {
        if (e.id == item.id) {
          currentRow.value.splice(index, 1);
        }
      });
    }
  }
  rightData.value=rightList.value
}
//点击右边列表的每一项
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 clearlist() {
  leftList.value = [];
  rightList.value = [];
  currentRow.value = [];
   rightData.value=[]
  multipleUserRef.value.clearSelection();
}
const handleSave = () => {
  const list = [...new Set(rightList.value.map(item => item.deptId))]
  if (props.xtbmry && list.length > 1) {
    ElMessage.error("请选择相同部门下的人员!");
  } else {
    if (props.Single) {
      const info = tableData.value.find((item) => {
        return item.id === ridioIndex.value;
      });
      emits("choosedUsers", [info]);
      closed();
    } else {
      emits("choosedUsers", rightList.value);
      closed();
    }
    multipleUserRef.value.clearSelection();
  }

};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageNum = currentPage;
  getListData();
};
/**
 * pageSize 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";

::v-deep .el-form--inline {
  padding-left: 0 !important;
}

::v-deep .el-radio__label {
  display: none !important;
}

.table-box-radio .el-table1__header-wrapper .el-checkbox {
  display: none !important;
}

: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;
  position: absolute;
  right: 20px;
  top: 20px;
}

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

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

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

.box {
  width: 100%;
  height: 516px;
  overflow-y: hidden;
  border: 1px solid var(--el-color-primary);
  display: flex;
  justify-content: space-between;
}

.treeBox2 {
  overflow: auto;
}

.cskbox {
  width: 40px;
  padding: 107px 0;
  margin-right: 20px;

  .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: 45%;
  overflow-y: scroll;

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

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

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

.fenye {
  margin-top: 10px;
}

::v-deep .el-dialog__body {
  overflow: auto !important;
  height: 600px !important;
}
</style>
