<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> 安全责任通知管理 </div>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部" name="" />
        <el-tab-pane label="公共区域" :name="1" />
        <el-tab-pane label="非公共区域" :name="2" />
      </el-tabs>
    </header>
    <main class="safety-platform-container__main">
      <div style="margin-bottom: 20px"
        ><el-button
          type="primary"
          @click="
            $router.push({
              name: 'responsibilityNoticeAdd:admin',
              query: {
                areaType: activeTab,
              },
            })
          "
          >添加
        </el-button></div
      >
      <div class="search-form">
        <el-form :inline="true">
          <el-form-item label="安全责任通知">
            <el-input
              v-model="queryParams.queryParam.responsibilityName"
              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-option :value="3" label="待审核" />
              <el-option :value="4" label="已完成" />
              <el-option :value="5" label="已作废" />
            </el-select>
          </el-form-item>
          <el-form-item label="区域类型" v-if="activeTab === ''">
            <el-select v-model="queryParams.queryParam.type" 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-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="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="safetyAreaName" width="180" /> -->
          <el-table-column label="下发数" prop="issuedQuantity" width="120" />
          <el-table-column label="反馈人数" prop="signedQuantity" width="120" />
          <el-table-column label="反馈比例" prop="signedRatio" width="120" />
          <el-table-column label="责任通知文档" prop="attachment" width="250">
            <template #default="scope">
              <!-- <div
                class="file-container--div"
                v-for="item in unformatAttachment(scope.row.attachment)"
                :key="item.fileId"
              >
                <span class="file-container--div__name">{{ item.fileName }}</span>
              </div> -->
              <div
                class="file-container--div"
                v-for="item in unformatAttachment(scope.row.attachment)"
                :key="item.fileId"
              >
                <img
                  class="file-container--div__icon"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  :src="FILE_TYPE_ICON[item.fileType]"
                />
                <span
                  class="file-container--div__name"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  >{{ item.fileName }}</span
                >
                <img
                  class="file-container--div__download"
                  :src="DownloadIcon"
                  @click="downloadFile(item.fileUrl, item.fileName)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="计划完成时间" prop="planEndTime" width="150" />
          <el-table-column fixed="right" min-width="240" label="操作">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="
                  $router.push({
                    name: 'responsibilityNoticeEdit:admin',
                    query: {
                      areaType: activeTab,
                      id: scope.row.id,
                    },
                  })
                "
                >编辑</el-button
              >
              <el-button
                link
                type="primary"
                @click="
                  $router.push({
                    name: 'responsibilityNoticeView:admin',
                    query: {
                      areaType: activeTab,
                      id: scope.row.id,
                    },
                  })
                "
                >通知对象</el-button
              >
              <el-button v-if="scope.row.status === 1" link type="primary" @click="handleSend(scope)">发送</el-button>
              <el-button
                type="primary"
                link
                v-if="scope.row.status === 4"
                @click="
                  $router.push({
                    name: 'responsibilityNoticeView:admin',
                    query: { id: scope.row.id, status: scope.row.status },
                  })
                "
                >审核</el-button
              >

              <el-popconfirm
                title="确定要删除吗?"
                v-if="scope.row.status === 1"
                @confirm="handleConfirmDeleteRow(scope)"
              >
                <template #reference>
                  <el-button type="primary" link>删除</el-button>
                </template>
              </el-popconfirm>
              <!-- <el-button type="primary" link @click="handleScrap(scope)">作废</el-button> -->
              <el-button type="primary" link @click="handleDownloadLink(scope)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container" v-if="tableData.total > 0">
        <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>
  <NotifySend
    v-if="notifySendOpen"
    :type="currentRow.type"
    v-model.visible="notifySendOpen"
    @submit="handleNotifySend"
  />
  <PreviewOnline ref="previewOnlineRef" />
</template>
<script lang="ts" setup>
  import { onMounted, ref, reactive, watch } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    safetyNoticeAdminQueryPage,
    safetyNoticeAdminDelete,
    safetyNoticeAdminIssuedNotice,
  } from '@/api/production-safety/responsibility-implementation';
  import { omit } from 'lodash-es';
  import { queryUserGroupPage } from '@/api/system/person-group';

  import { unformatAttachment } from '@/components/UploadFiles/utils';
  import { downloadFile } from '@/views/disaster/utils';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';

  import NotifySend from './components/NotifySend.vue';

  const router = useRouter();
  const activeTab = ref<any>('');
  const groupList = ref<any[]>([]);
  const currentRow = ref<any>(null);
  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      responsibilityName: '',
      status: '',
      date: '',
      type: '',
    },
  });
  const notifySendOpen = ref(false);

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

  watch(
    () => activeTab.value,
    (a) => {
      Object.assign(queryParams, {
        queryParam: {
          ...queryParams.queryParam,
          type: a,
        },
      });
      queryTableList();
    },
  );

  // 预览
  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 handleSend = (scope) => {
    notifySendOpen.value = true;
    currentRow.value = scope.row;
  };

  const handleNotifySend = (formValue, submitLoading) => {
    submitLoading.value = true;
    safetyNoticeAdminIssuedNotice({
      id: currentRow.value.id,
      safetyAreaId: formValue.safetyAreaData.map((item: any) => item.id).join(','),
      planStartTime: dayjs(formValue.planStartTime).format('YYYY-MM-DD'),
      planEndTime: dayjs(formValue.planEndTime).format('YYYY-MM-DD'),
    })
      .then(() => {
        notifySendOpen.value = false;
        currentRow.value = null;
        ElMessage.success('发送成功');
        queryTableList();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  };

  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 handleConfirmDeleteRow = (scope) => {
    safetyNoticeAdminDelete(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };
  const queryTableList = () => {
    console.log(queryParams.queryParam.type);
    safetyNoticeAdminQueryPage({
      ...queryParams,
      queryParam: {
        ...omit(queryParams.queryParam, 'date'),
        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.records;
      tableData.total = res.totalRow;
    });
  };
  const handleRestParams = () => {
    activeTab.value = '';
    Object.assign(queryParams, {
      pageNumber: 1,
      pageSize: 10,
      queryParam: {
        responsibilityName: '',
        status: '',
        date: '',
        type: '',
      },
    });
    queryTableList();
  };

  onMounted(async () => {
    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 *;

  :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;
  }
  .file-container--div {
    display: flex;
    align-items: center;
    gap: 10px;
    .file-container--div__name {
      min-width: 0;
      max-width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    img {
      cursor: pointer;
    }
  }
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
</style>
