<template>

  <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
  >
<!--    <el-form-item label="用户编号" prop="userId">-->
<!--      <el-input v-model="formData.userId" placeholder="请输入申请人的用户编号" />-->
<!--    </el-form-item>-->
    <el-form-item label="项目名称" prop="itemName">
      <el-input v-model="formData.itemName" placeholder="请输入项目名称" />
    </el-form-item>
    <!-- <el-form-item label="项目类型" prop="itemType">
      <el-select v-model="formData.itemType" placeholder="请选择项目类型">
        <el-option
          v-for="dict in getIntDictOptions(DICT_TYPE.BPM_DISBUESEMENT_ITEM_TYPE)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </el-form-item> -->
    <!-- <el-form-item label="项目归属" prop="itemBelong">
     <el-input v-model="formData.itemBelong" placeholder="请输入项目归属（上级项目）" />
      <el-tree-select
        v-model="formData.itemBelong"
        :data="datadept"
        :props="defaultProps"
        check-strictly
        node-key="id"
        placeholder="请选择归属部门"
      />
    </el-form-item> -->
    <!-- <el-form-item label="资金类型" prop="type">
      <el-select
        v-model="formData.type"
        multiple
        filterable
        allow-create
        default-first-option
        placeholder="请选择资金申请类型">
        <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BPM_FUND_APPLY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
        />
      </el-select>
    </el-form-item> -->
    <!-- <el-form-item label="资金总额" prop="funding">
      <el-input v-model="formData.funding" placeholder="请输入金额" />
    </el-form-item> -->

    <!-- <el-form-item label="申请原因" prop="reason">
      <el-input v-model="formData.reason" placeholder="请输入备注" />
    </el-form-item> -->
    <!-- <el-form-item label="专项借款申请材料" prop="specialLoansFile">
      <UploadFile v-model="formData.specialLoansFile" />
    </el-form-item> -->
    <!-- <el-form-item label="资金申请材料" prop="fundingApplicationFile">
      <UploadFile v-model="formData.fundingApplicationFile" />
    </el-form-item> -->
    <!-- <el-form-item label="项目相关图层" prop="itemShp">
      <el-select
        v-model="formData.itemShp"
        multiple
        filterable
        allow-create
        default-first-option
        placeholder="请选择项目相关图层">
        <el-option
          v-for="dict in datagisname"
          :key="dict.id"
          :label="dict.shpName"
          :value="dict.shpName"
        />
      </el-select>
    </el-form-item> -->

    <!-- <el-form-item label="项目3D图层" prop="file">
      <el-input v-model="formData.file" placeholder="请输入项目相关矢量图层" /> -->
<!--      <el-select-->
<!--        v-model="formData.file"-->
<!--        :reserve-keyword="false"-->
<!--        placeholder="请选择3DTiles模型"-->
<!--      >-->
<!--        <el-option-->
<!--          v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_THREED_TILES)"-->
<!--          :key="dict.value"-->
<!--          :label="dict.label"-->
<!--          :value="dict.value"-->
<!--        />-->
<!--      </el-select>-->
    <!-- </el-form-item> -->
    <!-- <el-form-item label="项目相关佐证材料" prop="itemImage"> -->
      <!-- <UploadImg v-model="formData.itemImage" />
    </el-form-item> -->
<!--    <el-form-item label="其他文件" prop="file">-->
<!--      <UploadFile v-model="formData.file" />-->
<!--    </el-form-item>-->
    <el-form-item>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </el-form-item>

  </el-form>

</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { DisbursementApi, DisbursementVO } from '@/api/bpm/disbursement'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as DefinitionApi from '@/api/bpm/definition'
import * as UserApi from '@/api/system/user'
import {defaultProps, handleTree} from "@/utils/tree";
import {getSimpleDeptList} from "@/api/system/dept";
import { getSimpleGisNameList } from "@/api/layer/gisname"

const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

defineOptions({ name: 'BpmDisbursementCreate' })
const datadept = ref([])
const datagisname = ref([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined,
  type: undefined,
  reason: undefined,
  funding: undefined,
  status: undefined,
  processInstanceId: undefined,
  file: undefined,
  specialLoansFile: undefined,
  itemName: undefined,
  itemType: undefined,
  itemBelong: undefined,
  itemShp: [],
  // itemShp: undefined,
  itemImage: undefined,
  fundingApplicationFile: undefined,
})
const formRules = reactive({
  // userId: [{ required: true, message: '申请人的用户编号不能为空', trigger: 'blur' }],
  itemName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  // itemType: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
  // type: [{ required: true, message: '申请类型不能为空', trigger: 'change' }],
  // reason: [{ required: true, message: '申请原因不能为空', trigger: 'blur' }],
  // funding: [{ required: true, message: '资金总额不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
// const deptList = ref<Tree[]>([]) // 树形结构

// 指定审批人
const processDefineKey = 'disbursement' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref({}) // 发起人选择审批人的表单 Rules
const userList = ref<any[]>([]) // 用户列表

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    await startUserSelectAssigneesFormRef.value.validate()
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DisbursementVO

    // 设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      data.startUserSelectAssignees = startUserSelectAssignees.value
    }

    await DisbursementApi.createDisbursement(data)
    message.success(t('common.createSuccess'))
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'Disbursement' })
  } finally {
    formLoading.value = false
  }
}

const deptdatalist = async () => {
  const res = await getSimpleDeptList()
  datadept.value = res
}

const gisnamedatalist = async () => {
  // const res =
  datagisname.value = await getSimpleGisNameList();
}



/** 初始化 */
onMounted(async () => {
  // const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
  //   undefined,
  //   processDefineKey
  // )
  // if (!processDefinitionDetail) {
  //   message.error('资金拨付的流程模型未配置，请检查！')
  //   return
  // }
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
  // 设置指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    // 设置校验规则
    for (const userTask of startUserSelectTasks.value) {
      startUserSelectAssignees.value[userTask.id] = []
      startUserSelectAssigneesFormRules.value[userTask.id] = [
        { required: true, message: '请选择审批人', trigger: 'blur' }
      ]
    }
    // 加载用户列表
    userList.value = await UserApi.getSimpleUserList()
  }
  deptdatalist()
  gisnamedatalist()
})
</script>
