<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title">预案审批</div>
    </div>
    <div class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <BasicSearch
            :searchConfig="EMERGENCY_PLAN_APPROVAL_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          />
        </header>
        <BasicTable
          :tableData="tableData"
          :tableConfig="tableConfig"
          @update:pageSize="handleSizeChange"
          @update:pageNumber="handleCurrentChange"
        >
          <template #planType="scope">
            <span>{{ getPlanType(scope.row.planType) }}</span>
          </template>
          <template #eventType="scope">
            <span>{{ getEmergencyEvent(scope.row.eventType) }}</span>
          </template>
          <template #approvalStatus="scope">
            <span>{{ getEmergencyPlanApproStatusLabel(scope.row.approvalStatus) }}</span>
          </template>
          <template #appendix="scope">
            <span class="appendix" v-if="scope.row.appendix" @click="handlePreviewScript(scope.row.appendix)">
              预览
            </span>
            <span v-else>--</span>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton
                v-if="scope.row.approvalStatus === APPROVAL_STATUS.PENDING"
                text="审批"
                @click="handleApproval(scope.row.id, scope.row.approvalOrder)"
              />
              <span v-else>--</span>
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
    <PreviewOnline ref="previewOnlineRef" />
  </div>
  <BasicDialog ref="basicDialogRef" title="审批" @refresh="closeDialog">
    <template #form>
      <el-form ref="formRef" :model="formData" style="width: 100%">
        <el-form-item label="审批：" prop="approvalStatus" :rules="[{ required: true, message: '请选择审批状态' }]">
          <el-radio-group v-model="formData.approvalStatus">
            <el-radio :value="APPROVAL_STATUS.APPROVED">通过</el-radio>
            <el-radio :value="APPROVAL_STATUS.REJECTED">退回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.approvalStatus === APPROVAL_STATUS.REJECTED"
          label="退回原因："
          prop="rejectReason"
          :rules="[{ required: true, message: '请输入退回原因' }]"
        >
          <el-input v-model="formData.rejectReason" placeholder="请输入退回原因" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleApprovalSubmit">提交</el-button>
      <el-button @click="basicDialogRef?.closeDialog">返回</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, type ElForm } from 'element-plus';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useEmergencyHook } from '../src/hoos';
  import { useEmergencyPlanHook } from './src/hook';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { PlanApprovalListQuery, PlanApprovalListResponse } from '@/types/emergency-plan';
  import { getEmergencyApprovalList, submitApproval } from '@/api/emergency-plan';
  import {
    EMERGENCY_PLAN_APPROVAL_SEARCH_CONFIG,
    EMERGENCY_PLAN_APPROVAL_TABLE_OPTIONS,
    EMERGENCY_PLAN_APPROVAL_TABLE_COLUMNS,
  } from './src/config';
  import { APPROVAL_STATUS } from './src/constant';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';

  const { tableConfig, pagination } = useTableConfig(
    EMERGENCY_PLAN_APPROVAL_TABLE_COLUMNS,
    EMERGENCY_PLAN_APPROVAL_TABLE_OPTIONS,
  );
  const { getEmergencyEventDict, getEmergencyEvent } = useEmergencyHook();
  const { getPlanTypeDict, getPlanType, getEmergencyPlanApproStatusLabel } = useEmergencyPlanHook();
  let planApprovalListQuery: QueryPageRequest<PlanApprovalListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const tableData = ref<PlanApprovalListResponse[]>([]);
  const searchData = reactive({
    approvalStatus: null,
  });
  const formData = reactive({
    approvalStatus: APPROVAL_STATUS.APPROVED,
    rejectReason: '',
  });
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const formRef = ref<InstanceType<typeof ElForm>>();
  const handleSearch = () => {
    planApprovalListQuery.queryParam = {};
    if (searchData.approvalStatus) {
      planApprovalListQuery.queryParam.approvalStatus = searchData.approvalStatus;
    }
    getTableData();
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getEmergencyApprovalList(planApprovalListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    planApprovalListQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    planApprovalListQuery.pageNumber = value;
    getTableData();
  };
  const handlePreviewScript = (appendix: string) => {
    const file = JSON.parse(appendix)[0];
    previewOnlineRef.value?.open(file.fileUrl, file.fileType as keyof typeof FILE_TYPE_ICON);
  };
  const currentId = ref<number>();
  const currentOrder = ref<number>();
  const handleApproval = (id: number, approvalOrder: number) => {
    currentId.value = id;
    currentOrder.value = approvalOrder;
    basicDialogRef.value?.openDialog();
  };
  const closeDialog = () => {
    formRef.value?.resetFields();
    basicDialogRef.value?.closeDialog();
  };
  const handleApprovalSubmit = () => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        if (!currentId.value || !currentOrder.value) return;
        await submitApproval({
          planId: currentId.value,
          approvalOrder: currentOrder.value,
          approvalStatus: formData.approvalStatus,
          returnReason: formData.rejectReason,
        });
        ElMessage.success('审批成功');
        basicDialogRef.value?.closeDialog();
        getTableData();
      }
    });
  };
  onMounted(() => {
    getPlanTypeDict();
    getEmergencyEventDict();
    getTableData();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  .appendix {
    cursor: pointer;
    color: $primary-color;
  }
</style>
