<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
    >
      <el-form-item label="项目名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="itemType">
        <el-select
          v-model="queryParams.itemType"
          placeholder="请选择项目类型"
          clearable
          class="!w-240px"
        >
          <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="userId">-->
<!--        <el-input-->
<!--            v-model="queryParams.userId"-->
<!--            placeholder="请输入申请人的用户编号"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--            class="!w-240px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="项目归属" prop="itemBelong">
        <el-input
          v-model="queryParams.itemBelong"
          placeholder="请输入项目归属"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申请类型" prop="type">
        <el-select
            v-model="queryParams.type"
            placeholder="请选择申请类型"
            clearable
            class="!w-240px"
        >
          <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="reason">
        <el-input
            v-model="queryParams.reason"
            placeholder="请输入申请原因"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="资金总额" prop="funding">
        <el-input
            v-model="queryParams.funding"
            placeholder="资金总额"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="审批结果" prop="status">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择审批结果"
            clearable
            class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['bpm:disbursement:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 发起流程
        </el-button>
        <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['bpm:disbursement:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" />
<!--      <el-table-column label="申请人的用户编号" align="center" prop="userId" />-->
      <el-table-column label="项目名称" align="center" prop="itemName" />
      <!-- <el-table-column label="项目类型" align="center" prop="itemType" /> -->
      <el-table-column label="创建人id" align="center" prop="itemBelong" />
      <el-table-column label="绑定图层" align="left" prop="itemShp" />
      <el-table-column label="原因备注" align="center" prop="reason" />
      <!-- <el-table-column label="资金总额" align="center" prop="funding" /> -->
      <!-- <el-table-column label="审批结果" align="center" prop="status" /> -->
<!--      <el-table-column label="流程实例的编号" align="center" prop="processInstanceId" />-->
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
      />
<!--      <el-table-column label="文件" align="center" prop="file" />-->
      <el-table-column align="center" label="操作" width="200">
        <template #default="scope">
          <el-button
              v-hasPermi="['bpm:disbursement:query']"
              link
              type="primary"
              @click="handleDetail( scope.row)"
          >
            配置
          </el-button>

          <el-button
            v-hasPermi="['bpm:disbursement:query']"
            link
            type="primary"
            @click="authority(scope.row.id)"
          >
            权限
          </el-button>
          <el-button
            v-hasPermi="['bpm:disbursement:query']"
            link
            type="primary"
            @click="record(scope.row.id)"
          >
            进度
          </el-button>
          <!-- <el-button
              v-hasPermi="['bpm:disbursement:query']"
              link
              type="primary"
              @click="handleProcessDetail(scope.row)"
          >
            进度
          </el-button> -->
          <el-button
              v-hasPermi="['bpm:disbursement:create']"
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <LtyForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：添加/修改 -->
  <RecordForm ref="recordRef" @success="getList" />

  <AuthorityForm ref="authorityRef" @success="getList" />

</template>
<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DisbursementApi, DisbursementVO } from '@/api/bpm/disbursement'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import LtyForm from './LtyForm.vue'
import RecordForm from './RecordForm.vue'
import AuthorityForm from './AuthorityForm.vue'
/** 资金拨付流程表	 列表 */
defineOptions({ name: ' <el-form-item label="金额" prop="funding">\n' +
    '      <el-input v-model="formData.funding" placeholder="请输入金额" />\n' +
    '    </el-form-item>' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter() // 路由

const loading = ref(true) // 列表的加载中
const list = ref<DisbursementVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  type: undefined,
  reason: undefined,
  funding: undefined,
  itemName: undefined,
  itemType: undefined,
  itemBelong: undefined,
  status: undefined,
  processInstanceId: undefined,
  createTime: [],
  file: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DisbursementApi.getDisbursementPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref();

const recordRef = ref();

const authorityRef = ref();
const ltyEdit = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
const authority = (id?: number) => {
  authorityRef.value.open(id)
}
const record = (id?: number) => {
  recordRef.value.open(id)
}

/** 添加操作 */
const openForm = () => {
  router.push({ name: 'BpmDisbursementCreate' })
}

/** 详情操作 */
const handleDetail = (row: DisbursementApi.DisbursementVO) => {
  router.push({
    name: 'BpmDisbursementDetail',
    query: {
      id: row.id
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DisbursementApi.deleteDisbursement(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DisbursementApi.exportDisbursement(queryParams)
    download.excel(data, '资金拨付流程表	.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 取消请假操作 */
const cancelLeave = async (row) => {
  // 二次确认
  const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
    inputErrorMessage: '取消原因不能为空'
  })
  // 发起取消
  await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.id, value)
  message.success('取消成功')
  // 刷新列表
  await getList()
}

/** 审批进度 */
const handleProcessDetail = (row) => {
  router.push({
    name: 'BpmProcessInstanceDetail',
    query: {
      id: row.processInstanceId
    }
  })
}

// fix: 列表不刷新的问题。
watch(
  () => router.currentRoute.value,
  () => {
    getList()
  }
)

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
