<template>
  <el-dialog class="dialog-container" :model-value="modelValue" :title="titles" :before-close="handleClose">
    <div class="dialog-header">
      <div class="flex align-center">下一节点：
        <el-checkbox v-model="showNode" :label="modelData.nodeName" size="large" />
      </div>
      <div> <el-button type="success" :icon="Plus" @click="newAdditions" /></div>
    </div>
    <div class="container-box">
      <div v-if="showNode">
        <el-divider content-position="left">节点</el-divider>
        <div>
          <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>

    <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 } 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.2422.30:2109/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 = orgId.value
  nodeData.value[chageIndex.value].orgData = {
    id:orgId.value,
    orgid:orgId.value,
    // id: '41fbffaf92a34b31bde6302004277486',
    // orgid: '41fbffaf92a34b31bde6302004277486',
    orgcode: e.orgCode,
    orgname: e.orgName
  }
  getUser()
}
// 提交
const qcckPostList = async () => {
  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.rwbh}&bkZt=05`,//流程审批通过
      "ABORT": `${InterfaceAddress}${props.path.nobyMeansOf}?id=${props.createProcess.rwbh}&bkZt=06`,//审批不通过
      "RECOVER": "",//流程回收
      "AGAIN": `${InterfaceAddress}${props.path.recycle}?id=${props.createProcess.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 modelData = ref({})
const modelMsg = ref()
const queryModel = async () => {
  const prrmes = {
    modelId: props.radioData,
    modelStatus: 1
  }
  const res = await splPost(prrmes, '/model/queryModel')
  const versionRes = await splPost({ modelVersionId: res.rows[0].currentVersionId }, '/modelVersion/queryModelVersion')
  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;
  overflow: auto;

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

    .select-user {
      margin: 0 10px;
    }
  }
}
</style>
