<template>
  <div class="safety-platform-container">
    <div class="breadcrumb-title back"> <BreadcrumbBack /> {{ $route.meta.title }} </div>
    <header class="safety-platform-container__header">
      <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"
              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>
            <el-button @click="handleExport">导出 </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" width="200"/>
          <el-table-column label="分组名称" prop="userGroupName" width="200"/>
          <el-table-column label="责任人姓名" prop="responsiblePersonName" width="200"/>
          <el-table-column label="责任人所在部门" prop="deptName" width="200" />
          <el-table-column label="是否并签" prop="signConfigName" width="200"/>
          <el-table-column label="责任书文档" width="200">
            <template #default="scope">
                <div class="file-list" v-if="scope.row.attachment.length > 0">
                    <div v-for="file in scope.row.attachment" :key="file.fileId" class="file-item">

                        <div class="file-info" @click="previewOnline(file.fileUrl, file.fileType as keyof typeof FILE_TYPE_ICON)">
                            <img :src="FILE_TYPE_ICON[file.fileType as keyof typeof FILE_TYPE_ICON]" />
                            <span class="file-name file-container--div__name">{{ file.fileName }}</span>
                        </div>
                        <img
                            class="file-container--div__download"
                            :src="DownloadIcon"
                            @click="downloadFile(file.fileUrl, file.fileName)"
                        />
                    </div>
                </div>
            </template>
          </el-table-column>
          <el-table-column label="计划完成时间" width="160" prop="planEndTime" />
          <el-table-column label="当前节点" prop="nodeDescription" width="200"/>
          <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 title="确定要作废吗?" v-if="scope.row.status !== 6">
                <template #reference>
                  <el-button type="primary" link @click="handleScrap(scope)">作废</el-button>
                </template>
              </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
          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>
  <PreviewOnline ref="previewOnlineRef" />
  </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 DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { downloadByData } from '@/utils/file/download';
  import { unformatAttachment } from '@/components/UploadFiles/utils';
  import { downloadFile } from '@/views/disaster/utils';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  const router = useRouter();
  const route = useRoute();
  const activeTab = ref<any>(route.query.status ? Number(route.query.status) : '');
  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 = (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) => {
    safetyResponsibilityAdminScrap(scope.row.id).then(() => {
      ElMessage.success('作废成功');
      queryTableList();
    });
  };

//    const handleExport = async () => {
//     try {
//       const response = await safetyResponsibilityAdminExportIssuedObject(queryParams.queryParam);
//       if (response) {
//         const fileName = `下发对象数据_${new Date().toISOString().split('T')[0]}.xlsx`;
//         downloadByData(response, fileName);
//         ElMessage.success('导出成功');
//       }
//     } catch (e:any) {
//       console.error('导出下发对象失败:', e);
//       ElMessage.error('导出失败，请重试');
//     }
//   };

  // 预览
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const previewOnline = (url: string | undefined, type: keyof typeof FILE_TYPE_ICON) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  const handleExport = async () => {
    await safetyResponsibilityAdminExportIssuedObject({
      ...omit(queryParams.queryParam, 'date'),
      adminId: Number(queryParams.queryParam.adminId),
      startTime: queryParams.queryParam.date?.[0],
      endTime: queryParams.queryParam.date?.[1]
    }).then((res) => {
      if (!res) {
        throw new Error('下载文件失败');
      }
      downloadByData(res, `下发对象数据_${new Date().toISOString().split('T')[0]}.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],
        endTime: queryParams.queryParam.date?.[1]
      },
    }).then((res) => {

      res.pages.records.forEach((item:any)=>{
        item.attachment = JSON.parse(item.attachment) || []
      })
      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(tableData.data)
    });
  };
  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,
  //   },
  // );

  watch(
    () => activeTab.value,
    (a) => {
      queryParams.queryParam.status = a ? Number(a) : '';
      queryTableList();
    },
    {
      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: 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;
  }
  .back {
    display: flex;
    align-items: center;
    gap: 16px;
    background-color: white;
    padding: 16px 22px;
    font-size: 20px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }
  .file-item {
    display: flex;
    align-items: center;
    gap: 10px;
    .file-info{
        display: flex;
        align-items: center;
        gap: 10px;
        img {
            width: 28px;
            cursor: pointer;
        }
        .file-name {
            min-width: 0;
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: pointer;
        }
    }
    .file-container--div__download {
        width: 28px;
        cursor: pointer;
    }
  }
</style>
