<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-table-container">
        <header>
          <div style="position: relative">
            <el-button type="primary" :icon="Plus" class="search-table-container--button" @click="handleCreate">
              添加
            </el-button>
            <!-- <el-button plain class="search-table-container--button" @click="handleImport">
              导入
            </el-button>
            <el-button plain class="search-table-container--button" @click="handleDownload">
              导出
            </el-button> -->
          </div>

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>单号：</span>
                <el-input
                  v-model="tableQuery.queryParam.queryKey"
                  placeholder="搜索申请单号/工号/姓名"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select
                  v-model="tableQuery.queryParam.status"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option label="待审核" :value="1" />
                  <el-option label="申请加盖公章及材料申请" :value="2" />
                  <el-option label="审核不通过" :value="3" />
                  <el-option label="已完成" :value="4" />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>所属部门：</span>
                 <el-cascader
                  v-model="tableQuery.queryParam.deptCode"
                  style="width: 170px"
                  ref="cascaderRef"
                  :options="firstLevelDepts"
                  :props="cascaderProp"
                  :show-all-levels="false"
                  placeholder="部门名称"
                  filterable
                  @change="handleChangeDept"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #status="scope">
              <span>
                {{ scope.row.workStatus === 1 ? '待审核' : scope.row.workStatus === 2 ? '申请加盖公章及材料申请' : scope.row.workStatus === 3 ? '审核不通过' : scope.row.workStatus === 4 ? '已完成' : '-' }}
              </span>
            </template>
            <template #injuryCategoryCode="scope">
              <span>
                {{ scope.row.injuryCategoryCode === '1' ? '责任事故' : scope.row.injuryCategoryCode === '2' ? '非责任事故' :  scope.row.injuryCategoryCode == '3' ? "交通事故" : '-' }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                
                <!-- 待审核：查看、审核 -->
                <template v-if="scope.row.workStatus === 1 || scope.row.workStatus === '1'">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <!-- <ActionButton text="审核" @click="handleAudit(scope.row.id,scope.row)" /> -->
                </template>
                <!-- 申请加盖公章及材料申请 -->
                <template v-else-if="scope.row.workStatus === 2 || scope.row.workStatus === '2'">
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                  <ActionButton text="确认" @click="confirmDialog = true;confirmId = scope.row.id;" />
                </template>
                <!-- 审核不通过：编辑、删除、查看 -->
                <template v-else-if="scope.row.workStatus === 3 || scope.row.workStatus === '3'">
                  <ActionButton text="编辑" @click="handleEdit(scope.row.id,scope.row)" />
                  <ActionButton
                    text="删除"
                    :popconfirm="{ title: '确定要删除该申请吗？' }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="查看" @click="handleView(scope.row.id!)" />
                </template>
                <!-- 已完成：查看 -->
                <template v-else-if="scope.row.workStatus === 4 || scope.row.workStatus === '4'">
                  <ActionButton text="查看" @click="handleView(scope.row.id!)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
      <!-- 确定弹窗 -->
      <el-dialog
        v-model="confirmDialog"
        title="用户告知内容"
        width="800px"
        destroy-on-close
        @close="confirmValue = '';confirmDialog = false"
      >
        <div class="editor-container">
          <Toolbar 
            style="border-bottom: 1px solid #dcdfe6" 
            :editor="editorRef" 
          />
          <Editor
            style="height: 400px; overflow-y: auto"
            v-model="confirmValue"
            mode="default"
            :defaultConfig="editorConfig"
            @on-created="handleEditorCreated"
          />
        </div>
        <template #footer>
          <el-button @click="confirmDialog = false">取消</el-button>
          <el-button type="danger" :loading="auditSubmitting" @click="confirmRequest">
            确定
          </el-button>
        </template>
      </el-dialog>
    </main>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="下载模板"
      :show-template="false"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref ,shallowRef ,computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, INVENTORY_TABLE_COLUMNS } from './configs/tables';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { queryInventoryManage, deleteInventory, exportInventory, auditWorkInjuryConfirm } from '@/api/inventory';
  import { downloadByData } from '@/utils/file/download';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import { getAllDepartments } from '@/api/auth/dept';
  import {
    queryWorkInjuryApplyList,
    type InventoryItem,
    type InventoryQueryParam,
  } from '@/api/production-safety/business-registration-application';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  // @ts-ignore: missing type declarations for CSS side-effect import
  import '@wangeditor/editor/dist/css/style.css';

  const router = useRouter();
  const auditSubmitting = ref(false);
  const confirmDialog = ref(false);
  const confirmValue = ref('');
  const confirmId = ref('');
  // 富文本编辑器
  const editorRef = shallowRef();
  const editorConfig = computed(() => ({
    placeholder: '请输入文档内容',
    MENU_CONF: {},
  }));
  
  const firstLevelDepts = ref<any[]>([]);
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const cascaderRef = ref();

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(INVENTORY_TABLE_COLUMNS, TABLE_OPTIONS);

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

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      queryKey: '', // 名称
      status: '', // 状态，默认启用
      ids: [], // 选择数据的ID
      deptCode: '', // 所属部门ID
    },
  });

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };


  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await queryWorkInjuryApplyList(tableQuery);
      if (res) {
        // 映射返回数据字段到表格字段
        tableData.value = res.records.map((item) => ({
          id: item.id,
          applyNo: item.applyNo, // 申请单号
          applicantCode: item.applicantCode, // 工号
          applicantName: item.applicantName, // 姓名
          departmentName: item.departmentName, // 所属部门
          injuryReason: item.injuryReason, // 受伤原因
          injuryTime: item.injuryTime, // 受伤时间
          injuryCategoryName: item.injuryCategoryName, // 工伤类别
          remark: item.remark, // 备注
          workStatus: item.workStatus, // 状态
          approvalTemplateId: item.approvalTemplateId, // 审批模板ID
          approvalOrder: item.approvalOrder, // 审批订单
          templateId: item.templateId, // 模板ID
          injuryCategoryCode: item.injuryCategoryCode, // 工伤类别编码
          rejectReason: item.rejectReason, // 拒绝原因
        }));
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取库存列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.queryKey = '';
    tableQuery.queryParam.status = ''; // 重置为默认启用状态
    tableQuery.queryParam.ids = [];
    tableQuery.queryParam.deptCode = ''; // 重置为默认启用状态
    handleSearch();
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/inventory/importInventory'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/import-inventory-template.xlsx');

  const handleImport = () => {
    batchImportVisible.value = true;
  };

  const handleUpdate = () => {
    batchImportVisible.value = false;
    getTableData();
  };

  const handleDownload = async () => {
    try {
      const exportParams = {
        queryKey: tableQuery.queryParam.queryKey || undefined,
        status: tableQuery.queryParam.status,
        ids: tableQuery.queryParam.ids.length > 0 ? tableQuery.queryParam.ids : undefined,
      };
      const response = await exportInventory(exportParams);
      if (response) {
        const fileName = `库存管理_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出库存失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  const handleCreate = () => {
    router.push({
      name: 'workInjuryApplyManageItem',
      query: {
        operate: 'inventory-create',
      },
    });
  };

  const handleEdit = (id: number,row: any) => {
    router.push({
      name: 'workInjuryApplyManageItem',
      query: {
        id,
        rejectReason:row.rejectReason ?? '',
        approvalTemplateId:row.templateId ?? '',
        approvalOrder:row.approvalOrder ?? '',
        approvalStatus:row.workStatus ?? '',
        injuryCategoryCode:row.injuryCategoryCode ?? '',
        operate: 'inventory-edit',
      },
    });
  };

  const handleAudit = (id: number,row: any) => {
    router.push({
      name: 'workInjuryApplyManageItem',
      query: {
        id,
        approvalTemplateId:row.templateId ?? '',
        approvalOrder:row.approvalOrder ?? '',
        operate: 'inventory-audit',
      },
    });
  }

  const handleDelete = async (id: number) => {
    try {
      await deleteInventory(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除库存失败:', e);
      ElMessage.error('删除失败，请重试');
    }
  };

  const handleView = (id: number) => {
    router.push({
      name: 'workInjuryApplyManageItem',
      query: {
        id,
        operate: 'inventory-view',
      },
    });
  };

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

  const handleEditorCreated = (editor: any) => {
    editorRef.value = editor;
  };

  const confirmRequest = async () => {
    auditSubmitting.value = true;
    try {
      if (!confirmValue.value) {
        ElMessage.error('请先填写用户告知内容！');
        return;
      }
      await auditWorkInjuryConfirm(Number(confirmId.value), confirmValue.value);
      ElMessage.success('操作成功');
      confirmDialog.value = false;
      confirmValue.value = '';
      getTableData();
    } catch (e) {
      console.error('操作失败:', e);
      ElMessage.error('操作失败，请重试');
    } finally {
      auditSubmitting.value = false;
    }
  };

  onMounted(() => {
    getTableData();
    getDeptData();
  });
</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 *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  .editor-container {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
</style>