<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>
            <el-button class="search-table-container--button" type="primary" :icon="Plus" @click="$router.push({ name: 'riskManageAdd' })">添加 </el-button>
            <el-button plain class="search-table-container--button" @click="handleImport">
              导入
            </el-button>
        </div>
      <div class="search-form">
        <el-form :inline="true">
          <el-form-item label="搜索">
            <el-input
              v-model="queryParams.queryParam.mergeFiled"
              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="1" label="正常" />
              <el-option :value="2" label="待确认" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门名称">
            <el-cascader
              v-model="queryParams.queryParam.responsibleDepartmentId"
              style="width: 170px"
              ref="cascaderRef"
              :options="firstLevelDepts"
              :props="cascaderProp"
              :show-all-levels="false"
              placeholder="部门名称"
              filterable
              @change="handleChangeDept"
            />
          </el-form-item>
          <el-form-item label="风险类型">
            <el-select
              v-model="queryParams.queryParam.riskCategory"
              clearable
              placeholder="风险类型"
              style="width: 170px"
            >
              <el-option :value="1" label="III级危险点" />
              <el-option :value="2" label="II级危险点" />
              <el-option :value="3" label="I级危险点" />
              <el-option :value="4" label="UPS" />
              <el-option :value="5" label="电力设施（强电）" />
              <el-option :value="6" label="高低温气体液体、高压气体" />
              <el-option :value="7" label="试验设施设备" />
              <el-option :value="8" label="特种设备" />
              <el-option :value="9" label="危化品、易燃易爆固液气体" />
              <el-option :value="10" label="有限空间" />
            </el-select>
          </el-form-item>
          <el-form-item label="风险等级">
            <el-select v-model="queryParams.queryParam.riskLevel" clearable placeholder="风险等级" style="width: 170px">
              <el-option :value="1" label="高" />
              <el-option :value="2" label="中" />
              <el-option :value="3" label="低" />
            </el-select>
          </el-form-item>
          <el-form-item label="责任人" prop="roomSafetyResponsible">
          <el-select
            v-model="queryParams.queryParam.roomSafetyResponsible"
            placeholder="责任人"
            style="width: 330px"
            filterable
          >
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        </el-form>

        <div>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handleRestParams">重置</el-button>
          <el-button plain  @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="楼号/区域" prop="buildingArea" width="180" />
          <el-table-column label="楼宇名称" prop="buildingName" width="180" />
          <el-table-column label="楼层/位置" prop="floorLocation" width="180" />
          <el-table-column label="房间号(名称)" prop="roomName" width="180" />
          <el-table-column label="安全责任人" prop="roomSafetyResponsibleName" width="180" />
          <el-table-column label="是否存在风险点" prop="hasRiskPointName" width="180" />
          <el-table-column label="风险点类别" prop="riskCategoryName" width="180" />
          <el-table-column label="变更原因" show-overflow-tooltip prop="changeReason" width="170" />
          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column fixed="right" min-width="240" label="操作">
            <template #default="scope">
                <div v-if="(id === scope.row.createdBy && id !== scope.row.roomSafetyResponsible) && scope.row.status === 1">
                    <el-button
                        type="primary"
                        link
                        @click="$router.push({ name: 'riskManageEdit', query: { id: scope.row.id } })"
                        >编辑</el-button>
                    <el-button type="primary" link @click="handleConfirmDeleteRow(scope)">删除</el-button>
                    <el-button type="primary" link @click="handleView(scope.row.id)">查看</el-button>
                </div>
                <div v-if="(id === scope.row.roomSafetyResponsible && id !==scope.row.createdBy) && scope.row.status === 1">
                    <el-button
                        type="primary"
                        link
                        @click="$router.push({ name: 'riskManageChange', query: { id: scope.row.id } })"
                        >变更</el-button>
                    <el-button type="primary" link @click="handleView(scope.row.id)">查看</el-button>
                </div>
                <div v-if="(id===scope.row.roomSafetyResponsible && id === scope.row.createdBy) && scope.row.status === 1">
                    <el-button
                        type="primary"
                        link
                        @click="$router.push({ name: 'riskManageEdit', query: { id: scope.row.id } })"
                        >编辑</el-button>
                    <el-button type="primary" link @click="handleConfirmDeleteRow(scope)">删除</el-button>
                    <el-button type="primary" link @click="handleView(scope.row.id)">查看</el-button>
                    <el-button
                        type="primary"
                        link
                        @click="$router.push({ name: 'riskManageChange', query: { id: scope.row.id } })"
                        >变更</el-button>
                </div>
                <div v-if="(id===scope.row.applyBy)&&scope.row.status === 2">
                    <el-button type="primary" link @click="handleApprove(scope, 0)">撤回</el-button>
                    <el-button type="primary" link @click="handleView(scope.row.id)">查看</el-button>
                </div>
                <div v-if="(id === scope.row.roomSafetyResponsibleTodo)&& scope.row.status===2">
                    <el-button type="primary" link @click="handleApprove(scope, 1)">确认</el-button>
                    <el-button type="primary" link @click="handleApprove(scope, 0)">拒绝</el-button>
                    <el-button type="primary" link @click="handleView(scope.row.id)">查看</el-button>
                </div>
            </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>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="风险清单导入模版"
      :show-template="true"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import {
    queryAvailableUserList,
    safetyRiskListQueryPage,
    safetyRiskListDelete,
    safetyRiskListApprove,
    exportRiskList,
  } from '@/api/production-safety/responsibility-implementation';
  import { omit } from 'lodash-es';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { unformatAttachment } from '@/components/UploadFiles/utils';
  import { downloadFile } from '@/views/disaster/utils';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import { getAllDepartments } from '@/api/auth/dept';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { downloadByData } from '@/utils/file/download';

  const router = useRouter();
  const { id } = useUserInfoHook();
  const firstLevelDepts = ref<any[]>([]);
  const userOptions = ref<any[]>([]);
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      mergeFiled: '',
      status: '',
      responsibleDepartment: '',
      riskCategory: '',
      riskLevel: '',
      userId: id,
      responsibleDepartmentId: [],
    },
  });
  const cascaderRef = ref();

  const tableData = reactive({
    data: [],
    total: 0,
  });

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

  const getDeptData = () => {
    getAllDepartments().then((res) => {
      firstLevelDepts.value = formatDeptTree(res);
    });
  };

  const handleQueryAvailableUserList = (deptName, realname = '') => {
    queryAvailableUserList({
      pageNumber: 1,
      pageSize: 200,
      queryParam: {
        deptName,
        realname,
      },
    }).then((res: any) => {
      userOptions.value = (res.records || []).map((u: any) => ({
        value: u.userId || u.id,
        label: u.realname,
      }));
    });
  };
  const handleChangeDept = () => {
    const deptInfo = cascaderRef.value?.getCheckedNodes();
    if (deptInfo?.[0]) {
      queryParams.queryParam.responsibleDepartment = deptInfo[0].label;
      handleQueryAvailableUserList(deptInfo[0].label, 'responsibleDepartment');
    }
  };
  const handleView = (id)=>{
    router.push({ name: 'riskManageView', query: { id} })
  } 
  const handleApprove = (scope, approveType) => {
    safetyRiskListApprove({
      id: scope.row.id,
      approveType,
    }).then(() => {
      ElMessage.success('操作成功!');
      queryTableList();
    });
  };

  const handleDownloadLink = (scope) => {
    const attachment = unformatAttachment(scope.row.attachment);
    attachment?.forEach((item: any) => {
      downloadFile(item.fileUrl, item.fileName);
    });
  };
  const handleConfirmDeleteRow = (scope) => {
    safetyRiskListDelete(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };

  const queryTableList = () => {
    safetyRiskListQueryPage({
      ...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,
        mergeFiled: '',
        status: '',
        responsibleDepartment: '',
        riskCategory: '',
        riskLevel: '',
        responsibleDepartmentId: [],
      },
    });
    queryTableList();
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  // /productionSafety/academyFile/import
  const importApiUrl = ref(urlJoin(urlPrefix, '/safetyRisk/list/importRiskList'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/风险清单导入模版.xlsx');

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

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

  const handleDownload = async () => {
    try {
      const response = await exportRiskList(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();
    handleQueryAvailableUserList()
    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(.el-form) {
    flex: 1;
    display: flex;
    row-gap: 15px;
    flex-wrap: wrap;
  }
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
  :deep(main) {
    display: flex;
    flex-direction: column;
  }
  .search-form {
    min-width: 800px;
    display: flex;

    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 20px;
  }

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