<template>
  <Dialog title="职工信息" width="80%" v-model="dialogVisible" center>
    <ContentWrap class="borderxx">
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="108px">
        <el-form-item label="姓名/工号" label-width="130px" prop="nickname">
          <el-input v-model="queryParams.userNickName" placeholder="请输入姓名/工号" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select v-model="queryParams.deptId" :data="deptList" :props="defaultProps" check-strictly node-key="id" clearable placeholder="请选择所属部门" />
        </el-form-item>
        <el-form-item label="岗位" prop="postId">
          <el-select v-model="queryParams.postIdNew" clearable placeholder="请选择岗位">
            <el-option v-for="dict in postList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <el-card class="hl-card">
      <!-- 列表 -->
      <ContentWrap>
        <el-table ref="multipleTable" v-loading="loading" :data="list" :stripe="true"  height="100%" :show-overflow-tooltip="true" :reserve-selection="true" class="hl-table" @selection-change="handleSelectionChange" :row-key="getRowKeys" @row-click="clickRow" selection :style="{height: list && list.length > 9 ? '475px' : ''}">
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column type="index" min-width="70" label="序号" align="center" />

          <el-table-column label="工号" align="center" prop="username" :show-overflow-tooltip="true" min-width="120" />
          <el-table-column label="姓名" align="center" prop="nickname" :show-overflow-tooltip="true" min-width="120" />
          <el-table-column label="部门" align="center" key="deptName" prop="deptName" :show-overflow-tooltip="true" min-width="120" />
          <el-table-column label="岗位" align="center" prop="postIdNew" min-width="120" />
          <el-table-column label="手机号码" align="center" prop="mobile" min-width="120" />
          <!-- <el-table-column label="性别" align="center" prop="sex" min-width="120"> -->
            <!-- <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
            </template>
          </el-table-column> -->
        </el-table>
        <!-- 分页 -->
        <!-- <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
      </ContentWrap>
    </el-card>
    <template #footer>
      <el-button @click="dialogVisible = false" size="large">取 消</el-button>
      <el-button @click="submitForm" type="success" size="large">保 存</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as DispatchApi from '@/api/heli/taskdispatch'
import { FormRules } from 'element-plus'
import { ElTable } from 'element-plus'
import { any, string } from 'vue-types'
import { toRefs } from 'vue'
const beforeOwnerList = ref([])
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数

const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([]) // 岗位列表

//接收父组件传递过来的值
const props = defineProps({
  dialogType: {
    type: Object,
    required: true
  }
})
const dialogTypeValue = toRefs(props).dialogType // 获取 props 中的 dialogType
const queryParams = reactive({
  pageNo: 1,
  pageSize: 999,
  userNickName: undefined,
  nickname: undefined,
  deptId: undefined,
  postIdNew:'',
  postId: undefined,
  status: 0
})
const queryFormRef = ref() // 搜索的表单
const finalToggleList : any = ref([])
const thisPageList : any = ref([])
/** 查询列表 */
const arrayEmpty = (list : any[]) => {
	if(list != null && list.length > 0){
		return false;
	}else{

		return true;
	}
}
const strEmpty = (str : string) => {
	if(str != null && str !==  ''){
		return false;
	}else{

		return true;
	}
}
const getList = async () => {
  loading.value = true
  // 清除选中状态
  try {
   // postList.value = [];
    list.value = []
    var hasSet = new Set;
    const data = await UserApi.getUserPage(queryParams)
    var ownerList =  await DispatchApi.getAssmebleDispatchPage();
    if(!arrayEmpty(ownerList)){
      ownerList.forEach(item => {
        data.list.forEach( item1 =>{
          if(item.busyId == item1.id){
            if(!strEmpty(queryParams.postIdNew)){
              if(item.postId == queryParams.postIdNew){
                let newItem = { postIdNew: item.postId, ...item1 };
                list.value.push(newItem)
                hasSet.add(item.postId)
              }
            }else{
              let newItem = { postIdNew: item.postId, ...item1 };
              list.value.push(newItem)
              hasSet.add(item.postId)
            }
          }
        })
      })
      if(!arrayEmpty(list.value)){
        if(!arrayEmpty(beforeOwnerList.value )){
        //反选
        beforeOwnerList.value.forEach(item =>{
          list.value.forEach(item1 =>{
              if(item == item1.id){
                  var id = multipleSelection.value. some(item2 => item2.id === item)
                  if(!id){
                       multipleSelection.value.push(item1);
                  }
                  multipleTable.value.toggleRowSelection(item1, true)

              }
          })
        })
      }
        total.value = list.value.length;
      }else{
        total.value = 0
      }

      if(!arrayEmpty(multipleSelection.value)){
          let seenIds = new Set();
          let uniqueItems = multipleSelection.value.filter(item => {
          // 如果 id 已经出现过，返回 false，否则返回 true
          if (seenIds.has(item.id)) {
          return false;
          } else {
          seenIds.add(item.id);
          return true;
          }
          });
          multipleSelection.value = uniqueItems
      }
      // if(arrayEmpty(postList.value)){
      //         hasSet.forEach(item =>{
      //       postList.value.push({
      //         label:item,
      //         value:item
      //       })
      //     })
      // }

    }else{
      list.value = []
      total.value = 0
    }
    // console.log(ownerList)
    // list.value = data.list
    // total.value = data.total
    // if((finalToggleList.value == null || finalToggleList.value.length == 0 )&& (multipleSelection.value  == null || multipleSelection.value.length == 0)){
    //   console.log('1')
    // }else if ((finalToggleList.value == null || finalToggleList.value.length == 0 )&& multipleSelection.value != null && multipleSelection.value.length >0){
    //   multipleSelection.value.forEach(item =>{
    //     finalToggleList.value.push(item);
    //   })
    //   multipleTable.value.clearSelection();
    // }else if (finalToggleList.value != null && finalToggleList.value.length >0 && multipleSelection.value != null && multipleSelection.value.length >0){

    //     if(thisPageList.value != null && thisPageList.value.length > 0){
    //       console.log('3')
    //                   // 在 multipleSelection 中但不在 thisPageList 中的数据 添加
    //       const inMultipleNotInThisPage = multipleSelection.value.filter(msItem =>
    //         !thisPageList.value.some(tpItem => tpItem.id === msItem.id)
    //       );

    //       // 在 thisPageList 中却不在 multipleSelection 中的数据 删除
    //       const inThisPageNotInMultiple = thisPageList.value.filter(tpItem =>
    //         !multipleSelection.value.some(msItem => msItem.id === tpItem.id)
    //       );

    //       // 创建一个以 id 为键的对象，用于快速查找 finalToggleList 中的元素
    //       const finalToggleListObj = finalToggleList.value.reduce((acc, item) => {
    //         acc[item.id] = item;
    //         return acc;
    //       }, {});

    //       // 添加 inMultipleNotInThisPage 中的数据到 finalToggleListObj
    //       inMultipleNotInThisPage.forEach(item => {
    //         finalToggleListObj[item.id] = item;
    //       });

    //       // 删除 inThisPageNotInMultiple 中的数据从 finalToggleListObj
    //       inThisPageNotInMultiple.forEach(item => {
    //         delete finalToggleListObj[item.id];
    //       });

    //       // 将 finalToggleListObj 转换回数组
    //       const updatedFinalToggleList = Object.values(finalToggleListObj);

    //       // 如果 finalToggleList 是响应式的，例如在 Vue.js 中，你可能需要更新原始的响应式变量
    //       finalToggleList.value = updatedFinalToggleList;
    //       thisPageList.value = []
    //       multipleTable.value.clearSelection();
    //     }else{
    //       console.log('4')
    //       multipleSelection.value.forEach(item => {
    //         finalToggleList.value.push(item)
    //       })
    //     }




    // }else if (finalToggleList.value != null && finalToggleList.value.length >0 && ( multipleSelection.value  == null || multipleSelection.value.length == 0) ){
    //   console.log('5')
    //   finalToggleList.value.forEach(item => {
    //   const row = list.value.find(r => r.matId === item.matId);
    //   console.log(row)
    //   if (row) {
    //     multipleTable.value.toggleRowSelection(row, true);
    //     thisPageList.value.push(row);
    //   }
    //  });
    // }
    // console.log(multipleSelection.value)
    // console.log(finalToggleList.value)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const multipleTable: any = ref<InstanceType<typeof ElTable>>()
const multipleSelection: any = ref([])

const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
}

//指定key值,数据更新之后保留之前选中的数据
const getRowKeys = (row) => {
  return row.id
}
const clickRow = (row: any) => {
  if (row) {
    multipleTable.value!.toggleRowSelection(row, undefined)
  } else {
    multipleTable.value!.clearSelection()
  }
}

/** 提交表单 */

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = () => {
  if (!multipleSelection.value || multipleSelection.value.length <= 0) {
    message.warning(t('common.selectText'))
    return
  }
  dialogVisible.value = false
  // 发送操作成功的事件
  // console.log(dialogTypeValue.value)
  console.log(multipleSelection.value);

  emit('success', multipleSelection.value, faindex.value)
  //重置父组件传递过来的值
}

const userInit = ref()
const faindex =ref()
/** 打开弹窗 */
const open = async (owners,index) => {
  multipleSelection.value=[]
  console.log(owners)
  postList.value = []
              postList.value.push({
              label:'4',
              value:'4'
            })
                          postList.value.push({
              label:'5',
              value:'5'
            })
  beforeOwnerList.value = owners;
  faindex.value=index
  dialogVisible.value = true
  queryParams.userNickName = undefined
  queryParams.deptId = undefined
  queryParams.postId = undefined
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 加载岗位列表
  // postList.value = await PostApi.getSimplePostList()

  //用户列表数据
  userInit.value = await UserApi.getSimpleUserList()
  handleQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

