<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">
        <BreadcrumbBack />
        {{ detailData?.responsibilityName }}
      </div>
      <div class="detail-content">
        <span>类别名称：{{ detailData?.safetyAreaTypeName }} </span>
        <span>创建人：{{ detailData?.createdByName }} </span>
        <span>创建时间：{{ detailData?.createdAt }} </span>
      </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部" name="" />
        <el-tab-pane label="待反馈材料" :name="2" />
        <el-tab-pane label="待审核" :name="3" />
        <el-tab-pane label="已完成" :name="4" />
        <el-tab-pane label="已作废" :name="5" />
      </el-tabs>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-form">
        <el-form :inline="true">
          <!-- <el-form-item label="状态" v-if="activeTab">
            <el-select v-model="queryParams.queryParam.status" clearable placeholder="状态" style="width: 170px">
              <el-option :value="1" label="未下发" />
              <el-option :value="2" label="待签署" />
              <el-option :value="3" label="待反馈材料" />
              <el-option :value="4" label="待审核" />
              <el-option :value="5" label="已完成" />
              <el-option :value="6" label="已作废" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="通知区域">
            <el-select v-model="queryParams.queryParam.safetyAreaId" clearable placeholder="选择通知区域" style="width: 170px">
                <el-option v-for="group in areaCheckListQueryList" :key="group.id" :label="group.nameFunction" :value="group.id" />
            </el-select>
          </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"
            />
          </el-form-item>
            <el-form-item label="关键词">
            <el-input v-model="queryParams.queryParam.keyWord" placeholder="关键词内容" style="width: 170px"></el-input>
          </el-form-item>
        </el-form>

        <div>
          <!-- <el-button type="primary" @click="handleExport">导出 </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 label="责任通知名称" prop="responsibilityName" width="180" />
          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column label="类型" prop="safetyAreaTypeName" />

          <el-table-column label="通知区域" prop="safetyAreaName" />
          <el-table-column label="安全责任人" prop="responsiblePersonName" />
          <el-table-column label="计划完成时间" prop="planEndTime" />
          <el-table-column fixed="right" width="200" label="操作">
            <template #default="scope">
              <el-popconfirm
                v-if="scope.row.status === 1 || scope.row.status === 6"
                title="确定要删除吗?"
                @confirm="handleConfirmDeleteRow(scope)"
              >
                <template #reference>
                  <el-button type="primary" link>删除</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm v-if="scope.row.status === 6">
                <el-button type="primary" link @click="handleScrap(scope)">作废</el-button>
              </el-popconfirm>
              <el-button
                v-if="scope.row.status === 3"
                type="primary"
                link
                @click="
                  $router.push({
                    name: 'responsibilityNoticeReview:admin',
                    query: { id: scope.row.id },
                  })
                "
                >审核
              </el-button>
              <el-button type="primary" link @click="handleDownloadLink(scope)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper,sizes, total"
          :current-page="queryParams.pageNumber"
          :page-size="queryParams.pageSize"
          :total="tableData.total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, reactive, watch } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { omit } from 'lodash-es';

  import { queryUserGroupPage } from '@/api/system/person-group';
  import {
    safetyNoticeAdminQueryIssuedObject,
    safetyNoticeAdminExportIssuedObject,
    safetyResponsibilityAdminDeleteIssuedObject,
    safetyNoticeAdminScrap,
    areaCheckListQueryPage,
  } from '@/api/production-safety/responsibility-implementation';
  import { downloadByData } from '@/utils/file/download';
  import { unformatAttachment } from '@/components/UploadFiles/utils';
  import { downloadFile } from '@/views/disaster/utils';

  const router = useRouter();
  const route = useRoute();
  const activeTab = ref<any>('');
  const groupList = ref<any>([]);

  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      adminId: route.query.id,
      status: '',
      date: '',
      type: route.query.type || '',
      safetyAreaId: '',
      keyWord: '',
    },
  });

  const queryParamsTow = reactive<any>({
    pageNumber: 1,
    pageSize: 9999,
    queryParam: {},
  });

  const detailData = reactive({
    createdAt: '',
    createdByName: '',
    safetyAreaTypeName: '',
    responsibilityName: '',
  });

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

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

  const handleQueryUserGroupPage = () => {
    queryUserGroupPage({
      pageNumber: 1,
      pageSize: 500,
    }).then((res) => {
      groupList.value = res.records;
    });
  };

  const handleSizeChange = (value) => {
    queryParams.pageSize = value;
    queryTableList();
  };
  const handleCurrentChange = (value) => {
    queryParams.pageNumber = value;
    queryTableList();
  };
  const handleDownloadLink = (scope) => {
    const attachment = unformatAttachment(scope.row.attachment);
    attachment?.forEach((item: any) => {
      downloadFile(item.fileUrl, item.fileName);
    });
  };

  const handleScrap = (scope) => {
    safetyNoticeAdminScrap(scope.row.id).then(() => {
      ElMessage.success('作废成功');
      queryTableList();
    });
  };

  const handleExport = () => {
    safetyNoticeAdminExportIssuedObject({
      ...queryParams,
      queryParam: {
        ...omit(queryParams.queryParam, 'date'),
        adminId: Number(queryParams.queryParam.adminId),
        status: queryParams.queryParam.status,
        startTime: queryParams.queryParam.date?.[0]
          ? dayjs(queryParams.queryParam.date?.[0]).format('YYYY-MM-DD')
          : undefined,
        endTime: queryParams.queryParam.date?.[1]
          ? dayjs(queryParams.queryParam.date?.[1]).format('YYYY-MM-DD')
          : undefined,
      },
    }).then((res) => {
      if (!res) {
        throw new Error('下载文件失败');
      }
      downloadByData(res, `${Date.now()}.xlsx`);
      ElMessage.success('导出文件成功');
    });
  };
  const handleConfirmDeleteRow = (scope) => {
    safetyResponsibilityAdminDeleteIssuedObject(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };
  const queryTableList = () => {
    safetyNoticeAdminQueryIssuedObject({
      ...queryParams,
      queryParam: {
        ...omit(queryParams.queryParam, 'date'),
        adminId: queryParams.queryParam.adminId,
        startTime: queryParams.queryParam.date?.[0]
          ? dayjs(queryParams.queryParam.date?.[0]).format('YYYY-MM-DD')
          : undefined,
        endTime: queryParams.queryParam.date?.[1]
          ? dayjs(queryParams.queryParam.date?.[1]).format('YYYY-MM-DD')
          : undefined,
      },
    }).then((res) => {
      tableData.data = res.pages.records;
      tableData.total = res.pages.totalRow;
      Object.keys(detailData).forEach((item) => {
        if (item in res) {
          detailData[item] = res[item];
        }
      });
      console.log(detailData);
    });
  };
  const handleRestParams = () => {
    Object.assign(queryParams, {
      pageNumber: 1,
      pageSize: 10,
      queryParam: {
        ...queryParams.queryParam,
        status: '',
        date: '',
        userGroupId: '',
        safetyAreaId: '',
        keyWord: '',
      },
    });
    queryTableList();
  };

  const areaCheckListPost = () => {
    areaCheckListQueryPage(queryParamsTow).then((res) => {
      areaCheckListQueryList.value = res.records;
    });
  };

  watch(
    () => activeTab.value,
    (a) => {
      queryParams.queryParam.status = a ? Number(a) : '';
      queryTableList();
      //
    },
  );

  onMounted(async () => {
    activeTab.value = route.query.status;
    Object.assign(queryParams, {
      queryParam: {
        ...queryParams.queryParam,
        status: Number(activeTab.value),
      },
    });
    await handleQueryUserGroupPage();

    queryTableList();

    areaCheckListPost();

  });
</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 *;

  .safety-platform-container__header {
    padding-bottom: 0 !important;
  }

  :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;
  }

  .detail-content {
    display: flex;
    gap: 30px;
    margin: 10px 0;
    font-size: 14px;
  }

  .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;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
</style>
