<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> 危险作业管理审核 </div>
    </header>

    <main class="safety-platform-container__main">
      <div class="search-form">
        <el-form :inline="true">
          <el-form-item label="申请单位名称">
            <el-input
              v-model="queryParams.queryParam.applicationUnitName"
              placeholder="申请单位名称"
              style="width: 170px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.queryParam.status" clearable placeholder="状态" style="width: 170px">
              <el-option value="" label="全部" />
              <el-option :value="1" label="待提交" />
              <el-option :value="2" label="待审批" />
              <el-option :value="3" label="已完成" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请人名称">
            <el-input v-model="queryParams.queryParam.applicantName" placeholder="搜索申请人" style="width: 170px" />
          </el-form-item>
          <el-form-item label="申请部门">
            <el-cascader
              v-model="queryParams.queryParam.applicationDepartmentId"
              style="width: 170px"
              ref="cascaderRef"
              :options="firstLevelDepts"
              :props="cascaderProp"
              :show-all-levels="false"
              placeholder="部门名称"
              filterable
              @change="handleChangeDept"
            />
          </el-form-item>
        </el-form>

        <div>
          <!-- <el-button type="primary" @click="$router.push({ name: 'hazardApprovalManageAdd' })">添加 </el-button> -->
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handleRestParams">重置</el-button>
          <el-button @click="handleDownload">导出</el-button>
        </div>
      </div>

      <div class="table-content">
        <el-table :data="tableData.data">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column label="申请单号" width="150" prop="code" />
          <el-table-column label="申请单位" width="180" prop="applicationUnitName" />
          <el-table-column label="申请人" width="180" prop="applicantName" />
          <el-table-column label="申请部门" width="180" prop="applicationDepartment" />
          <el-table-column label="申请人电话" width="180" prop="applicantPhone" />
          <el-table-column label="作业类别" width="180" prop="hazardOperationType" />
          <el-table-column label="申请状态" width="120" prop="statusName" />
          <el-table-column label="申请时间" width="180" prop="createdAt" />
          <!-- <el-table-column label="备注" width="180" prop="remark" /> -->
          <el-table-column label="当前节点名称" width="180" prop="nodeDescription" />
          <el-table-column fixed="right" min-width="140" label="操作">
            <template #default="scope">
              <!-- <el-button
                type="primary"
                link
                @click="$router.push({ name: 'constructionSafetyManageEdit', query: { id: scope.row.id } })"
                >编辑</el-button
              > -->
              <el-button
                type="primary"
                link
                @click="$router.push({ name: 'hazardApprovalManageView', query: { id: scope.row.id } })"
                >查看</el-button
              >

              <!-- <el-button type="primary" link @click="handleConfirmDeleteRow(scope)">删除</el-button> -->

              <el-button type="primary" link @click="openApproveDialog(scope)" v-if="scope.row.status === 2">审核</el-button>
              <!-- <el-button
                type="primary"
                link
                @click="$router.push({ name: 'constructionSafetyManageMonitor', query: { id: scope.row.id } })"
                >视频监控</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container" v-if="tableData.total > 0">
        <el-pagination
          background
          :current-page="queryParams.pageNumber"
          :page-size="queryParams.pageSize"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>
  </div>
  <!-- 审核弹窗 -->
  <BasicDialog v-model="showApproveDialog" 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="2">通过</el-radio>
            <el-radio :value="3">退回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.approvalStatus === 3"
          label="退回原因："
          prop="returnReason"
          :rules="[{ required: true, message: '请输入退回原因' }]"
        >
          <el-input v-model="formData.returnReason" placeholder="请输入退回原因" type="textarea" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleApproveSubmit">提交</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </template>
  </BasicDialog>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    dangerWorkQueryDangerWorkApprovalPage,
    dangerWorkSaveApproval,
    exportHazardWorkApprovalList,
  } from '@/api/production-safety/responsibility-implementation';
  import { omit } from 'lodash-es';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { downloadByData } from '@/utils/file/download';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import { getAllDepartments } from '@/api/auth/dept';
  import { APPROVAL_STATUS } from '@/views/emergency/emergency-plan/src/constant';
  import { type ElForm } from 'element-plus';

  const firstLevelDepts = ref<any[]>([]);

  const showApproveDialog = ref(false);
  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const formRef = ref<InstanceType<typeof ElForm>>();
  const formData = reactive({
    approvalStatus: APPROVAL_STATUS.APPROVED,
    returnReason: '',
  });
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      status: '',
      applicationUnitName: '',
      applicantName: '',
      applicationDepartmentId: [],
    },
  });
  const currentRow = ref<any>();
  const cascaderRef = ref();
  const tableData = reactive({
    data: [],
    total: 0,
  });

  const handleSizeChange = (value) => {};

  const handleCurrentChange = (value) => {
    queryParams.pageNumber = value;
    queryTableList();
  };

  const closeDialog = () => {
    formRef.value?.resetFields();
    showApproveDialog.value = false;
    currentRow.value = null;
  };

  function openApproveDialog(scope) {
    currentRow.value = scope.row;
    showApproveDialog.value = true;
  }

  function handleApproveSubmit() {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        try {
          await dangerWorkSaveApproval({
            approvalOrder: currentRow.value.approvalOrder,
            approvalStatus: formData.approvalStatus,
            id: currentRow.value.id,
            returnReason: formData.returnReason,
          });
          ElMessage.success('审核成功');
          showApproveDialog.value = false;
          queryTableList();
        } catch (e) {
          console.error('审核失败:', e);
          ElMessage.error('审核失败，请重试');
        }
      } else {
      }
    });
  }

  const getDeptData = () => {
    getAllDepartments().then((res) => {
      firstLevelDepts.value = formatDeptTree(res);
    });
  };
  const handleChangeDept = () => {
    const deptInfo = cascaderRef.value?.getCheckedNodes();
    if (deptInfo?.[0]) {
      queryParams.queryParam.department = deptInfo[0].label;
      queryParams.queryParam.departmentId = deptInfo[0].pathValues;
    }
  };

  const queryTableList = () => {
    dangerWorkQueryDangerWorkApprovalPage({
      ...queryParams,
      queryParam: {
        ...omit(queryParams.queryParam, 'responsibleDepartmentId'),
      },
    }).then((res) => {
      tableData.data = res.records;
      tableData.total = res.totalRow;
    });
  };
  const handleRestParams = () => {
    Object.assign(queryParams, {
      pageNumber: 1,
      pageSize: 10,
      queryParam: {
        ...queryParams.queryParam,
        status: '',
        applicationUnitName: '',
        applicantName: '',
        applicationDepartmentId: [],
      },
    });
    queryTableList();
  };

  const handleDownload = async () => {
    try {
      const response = await exportHazardWorkApprovalList(queryParams.queryParam);
      if (response) {
        const fileName = `危险作业管理审核_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出院级文件失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  onMounted(async () => {
    await getDeptData();
    queryTableList();
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;

  :deep(.el-tabs__header) {
    margin: 0;
  }
  :deep(.el-tabs__item) {
    font-size: 14px !important;
  }
  :deep(.flexContent) {
    display: flex;
  }
  :deep(.breadcrumb .title) {
    margin-left: 0;
  }

  :deep(main) {
    display: flex;
    flex-direction: column;
  }
  .search-form {
    min-width: 800px;
    display: flex;

    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    :deep(.el-form) {
      flex: 1;
      display: flex;
      row-gap: 15px;
      flex-wrap: wrap;
    }
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }

  .button-content {
    margin-bottom: 20px;
  }
  .table-content {
    flex: 1;
    overflow: hidden;
    overflow-y: auto;
  }
  .page-content {
    display: flex;
    justify-content: flex-end;
  }
</style>
