<template>
  <el-dialog v-model="dialogVisible" title="添加评价小组" width="60%">
    <div class="flex just-end">
      <el-button type="primary" @click="addUser">新增人员</el-button>

    </div>
    <div class="pjxz-table-div">
      <el-table :data="tableData" border stripe>
        <el-table-column label="序号" type="index" align="center" width="150" />
        <el-table-column label="评价人员" property="userName" align="center" width="250"> </el-table-column>
        <el-table-column label="范围" property="scope" align="center"></el-table-column>
        <el-table-column label="操作" property="aliasName" align="center">
          <template #default="{ row, $index }">
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="remove(row)">
              <template #reference>
                <el-link type="danger">删除</el-link>
              </template>
            </el-popconfirm>
            <span class="operedit" @click="editScoped(row, $index)">
              <el-icon>
                <EditPen />
              </el-icon>
              编辑范围
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 人员组件 -->
      <ChooseUser id="most-user-pj" v-model="isShowUserTc" :Single="false" :deptId="deptId" :data="userData"
        @choosedUsers="userChange"></ChooseUser>

      <!-- 选择部门范围 -->
      <MOSTY.ChoosebmTree v-if='isShowbmTc' :formInfo="fromObj" :showDdld="isShowbmTc" :orgLevels="orgLevels"
        @closezzjg="isShowbmTc = false" @listdata="bmChange" :parentId="null" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineEmits, getCurrentInstance, computed, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import * as MOSTY from "@/components/MyComponents/index";

import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
// import dwhasbjMult from "@/components/MyComponents/ChooseDept/dwhasbjMult.vue";
import { getLevel } from "@/utils/auth.js";

const { proxy } = getCurrentInstance()

const emits = defineEmits(['close', 'ok'])
const props = defineProps({
  /**计划id */
  planid: {
    type: String,
    default: null
  }
})
// const { KHLX } = proxy.$dict("KHLX");
/** 人员列表 */
const tableData = ref([])
/**部门回显 */
const fromObj = ref([])
const isShowUserTc = ref(false)
const isShowbmTc = ref(false)
/** 部门回显 */
const bmIds = ref([])
const currIdx = ref()
const currRow = ref({})
const orgLevels = ref(getLevel() + '1');
const userData = ref([])
/** 已选人员id数组 */
// const userData = computed(() => {
//   return tableData.value.map(item => item.userId).filter(item => item)
// })
const getUserIds = () => {
  return tableData.value.map(item => item.userId).filter(item => item)
}
const deptId = getItem("deptId").ssdwid + "XN";

/** 原人员的行id 方便编辑回传 */
const userIdObj = ref({})
// 表单数据
const formData = ref({
  dictCode: null,
  fbRiskunitTreeId: undefined,
})


// 控制弹窗显示
const dialogVisible = ref(false)
/**要删除的id */
const getDelIds = () => {
  const ids = Object.keys(userIdObj.value).filter(userId => !tableData.value.some(val => val.userId === userId))
  return ids.map(userId => userIdObj.value[userId])
}
// 提交表单并关闭弹窗
const submitForm = () => {
  const pjxzList = tableData.value.map(item => {
    return {
      id: item.id,
      userId: item.userId,
      userName: item.userName,
      scopeId: item.scopeId,
      scope: item.scope,
      orgId: item.orgId,
      orgName: item.orgName,
    }
  })
  /**删除的id */
  const delIds = getDelIds()
  const params = {
    ids: delIds,
    planId: props.planid,
    pjxzList,
  }

  postApi(params, `/mosty-jcgl/dangerPjxz/processPjxzInfo`).then(res => {
    ElMessage({
      type: 'success',
      message: '风险单元绑定成功！',
    })
    emits('ok')
    dialogVisible.value = false
  })
}

// 关闭前处理
const handleClose = () => {
  // 可以在这里添加关闭前的处理逻辑
  dialogVisible.value = false
  emits('close')
}
const addUser = () => {
  isShowUserTc.value = true
}
const getTableData = () => {

  getApi({}, `/mosty-jcgl/dangerPjxz/getList?planId=${props.planid}`).then(res => {

    tableData.value = Array.isArray(res) ? res : []
    userIdObj.value = res.reduce((acc, cur) => {
      acc[cur.userId] = cur.id
      return acc
    }, {})
  })
}
// 公开方法：打开弹窗
const open = (obj) => {


  dialogVisible.value = true
  getTableData()
}
const userChange = (val) => {

  const userId = getUserIds() || []

  const noRepeatArr = val.filter(item => !userId.includes(item.id)).map(item => {
    return {
      userId: item.id,
      userName: item.userName,
      orgId: item.deptId,
      orgName: item.deptName,
      scope: null, // 范围
      scopeId: '',
    }
  })
  tableData.value = [...tableData.value, ...noRepeatArr]
}
const bmChange = (val) => {
  tableData.value[currIdx.value].scopeId = val.map(item => item.id).join(",")
  tableData.value[currIdx.value].scope = val.map(item => item.orgName).join(",")
  tableData.value[currIdx.value].scopeArr = val
}
const remove = (row) => {
  tableData.value = tableData.value.filter(item => item.userId !== row.userId)
}
const editScoped = (row, index) => {

  currRow.value = row
  currIdx.value = index
  fromObj.value = row.scopeId ? row.scopeId.split(",") : []
  isShowbmTc.value = true
}
// 将打开弹窗的方法暴露给父组件
defineExpose({ open })
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}

.pjxz-table-div {
  height: calc(84vh - 220px);
  overflow: auto;
  margin-top: 10px
}
</style>
