<template>
  <el-dialog class="dialog-container" :model-value="modelValue" :title="titles" :before-close="close">
    <div v-loading="loading">
      <div class="dialog-header" v-if="showModel">
        <div class="flex align-center">下一节点：
          <el-checkbox-group v-model="checkList" @change="handleCheckAllChange">
            <el-checkbox v-model="showNode" :label="item.nodeId" size="large" v-for="(item, index) in modelData"
              :key="index">{{ item.nodeName }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div> <el-button type="success" :icon="Plus" @click="newAdditions"  v-if="optional"/></div>
      </div>
      <div v-if="optional"  class="container-box">
        <!-- <div v-if="flwsNode.flwsUserNode?.role.length == 0"> -->
            <div class="row" v-for="(item, index) in nodeData" :key="index">
              <MOSTY.Department filterable v-model="item.deptId" width="100%"
                @getDepValue="(obj) => changePostList(index, obj)" clearable placeholder="请选择所属部门" />
              <el-select class="select-user" v-model="item.userId" filterable placeholder="选择审批人"
                @change="changeUser(index)">
                <el-option v-for="item in item.listData" :key="item.id" :label="item.userName" :value="item.id" />
              </el-select>
              <div>
                <el-button type="danger" @click="newDelitions(index)">删除</el-button>
              </div>
            </div>
          <!-- </div> -->
      </div>
      <div class="container-box" v-else>
        <div v-for="(item, index) in userList" :key="item.id">
          <div v-if="checkList.includes(item.nodeId)">
            <el-divider content-position="left">{{ item.nodeName }}</el-divider>
            <template v-if="Array.isArray(item.userList)">
              <div class="reloBox" v-for="items in item.userList">
                <div class="orgName">{{ items.name }}</div>
                <el-checkbox-group v-model="items.checkList">
                  <el-checkbox :label="it.userid" v-for="(it, index) in items.users" :key="it.id">{{
                    it.username }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </template>
            <template v-else>
              <div class="reloBox">
                <div class="orgName">{{ item.userList.name }}</div>
                <el-checkbox-group v-model="item.checkList">
                  <el-checkbox :label="it.userid" v-for="(it, index) in item.userList.users" :key="it.id">{{
                    it.username }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </template>


          </div>

        </div>
      </div>


    </div>
    <div v-if="showNode && showModel">


        </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="qcckPostList">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script>
</script>
<script setup>
import { ref, getCurrentInstance, reactive, watch } from 'vue'
import { qcckGet, qcckPost } from '@/api/qcckApi'
import { splGet, splPost, submitProcess, queryUserListByRule, queryListByEntity, querysingleByEntity, queryUporgsByEntity } from '@/api/spl'
import { getItem } from '@/utils/storage'
import { Plus } from '@element-plus/icons-vue'
import * as MOSTY from "@/components/MyComponents/index";
const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }, title: {
    type: String,
    default: '发起流程'
  },
  createProcess: {
    type: Object,
    default: () => { }
  }, radioData: {
    type: String,
    default: ''
  }, path: {
    type: Object,
    default: {
      byMeansOf: '',
      nobyMeansOf: '',
      clueVerification: "",
      recycle: ""
    }
  }, userData: {
    type: Object,
    default: () => {
      return {
        ajmc: "",
        flowType: ""
      }
    }

  }
})
const emit = defineEmits(['update:modelValue', 'close', 'getList'])
const titles = ref(props.title)
const showNode = ref(true)

// 新增
const nodeData = ref([
  {
    deptId: '',
    userId: '',
    userData: {},
    orgData: {},
  }
])
//新增表单
const newAdditions = () => {
  nodeData.value.push({
    deptId: '',
    userId: '',
    userData: {},
    orgData: {},
    listData: []
  })
}
// 删除表单
const newDelitions = (item) => {
  nodeData.value.splice(item, 1)
}
const chageIndex = ref(0)
// 选取角色
const changeUser = (index) => {
  chageIndex.value = index
  let obj = nodeData.value[index].listData.find(item => { return item.id == nodeData.value[index].userId })
  nodeData.value[index].userData = {
    userId: obj.userId,
    userName: obj.userName,
    sfzh: obj.idEntityCard,
    userData: {
      // id: '41fbffaf92a34b31bde6302004277486',
      // orgid: '41fbffaf92a34b31bde6302004277486',
      id: orgId.value,
      orgid: orgId.value,
      orgcode: obj.deptCode,
      orgname: obj.deptName
    }
  }
}
//选取部门
const orgId = ref()
const changePostList = (index, e) => {
  orgId.value = e.fzOrgId
  chageIndex.value = index
  nodeData.value[chageIndex.value].id = e.id
  nodeData.value[chageIndex.value].orgData = {
    id: orgId.value,
    orgid: orgId.value,
    // id: '41fbffaf92a34b31bde6302004277486',
    // orgid: '41fbffaf92a34b31bde6302004277486',
    orgcode: e.orgCode,
    orgname: e.orgName
  }
  getUser()
}
const newUserData = ref({})

const transformData = (nodeData) => {
  console.log(nodeData);

  const { userList, checkList } = nodeData;
  if (Array.isArray(userList)) {
    const result = [];
    // 遍历所有组织
    for (const org of userList) {
      // 遍历组织中的用户
      for (const user of org.users) {
        // 创建用户数据对象
        const userData = {
          id: user.id,
          orgid: org.id,
          orgcode: org.code,
          orgname: org.name
        };
        // 创建结果对象
        const transformedUser = {
          userId: user.userid,
          userName: user.username,
          userData: JSON.stringify(userData)
        };
        result.push(transformedUser);
      }
    }
    return result;
  } else {
    const { id: orgid, code: orgcode, name: orgname, users } = userList;
    const checkListSet = new Set(checkList);
    const filteredUsers = users.filter(user => checkListSet.has(user.userid));
    return filteredUsers.map(user => {
      newUserData.value = JSON.stringify({
        id: user.id,
        orgid,
        orgcode,
        orgname
      })
      return {
        userId: user.userid,
        userName: user.username,
        userData: newUserData.value
      }
    }
    )
  }

};



const checkListData = ref()
// 删除
const handleCheckAllChange = (e) => {
  const checkListSet = new Set(e);
  checkListData.value = userList.value.filter(item => checkListSet.has(item.nodeId));

}
// 提交
const qcckPostList = async () => {
  const data = {}
  const listError = []
  for (let i = 0; i < checkListData.value.length; i++) {

    if (Array.isArray(checkListData.value[i].userList)) {
      for (let j = 0; j < checkListData.value[i].userList.length; j++) {
        const item = checkListData.value[i].userList[j]
        if (item.checkList && item.checkList.length > 0) {
          data[checkListData.value[i].nodeId] = {
          users: transformData(checkListData.value[i])
          }
        } else {
          listError.push(checkListData.value[i].nodeName)
        }
        continue
      }
    } else {
      if (checkListData.value[i].checkList && checkListData.value[i].checkList.length > 0) {
        data[checkListData.value[i].nodeId] = {
          users: transformData(checkListData.value[i])
        }
      } else {
        listError.push(checkListData.value[i].nodeName)
      }
    }

  }
  if (modelData.value.length !== checkList.value.length) {
    proxy.$message({ type: "warning", message: '环节' + listError.join('、') + '中有需要勾选的项' });
    return
  }
  if (listError.length > 0) {
    proxy.$message({ type: "warning", message: listError.join('、') + '请选择审批人' });
    return
  }
  const submitData = {
    ...props.createProcess,
    decision: JSON.stringify({
      ...data,
      services: [],
      events: [],
      userData: newUserData.value,
    })
  }
  submitData.processData = JSON.stringify(submitData.processData)
  await submitProcess({ ...submitData }).then(res => {
    proxy.$message({ type: "success", message: "提交审批成功" });
    sendMessage(res.rows[0])
  })
  await emit('getList')
  emit('close')
  close()
}

//获取角色
const getUser = () => {
  const promes = {
    size: 200, current: 1,
    deptId: nodeData.value[chageIndex.value].id
  }
  qcckGet(promes, '/mosty-base/sysUser/selectPage').then(res => {
    nodeData.value[chageIndex.value].listData = res.records
  })
}
const showModel = ref(true)
//查询模板
const modelData = ref({})
const loading = ref(false)
const userList = ref()
//节点审核人
const checkList = ref()
const endpoints = [
  '/modelVersion/queryModelVersion',
  '/modelVersion/queryModelNode',
  '/modelVersion/queryModelSequenceFlow',
  '/modelVersion/queryModelReachability'
]
const queryModel = async () => {
  try {
    loading.value = true

    // 查询模型信息
    const params = {
      modelId: props.radioData,
      modelStatus: 1
    }
    const modelRes = await splPost(params, '/model/queryModel')

    if (modelRes.rows.length === 0) {
      proxy.$message({ type: "error", message: "模板不存在" })
      showModel.value = false
      return
    }
    // 并行获取模型相关数据
    const resData = await Promise.all(endpoints.map(item => {
      return splPost({ modelVersionId: modelRes.rows[0].currentVersionId }, item)
    }))
    // 解析节点数据
    const rootNode = resData[1].rows.find(item => item.eventType === '0')
    const sequenceNode = resData[2].rows.find(item => item.sourceNodeId === rootNode.nodeId)
    const eventNode = resData[1].rows.find(item =>
      item.nodeType === '1' && item.nodeId === sequenceNode.targetNodeId
    )
    const orgId = 'a8aa5ed229724b278faa7abd0f0cceb6'
    // getItem('userOrg').parentid
    if (eventNode) {
      // 处理事件节点
      await handleEventNode(eventNode, orgId)
    } else {
      // 处理普通节点
      await handleNormalNodes(resData, sequenceNode, orgId)
    }
  } catch (error) {
    console.error('查询模型失败:', error)
    proxy.$message({ type: "error", message: "查询模型失败，请重试" })
  } finally {
    loading.value = false
  }
}
const optional=ref(false)
// 处理事件节点
const handleEventNode = async (eventNode, orgId) => {

  const nodeExtension = JSON.parse(eventNode.nodeExtension)
  modelData.value = [eventNode]
  checkList.value = [eventNode.nodeId]
  let userRes
  let orgData
  const roles = nodeExtension.flwsUserNode.role[0] ? nodeExtension.flwsUserNode.role[0] : ''
  const promes = {
    posts: "",
    orgid: ""
  }
  if (nodeExtension.flwsUserNode.orgType == 'brothers') {
    orgData = await queryListByEntity({ id: orgId })
  } else if (nodeExtension.flwsUserNode.orgType == 'parent') {
    orgData = await querysingleByEntity({ id: orgId })
  } else if (nodeExtension.flwsUserNode.orgType == 'parents') {
    orgData = await queryUporgsByEntity({ id: orgId })
  } else if (nodeExtension.flwsUserNode.orgType == 'appoint') {
    // orgData = await queryUporgsByEntity({ orgcode: orgId })
  }
  if (nodeExtension.flwsUserNode.orgType == 'appoint') {
    promes.roles = roles
    promes.orgcode = nodeExtension.flwsUserNode.orgcode
    userRes = await queryUserListByRule(promes)
    checkListData.value = userList.value = [{
      ...eventNode,
      userList: userRes.rows[0]
    }]
  }
  if (nodeExtension.flwsUserNode.orgType == 'current') {
    promes.roles = roles
    promes.orgid = orgId
    userRes = await queryUserListByRule(promes)
    checkListData.value = userList.value = [{
      ...eventNode,
      userList: userRes.rows[0]
    }]
  } else if (nodeExtension.flwsUserNode.orgType == 'optional') {
    optional.value=true
  } else {

    const parentids = orgData.rows.map(item => item.parentid)
    const userListPromises = parentids.map((item) => {
      const promes = {
        roles: roles,
        posts: "",
        orgid: item
      }
      return queryUserListByRule(promes)
    }
    )
    const userListResults = await Promise.all(userListPromises)
    checkListData.value = userList.value = modelData.value.map((item, index) => ({
      ...item,
      userList: userListResults[index]?.rows[0]
    }))
  }
  console.log(checkListData.value);


}

// 处理普通节点
const handleNormalNodes = async (resData, sequenceNode, orgId) => {

  const targetNodeIds = resData[2].rows
    .filter(item => item.sourceNodeId === sequenceNode.targetNodeId)
    .map(item => item.targetNodeId)
  const targetIdSet = new Set(targetNodeIds)
  modelData.value = resData[1].rows.filter(item => targetIdSet.has(item.nodeId))
  checkList.value = modelData.value.map(item => item.nodeId)
  // 并行获取用户列表
  let promesList = {}
  for (let i = 0; i < modelData.value.length; i++) {
    const str = JSON.parse(modelData.value[i].nodeExtension)
    let res = {}
    let list = []
    if (str.flwsUserNode.orgType == 'brothers') {
      res = await queryListByEntity({ parentid: orgId })
      list = res.rows.map(item => {
        return {
          orgid: item.id,
          posts: str.flwsUserNode.post[0] ? str.flwsUserNode.post[0] : '',
          roles: str.flwsUserNode.role[0] ? str.flwsUserNode.role[0] : '',
        }
      })
      promesList[modelData.value[i].nodeId] = list
    } else if (str.flwsUserNode.orgType == 'parent') {
      res = await querysingleByEntity({ id: orgId })
      list = res.rows.map(item => {
        return {
          orgid: item.id,
          posts: str.flwsUserNode.post[0] ? str.flwsUserNode.post[0] : '',
          roles: str.flwsUserNode.role[0] ? str.flwsUserNode.role[0] : '',
        }
      })
      promesList[modelData.value[i].nodeId] = list
    } else if (str.flwsUserNode.orgType == 'parents') {
      res = await queryUporgsByEntity({ id: orgId })
      list = res.rows.map(item => {
        return {
          orgid: item.id,
          posts: str.flwsUserNode.post[0] ? str.flwsUserNode.post[0] : '',
          roles: str.flwsUserNode.role[0] ? str.flwsUserNode.role[0] : '',
        }
      })
      promesList[modelData.value[i].nodeId] = list
    } else if (str.flwsUserNode.orgType == 'appoint') {
      list = [{
        posts: str.flwsUserNode.post[0] ? str.flwsUserNode.post[0] : '',
        roles: str.flwsUserNode.role[0] ? str.flwsUserNode.role[0] : '',
        orgcode: str.flwsUserNode.orgcode
      }]
      promesList[modelData.value[i].nodeId] = list
    } else {
      list = [{
        posts: str.flwsUserNode.post[0] ? str.flwsUserNode.post[0] : '',
        roles: str.flwsUserNode.role[0] ? str.flwsUserNode.role[0] : '',
        orgid: orgId
      }]
      promesList[modelData.value[i].nodeId] = list
    }
  }
  const listByRule = {}
  for (const key in promesList) {
    console.log(promesList[key]);

    listByRule[key] = promesList[key].map(item => {
      return queryUserListByRule(item)
    })
  }
  const userListByRule = {}
  for (const key in listByRule) {
    userListByRule[key] = await Promise.all(listByRule[key])
  }
  const model = {}
  for (const key in userListByRule) {
    model[key] = userListByRule[key].flatMap(item => item.rows)
  }
  checkListData.value = userList.value = modelData.value.map((item, index) => {
    return {
      ...item,
      userList: model[item.nodeId] ? model[item.nodeId] : []
    }
  })
}
function filterUsersWithOrgInfo(orgsData, checkList) {
    const result = [];

    // 如果没有数据或检查列表为空，返回空数组
    if (!orgsData || !Array.isArray(orgsData) || !checkList || checkList.length === 0) {
        return result;
    }

    // 将checkList转换为Set以提高查找效率
    const checkSet = new Set(checkList);

    // 遍历所有组织
    for (const org of orgsData) {
        // 检查组织是否有用户数据
        if (org.users && Array.isArray(org.users)) {
            // 筛选匹配的用户
            for (const user of org.users) {
                if (checkSet.has(user.userid)) {
                    // 创建带组织信息的用户对象
                    const userWithOrgInfo = {
                        ...user, // 保留所有原始用户属性
                        orgCode: org.code, // 添加组织code
                        orgName: org.name, // 添加组织name
                        orgId: org.id      // 添加组织id
                    };
                    result.push(userWithOrgInfo);
                }
            }
        }
    }

    return result;
}
//发消息
const sendMessage = (gzlid) => {
  let letDataCheck = []
  let userList = []
  console.log(checkListData.value);

  for (let i = 0; i < checkListData.value.length; i++) {
    letDataCheck = [...letDataCheck, ...checkListData.value[i].checkList]
  userList.push(checkListData.value[i].userList)
  }
  console.log(letDataCheck);
  console.log(userList);
  const bkshrSfzh = filterUsersWithOrgInfo(userList, letDataCheck).map(item => {
        return {
      bkshrXm: item.username,
      bkshrSfzh: item.userid,
      bkshrSsbmmc: item.orgName,
      bkshrSsbmdm: item.orgCode,
    }
  })
  const promes = {
    xxly: '005',
    gzlid: gzlid,
    list: bkshrSfzh,
    versionId: checkListData.value[0].modelVersionId,
    id: props.createProcess.processData.rwbh
  }
  switch (props.userData.flowType) {
    case 'BKSP':
      qcckPost(promes, '/mosty-gsxt/tbGsxtBk/updateBkgzl').then(res => {
        console.log(res);
      })
      break;
    case 'ZDRYSDFJDP':
      qcckPost(promes, '/mosty-gsxt/tbGsxtRqfjRy/updateBkgzl').then(res => {
        console.log(res);
      })
      break;
    case 'XSSJCJSP':
      qcckPost(promes, '/mosty-gsxt/qbcj/updateBkgzl').then(res => {
        console.log(res);
      })
      break;
  }
}

watch(() => props.modelValue, (val) => {
  if (val) {
    queryModel()
  }
})
const close = () => {
  nodeData.value = [
    {
      deptId: '',
      userId: '',
      userData: {},
      orgData: {},
    }
  ]
  optional.value=false
  emit('update:modelValue', false)
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/homeScreen.scss";

::v-deep .el-dialog__body {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
}



.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.container-box {
  // height: 300px;
  min-height: 300px;
  overflow: auto;
  // border: 1px solid rgba(172, 172, 172, 0.479);
  padding: 10px;
  max-height: 500px;

  // border-radius: 5px;
  .row {
    margin-top: 10px;
    align-items: center;
    display: flex;
    margin-right: 10px;

    .select-user {
      margin: 0 10px;
    }
  }

  .reloBox {
    position: relative;
    padding: 0 10px;
    border: 1px solid rgba(192, 192, 192, 0.426);
    border-radius: 5px;
    min-height: 100px;
    margin-bottom: 20px;

    .orgName {
      position: absolute;
      transform: translate(-50%, -50%);
      left: 50%;
      padding: 0 10px;
      background-color: #fff;
    }
  }
}
</style>
