<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.keyProcessUnit"
              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-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.inherentRiskLevel"
              clearable
              placeholder="固有风险等级"
              style="width: 170px"
            >
              <el-option :value="1" label="B" />
              <el-option :value="2" label="C" />
            </el-select>
          </el-form-item>
          <el-form-item label="控制风险等级">
            <el-select
              v-model="queryParams.queryParam.controlRiskLevel"
              clearable
              placeholder="控制风险等级"
              style="width: 170px"
            >
              <el-option value="D" label="D" />
            </el-select>
          </el-form-item>
        </el-form>

        <div>
          <el-button type="primary" @click="$router.push({ name: 'hazardManageAdd' })">添加 </el-button>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handleRestParams">重置</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="hazardCode" width="180" />
          <el-table-column label="关键过程/作业单元" prop="keyProcessUnit" width="180" />
          <el-table-column label="危险源名称" prop="hazardName" width="180" />
          <el-table-column label="是否重大危险" prop="isMajorHazard" width="180" />
          <el-table-column label="危险源来源" prop="hazardSource" width="180" />
          <el-table-column label="涉及型号" prop="involvedDepartment" width="180" />
          <el-table-column label="危险源管理的主责单位/部门" prop="riskManagementDept" width="240" />
          <el-table-column label="状态" prop="statusName" width="80" />
          <el-table-column label="变更原因" prop="changeReason" width="120" />
          <el-table-column fixed="right" min-width="240" label="操作">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="$router.push({ name: 'hazardManageEdit', query: { id: scope.row.id } })"
                >编辑</el-button
              >

              <el-button type="primary" link @click="handleConfirmDeleteRow(scope)">删除</el-button>
              <el-button
                type="primary"
                link
                @click="$router.push({ name: 'hazardManageView', query: { id: scope.row.id } })"
                >查看</el-button
              >
              <el-button
                type="primary"
                link
                @click="$router.push({ name: 'hazardManageCreatePlan', 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>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    safetyHazardInventoryQueryPage,
    safetyHazardInventoryDelete,
    safetyRiskListApprove,
  } 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';

  const router = useRouter();
  const { id } = useUserInfoHook();
  const firstLevelDepts = ref<any[]>([]);
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      keyProcessUnit: '',
      status: '',
      inherentRiskLevel: '',
      controlRiskLevel: '',
      riskManagementDept: '',
      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 handleChangeDept = () => {
    const deptInfo = cascaderRef.value?.getCheckedNodes();
    if (deptInfo?.[0]) {
      queryParams.queryParam.responsibleDepartment = deptInfo[0].label;
    }
  };

  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) => {
    safetyHazardInventoryDelete(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };

  const queryTableList = () => {
    safetyHazardInventoryQueryPage({
      ...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,
        keyProcessUnit: '',
        status: '',
        inherentRiskLevel: '',
        controlRiskLevel: '',
        riskManagementDept: '',
        userId: id,
        responsibleDepartmentId: [],
      },
    });
    queryTableList();
  };

  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(.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>
