<template>
  <div class="safety-platform-container">
    <div class="flex"> <BreadcrumbBack /><span class="breadcrumb-title">创建计划和方案</span> </div>
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> {{ detailData?.hazardName }} </div>
      <div class="detail-content">
        <span class="m-r">编号：{{ detailData?.hazardCode }} </span>
        <span class="m-r">创建人：{{ detailData?.createdName }} </span>
        <span class="m-r">创建时间：{{ detailData?.createdAt }} </span>
      </div>
      <el-tabs v-model="activeTab" @tab-click="clickTab">
        <el-tab-pane label="全部" name="" />
        <el-tab-pane label="待开始" :name="1" />
        <el-tab-pane label="进行中" :name="2" />
        <el-tab-pane label="已完成" :name="3" />
      </el-tabs>
    </header>
    <main class="safety-platform-container__main">
      <div style="margin-bottom: 20px">
        <el-button type="primary" @click="handleAddPlan">添加 </el-button>
      </div>
      <div class="search-form">
        <el-form :inline="true">
          <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-cascader
              v-model="queryParams.queryParam.execDepartment"
              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-date-picker
              v-model="queryParams.queryParam.date"
              clearable
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 230px"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form>

        <div>
          <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="planName" width="180">
            <template #default="scope">
              <el-link type="primary" underline @click="handleShowPlan(scope)">
                {{ scope.row.planName }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column label="执行部门" prop="execDepartment" width="180" />
          <el-table-column label="执行人" prop="executorName" width="130" />
          <el-table-column label="计划/方案描述" prop="planContent" width="180" />
          <el-table-column label="计划开始时间" prop="planStartDate" width="220" />
          <el-table-column label="计划结束时间" prop="planEndDate" width="220" />

          <el-table-column fixed="right" min-width="240" label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="handleEditPlan(scope)"> 编辑 </el-button>

              <el-button type="primary" link @click="handleConfirmDeleteRow(scope)">删除</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>
  <PlansAndProgramsDialog
    v-if="planDialogOpen"
    v-model.visible="planDialogOpen"
    :dialogInfo="dialogInfo"
    @submit="handlePlanSubmit"
  />
</template>
<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import {
    safetyHazardInventoryQueryPlanAndSchemePage,
    safetyHazardInventoryDeletePlan,
    safetyHazardInventoryQueryPlanDetail,
    safetyHazardInventorySavePlan,
    safetyHazardInventoryUpdatePlan,
  } 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 PlansAndProgramsDialog from './components/PlansAndProgramsDialog.vue';
  import { exec } from 'child_process';

  const router = useRouter();
  const route = useRoute();
  const { id } = useUserInfoHook();
  const firstLevelDepts = ref<any[]>([]);
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };
  const activeTab = ref('');
  const planDialogOpen = ref(false);
  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      status: '',
      date: null,
      execDepartment: '',
    },
  });
  const cascaderRef = ref();
  const detailData = reactive({
    createdAt: '',
    createdName: '',
    hazardName: '',
    hazardCode: '',
  });
  const tableData = reactive({
    data: [],
    total: 0,
  });

  const dialogInfo = reactive<any>({
    title: '新增风险源计划与方案',
    currentRow: null,
    type: 'add',
  });

  const handleAddPlan = () => {
    planDialogOpen.value = true;
    dialogInfo.title = '新增风险源计划与方案';
    dialogInfo.type = 'add';
  };

  const handleEditPlan = async (scope: any) => {
    dialogInfo.currentRow = scope.row;
    dialogInfo.title = '编辑风险源计划与方案';
    dialogInfo.type = 'edit';
    planDialogOpen.value = true;
  };

  const handleShowPlan = async (scope: any) => {
    dialogInfo.currentRow = scope.row;
    dialogInfo.title = '查看风险源计划与方案';
    dialogInfo.type = 'view';
    planDialogOpen.value = true;
  };

  const handleClosePlanDialog = () => {
    planDialogOpen.value = false;
    dialogInfo.currentRow = null;
    dialogInfo.type = '';
    dialogInfo.title = '';
  };

  const handlePlanSubmit = (formData, loading) => {
    const req = dialogInfo.type === 'edit' ? safetyHazardInventoryUpdatePlan : safetyHazardInventorySavePlan;
    loading.value = true;
    req({
      ...formData,
      id: dialogInfo.type === 'edit' ? dialogInfo.currentRow.id : undefined,
      hazardListId: route.query.id,
      execDepartmentId: formData.execDepartmentId.join(','),
      executor: formData.executor.join(','),
    })
      .then(() => {
        handleClosePlanDialog();
        queryTableList();
        ElMessage.success('操作成功!');
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const clickTab = (tab) => {
    queryParams.queryParam.status = activeTab.value;
    queryParams.pageNumber = 1;
    queryTableList();
  };
  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.execDepartment = deptInfo[0].value; //id
    }
  };

  const handleConfirmDeleteRow = (scope) => {
    safetyHazardInventoryDeletePlan(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };

  const queryTableList = () => {
    safetyHazardInventoryQueryPlanAndSchemePage({
      ...queryParams,
      queryParam: {
        ...omit(queryParams.queryParam, ['date', 'responsibleDepartmentId']),
        hazardListId: route.query.id,

        startTime: queryParams.queryParam.date ? queryParams.queryParam.date[0] : undefined,
        endTime: queryParams.queryParam.date ? queryParams.queryParam.date[1] : undefined,
      },
    }).then((res) => {
      tableData.data = res.page.records;
      tableData.total = res.totalRow;
      Object.assign(detailData, res);
    });
  };
  const handleRestParams = () => {
    Object.assign(queryParams, {
      pageNumber: 1,
      pageSize: 10,
      queryParam: {
        ...queryParams.queryParam,
        status: '',
        date: null,
        execDepartment: '',
      },
    });
    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;
  }
  .flex {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px 22px;
    flex-shrink: 0;
    background-color: white;
  }
  .m-r {
    margin-right: 10px;
  }
</style>
