<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> <BreadcrumbBack /> 查看下发对象 </div>
      <div class="detail-content">
        <span>类别名称：{{ detailData?.departmentName }} </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-tab-pane label="已作废" :name="6" />
      </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.userGroupId" placeholder="分组名称" style="width: 170px">
              <el-option v-for="group in groupList" :key="group.id" :label="group.name" :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>

        <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="departmentName" />

          <el-table-column label="分组名称" prop="userGroupName" />
          <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 === 4"
                type="primary"
                link
                @click="
                  $router.push({
                    name: 'agreeDocumentReview',
                    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
          :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, 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 {
    safetyResponsibilityAdminQueryIssuedObject,
    safetyResponsibilityAdminExportIssuedObject,
    safetyResponsibilityAdminDeleteIssuedObject,
    safetyResponsibilityAdminScrap,
  } 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: route.query.status,
      date: '',
      userGroupId: '',
    },
  });

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

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

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

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

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

  const handleExport = () => {
    safetyResponsibilityAdminExportIssuedObject({
      ...omit(queryParams.queryParam, 'date'),
      adminId: Number(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) => {
      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 = () => {
    safetyResponsibilityAdminQueryIssuedObject({
      ...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.totalPage;
      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: '',
      },
    });
    queryTableList();
  };

  watch(
    () => route.query.status,
    (a, b) => {
      activeTab.value = Number(a);
    },
    {
      immediate: true,
    },
  );

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

    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 *;
  .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: center;
    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>
