<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" /></div> -->
      </div>
      <div class="container-box">
        <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>
            <div class="reloBox">
              <div class="orgName">{{ item.userList.name }}</div>
              <el-checkbox-group v-model="item.checkList">
                <el-checkbox :label="items.userid" v-for="(items, index) in item.userList.users" :key="items.id">{{
                  items.username }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>

        </div>
      </div>


    </div>
    <!-- <div v-if="showNode && showModel">
          <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 v-else>

          </div>
        </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 } 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 InterfaceAddress = 'http://155.24.22.30:2109/mosty-api/mosty-gsxt/'
const InterfaceAddress = 'http://192.168.0.231:8006/mosty-api/mosty-gsxt/'
// 新增
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) => {
  const { userList, checkList } = nodeData;
  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 (checkListData.value[i].checkList && checkListData.value[i].checkList.length > 0) {
      data[checkListData.value[i].nodeId] = transformData(checkListData.value[i]);
    } else {
      listError.push(checkListData.value[i].nodeName)

    }
  }
  if (listError.length > 0) {
    proxy.$message({ type: "warning", message: listError.join('、') + '请选择审批人' });
    return
  }
  const submitData = {
    ...props.createProcess,
    flowType: "ZyCompany",
    callback: {
      "START": "",//流程开始
      "APPROVE": "",//节点审批通过
      "BACK": "",//退回上一节点
      "REVOKE": "",//撤回审批
      "DONE": `${InterfaceAddress}${props.path.byMeansOf}?id=${props.createProcess.processData.rwbh}&bkZt=05`,//流程审批通过
      "ABORT": `${InterfaceAddress}${props.path.nobyMeansOf}?id=${props.createProcess.processData.rwbh}&bkZt=06`,//审批不通过
      "RECOVER": "",//流程回收
      "AGAIN": `${InterfaceAddress}${props.path.recycle}?id=${props.createProcess.processData.rwbh}&bkZt=07`//流程退回初始
    },
    decision: JSON.stringify({
      ...data,
      services: [],
      events: [],
      userData: newUserData.value,
    })
  }
  console.log(submitData);

  submitData.processData = JSON.stringify(submitData.processData)
  submitData.callback = JSON.stringify(submitData.callback)
  await submitProcess({ ...submitData }).then(res => {
    proxy.$message({ type: "success", message: "提交审批成功" });
    sendMessage(res.rows[0])
  })
  // await emit('getList')
  // emit('close')
  // close()

}


// const deptId = getItem('deptId')
//   let users = nodeData.value.map(item => {
//     return {
//       userId: item.userData.userId,
//       // userId: '540422200010197495',
//       userName: item.userData.userName,
//       userData: JSON.stringify(item.userData.userData)
//       // ...item.userData
//     }
//   })
//   let userData = {
//     id: deptId[0].fzOrgId,
//     orgid: deptId[0].fzOrgId,
//     //  id: '41fbffaf92a34b31bde6302004277486',
//     //     orgid: '41fbffaf92a34b31bde6302004277486',
//     orgcode: deptId[0].deptCode,
//     orgname: deptId[0].deptName,
//   }
//   const promes = {
//     ...props.createProcess,
//     // processData: { ...props.createProcess.processData.sqrw, orgNameData: userData },
//     flowType: "ZyCompany",
//     // iframe: `/#/${props.path.clueVerification}?id=${props.createProcess.processData.rwbh}`,
//     callback: {
//       "START": "",//流程开始
//       "APPROVE": "",//节点审批通过
//       "BACK": "",//退回上一节点
//       "REVOKE": "",//撤回审批
//       "DONE": `${InterfaceAddress}${props.path.byMeansOf}?id=${props.createProcess.processData.rwbh}&bkZt=05`,//流程审批通过
//       "ABORT": `${InterfaceAddress}${props.path.nobyMeansOf}?id=${props.createProcess.processData.rwbh}&bkZt=06`,//审批不通过
//       "RECOVER": "",//流程回收
//       "AGAIN": `${InterfaceAddress}${props.path.recycle}?id=${props.createProcess.processData.rwbh}&bkZt=07`//流程退回初始

//     },
//     decision: JSON.stringify({
//       [modelData.value.nodeId]: {
//         users: users,
//         services: [],
//         events: [],
//         userData: JSON.stringify(userData)
//       }
//     })
//   }
//   promes.processData = JSON.stringify(promes.processData)
//   promes.callback = JSON.stringify(promes.callback)
//   console.log(promes);
//   await submitProcess({ ...promes }).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 modelMsg = ref()
const nodeDetails = ref({})
const loading = ref(false)
const flwsNode = ref({})
const userList = ref()
//节点审核人
const checkList = ref()
const endpoints = [
  '/modelVersion/queryModelVersion',
  '/modelVersion/queryModelNode',
  '/modelVersion/queryModelSequenceFlow',
  '/modelVersion/queryModelReachability'
]
const queryModel = async () => {
  try {
    loading.value = true
    const prrmes = {
      modelId: props.radioData,
      modelStatus: 1
    }
    const res = await splPost(prrmes, '/model/queryModel')
    if (res.rows.length > 0) {
      const resData = await Promise.all(endpoints.map(item => {
        return splPost({ modelVersionId: res.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)

      // 如果是事件节点
      if (eventNode) {
        console.log(eventNode);
        const nodeExtension = JSON.parse(eventNode.nodeExtension)
        console.log(nodeExtension);
        modelData.value = [eventNode]
        checkList.value = modelData.value.map(item => {
          return item.nodeId
        })
        const res = await queryUserListByRule({ roles: '', posts: "", orgid: "eebefa725cb546118d6b2d17c8657ef3" })
        checkListData.value = userList.value = modelData.value.map((item, index) => {
        return { ...item, userList: res.rows[0] }
        })
      } else {
        const targetNodeId = resData[2].rows.filter(item => item.sourceNodeId == sequenceNode.targetNodeId).map(item => item.targetNodeId)
        console.log(targetNodeId);
        const targetIdSet = new Set(targetNodeId);
        modelData.value = resData[1].rows.filter(item => targetIdSet.has(item.nodeId));
        checkList.value = modelData.value.map(item => {
          return item.nodeId
        })
      const nodeExtension = modelData.value.map(item => {
        return JSON.parse(item.nodeExtension)
      })
      const roles = nodeExtension.map(item => {
        return queryUserListByRule({ roles: '', posts: "", orgid: "eebefa725cb546118d6b2d17c8657ef3" })
      })
      const a = await Promise.all(roles)
      checkListData.value = userList.value = modelData.value.map((item, index) => {
        return { ...item, userList: a[index].rows[0] }
      })
      }

      // const targetIdSet = new Set(targetNodeId);
      // modelData.value = resData[1].rows.filter(item => targetIdSet.has(item.nodeId));
      // checkList.value = modelData.value.map(item => {
      //   return item.nodeId
      // })

      // console.log( modelData.value);

      // const nodeExtension = modelData.value.map(item => {
      //   console.log(item);

      //   return JSON.parse(item.nodeExtension)
      // })

      // const roles = nodeExtension.map(item => {
      //   return queryUserListByRule({ roles: '', posts: "", orgid: "eebefa725cb546118d6b2d17c8657ef3" })
      // })
      // console.log(roles);
      // const a = await Promise.all(roles)
      // checkListData.value = userList.value = modelData.value.map((item, index) => {
      //   return { ...item, userList: a[index].rows[0] }
      // })

    } else {
      proxy.$message({ type: "error", message: "模板不存在" });
      showModel.value = false
    }
  } catch (error) {

  } finally {
    loading.value = false
  }

}
// queryModelVersion(res.rows[0].currentVersionId)
// queryModelNode(res.rows[0].currentVersionId)
// modelMsg.value = versionRes.rows[0]
// const nodeRes = await splPost({ modelVersionId: res.rows[0].currentVersionId }, '/modelVersion/queryModelNode')
// if (versionRes.rows.length > 0) {
//   modelData.value = nodeRes.rows.filter(item => item.nodeType == '1')[0]
// }

//发消息
const sendMessage = (gzlid) => {
  const bkshrSfzh = nodeData.value.map(item => {
    return {
      bkshrXm: item.userData.userName,
      bkshrSfzh: item.userData.sfzh,
      bkshrSsbmmc: item.userData.userData.orgname,
      bkshrSsbmdm: item.userData.userData.orgcode,
    }
  })
  const promes = {
    xxly: '005',
    gzlid: gzlid,
    list: bkshrSfzh,
    versionId: modelMsg.value.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: {},
    }
  ]
  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>
