<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.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="B" />
              <el-option :value="2" label="C" />
            </el-select>
          </el-form-item>
        </el-form>

        <div>
          <el-button type="primary" @click="$router.push({ name: 'riskManageAdd' })">添加 </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="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="变更原因" prop="changeReason" width="170" />
          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column fixed="right" min-width="240" label="操作">
            <template #default="scope">
              <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>查看</el-button>
              <el-button
                type="primary"
                link
                @click="$router.push({ name: 'riskManageChange', query: { id: scope.row.id } })"
                >变更</el-button
              >
              <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="handleApprove(scope, 0)">撤回</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 dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    safetyRiskListQueryPage,
    safetyRiskListDelete,
    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: {
      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 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) => {
    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();
  };

  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>
