<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 v-if="isNewChooseDept" style="width: 300px;" label="相关方选择">
          <el-select v-model="isRlx" style="width: 120px" clearable placeholder="相关方选择" @change="isRlxChange">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isRlx" label="所属部门" style="width: 300px;">
          <el-select v-if="isNewChooseDept || isNewChooseDeptWx" v-model="deptName" style="width: 250px" clearable
            placeholder="请选择所属部门" @change="changedept">
            <el-option v-for="item in deptData" :key="item" :label="item.orgName" :value="item.id" />
          </el-select>
          <MOSTY.Department v-else width="250px" clearable @depitem="changedept" :searchType="props.searchType"
            :deptId="props.deptId" v-model="listQuery.deptId" :key="keys" />
        </el-form-item>
        <el-form-item v-else label="所属相关方" style="width: 350px;">
          <el-select v-model="rlxName" style="width: 300px" clearable placeholder="请选择相关方" @change="changeRlxdept">
            <el-option v-for="item in rlxData" :key="item" :label="item.relatedname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" v-if="!isRlx" style="width: 300px;">
          <el-input placeholder="请输入用户名" v-model="listQuery.loginName" clearable style="width: 250px;"
            @keyup.enter="handleFilter"></el-input>
        </el-form-item>
        <el-form-item style="">
          <el-button v-if="!isRlx" type="success" @click="handleFilter">查询</el-button>
          <el-button type="success" @click="reset()"> 重置 </el-button>
          <el-button type="success" @click="resetClose()" v-if="props.closeSelect && Single"> 取消选择 </el-button>
        </el-form-item>
      </el-form>
      <!-- 组织机构信息 -->
      <div style="height: calc(100% - 80px);" class="flex just-between treeBox2 ww100">
        <div class="tabBox" :class="Single ? 'table-box-radio' : ''" style="margin-top: 0px;height: 100%;">
          <el-table v-if="!isRlx" stripe ref="multipleUserRef" v-loading="tableloading"
            @selection-change="handleSelectionChange" @row-click="changecoose" :data="tableData" border :row-key="keyid"
            v-model="currentRow" height="100%">
            <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>
          <el-table v-else stripe ref="multipleUserRef" v-loading="tableloading"
            @selection-change="handleSelectionChange" @row-click="changecoose" :data="tableData" border :row-key="keyid"
            v-model="currentRow" height="100%">
            <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>
        </div>
        <div class="cskbox" v-if="!Single">
          <!-- 穿梭按钮 -->
          <el-icon @click="pushRight" title="快捷键：空格键">
            <DArrowRight />
          </el-icon>
          <el-icon @click="pushLeft" title="快捷键：Q键">
            <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" title="快捷键：回车键" :disabled="!Single && rightData.length === 0">
              <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, onUnmounted, onMounted } 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 ridioIndex = ref(null);
const multipleUserRef = ref(null);
const tableloading = ref(false);
const rightData = ref([])
const keys = ref(1)
/** 选中的数据 */
const selectData = ref([])
const listQuery = ref({
  pageNum: 1,
  pageSize: 10,
});
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  closeSelect: {
    type: Boolean,
    default: false
  },
  isNewChooseDept: {
    type: Boolean,
    default: false
  },
  isNewChooseDeptWx: {
    type: Boolean,
    default: false
  },
  titleValue: {
    type: String,
    default: "选择用户"
  },
  // 选择成员
  data: {
    type: [Array, String],
    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为vue保留字段，这里避免一直提示warning错误，注释了 */
  // 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 = [];
  currentRow.value = [];
  rightData.value = []
  listQuery.value.loginName = []
  deptName.value = ''
  rlxName.value = ''
  isRlx.value = false
  emits("update:modelValue", false);
};
const keyid = (row) => {
  return row.id;
};
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      listQuery.value.deptId = null
      multipleUserRef.value = null
      ridioIndex.value = null
      rightData.value = []
      if (!props.deptId) {
        listQuery.value.deptId = null;
        handleFilter();
      } else {
        listQuery.value.deptId = props.deptId;
        handleFilter();
        listQuery.value.deptId = null;
      }
      keys.value++
      selectData.value = Array.isArray(props.data) ? props.data : [];
      // 监听空格，回车键，触发快捷方式
      document.addEventListener('keydown', doChoose);

    } else {
      document.removeEventListener('keydown', doChoose);
    }
  }
);
// 当前单位部门
const deptData = ref([])
const deptName = ref('')
const rlxData = ref([])
const rlxName = ref('')
const isRlx = ref(false)
const isRlxChange = (data) => {
  tableData.value = [];
  if(isRlx.value){
    let id=rlxData.value.length>0?rlxData.value[0].id:''
    rlxName.value=id
    changeRlxdept(id)
  }else{
    reset()
  }
}
const changeRlxdept = (id) => {
  tableData.value = [];
  tableloading.value = true;
  const params = {
    id: id,
    pageCurrent: 1,
    pageSize: 10,
  };
  let ssdwmc = ''
  rlxData.value.forEach((item) => {
    if (item.id === id) {
      ssdwmc = item.relatedname
    }
  })
  // 当前相关方人员
  getApi(params, '/mosty-jcgl/relatedpartyinfo/getRelatedUserPage')
    .then((res) => {
      // tableData.value = res
      console.log(res.records)
      if (res.records && res.records.length > 0) {
        res.records.forEach((item) => {
          tableData.value.push({
            ssdwmc: ssdwmc,
            deptName: ssdwmc + '单位',
            userName: item.xm,
            idEntityCard:item.idcard,
            outsourcingLevel:'3',
            id: item.id,
            sex: item.sex,
            deptId: item.relatedid,
          })
        })
      }
      total.value = Number(res.total);
      tableloading.value = false;
    })
}
onMounted(() => {
  if (props.isNewChooseDept || props.isNewChooseDeptWx) {
    // 当前用户所属部门
    getApi({}, '/mosty-base/deptFeign/getOwerDept')
      .then((res) => {
        deptData.value = res
      })
    // 相关方接口
    getApi({}, '/mosty-jcgl/relatedpartyinfo/getListFireUse')
      .then((res) => {
        rlxData.value = res
      })
  }
})
watch(
  () => props.leaderid,
  (val) => {
    multipleUser(val);
  }
);
function doChoose(e) {
  // 如果是输入框或文本区域，则不处理
  if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return
  // 空格键选择到右边
  if (e.code === 'Space') {
    e.preventDefault();
    if (props.modelValue && currentRow.value.length > 0) {
      if (!props.Single) pushRight();
    }
  }
  // Q 键盘选择到左边
  if (e.code === 'KeyQ') {
    e.preventDefault();
    if (props.modelValue) {
      pushLeft();
    }
  }
  // 回车键保存
  if (e.code === 'Enter') {
    e.preventDefault();
    handleSave();
  }
}
function resetClose() {
  if (props.Single) {
    // 单选模式：清除单选框选择
    ridioIndex.value = null;
    ElMessage.success('已取消人员选择');
  } else {
    // 多选模式：清除所有选择
    clearlist();
    ElMessage.success('已取消所有选择');
  }

  // 额外确保清除表格的选择状态
  if (multipleUserRef.value) {
    multipleUserRef.value.clearSelection();
  }
  currentRow.value = [];
  emits("choosedUsers", [{
    userName: '',
    id: '',
    deptId: '',
  }]);
  closed();
}
function reset() {
  isRlx.value=false
  deptName.value = ''
  rlxName.value = ''
  listQuery.value.loginName = ''
  listQuery.value.deptId = props.deptId;
  listQuery.value.pageNum = 1;
  keys.value++
  getListData();
}
//获取查询值
function changedept(val) {
  if (props.isNewChooseDept || props.isNewChooseDeptWx) {
    listQuery.value.deptId = val
  } else {
    listQuery.value.deptId = val.orgCode ? val.orgCode : props.deptId;
  }
  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 (selectData.value && selectData.value.length > 0 && rightData.value.length == 0) {
    multipleUser(selectData.value);
  }
};
// 列表回显
function multipleUser(row) {
  // 左右清除历史缓存
  rightList.value = []
  tableData.value.forEach((val) => {
    multipleUserRef.value.toggleRowSelection(val, false);
  });
  if (row) {
    if (props.Single) {
      if (Array.isArray(row)) {
        ridioIndex.value = row[0];
      } else {
        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
  selectData.value = rightList.value.map(item => item.id)
}
//点击左箭头
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
  selectData.value = rightList.value.map(item => item.id)
}
//点击右边列表的每一项
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 = []
  selectData.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;
      });
      info.memberType = isRlx.value ? 2 : 1
      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();
};

onUnmounted(() => {
  document.removeEventListener('keydown', doChoose);
});
</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;
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

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

.table-box-radio {
  width: 100%;
}

.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: 68vh !important;
}
</style>
