<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="院领导" />
        <el-tab-pane label="部门" name="部门" />
        <el-tab-pane label="科室" name="科室" />
        <el-tab-pane label="员工" name="员工" />
        <el-tab-pane label="常驻供应商" name="常驻供应商" />
      </el-tabs> -->
    </header>
    <main class="safety-platform-container__main">
      <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-option :value="6" label="已作废" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="activeTab" label="所属部门">
            <el-select
              v-model="queryParams.queryParam.departmentName"
              clearable
              placeholder="所属部门"
              style="width: 170px"
            >
              <el-option value="院领导">院领导</el-option>
              <el-option value="所/中心/职能部门/直属研究部/分公司">所/中心/职能部门/直属研究部/分公司</el-option>
              <el-option value="所/中心级部门">所/中心级部门</el-option>
              <el-option value="科室">科室</el-option>
              <el-option value="员工">员工</el-option>
              <el-option value="常驻供应商">常驻供应商</el-option>
            </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 style="margin-bottom: 20px">
        <el-button type="primary" @click="handleOpenBatchSign">批量签署</el-button>
      </div>

      <div class="table-content">
        <el-table ref="multipleTableRef" :data="tableData.data" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="selectable" width="55" />
          <el-table-column label="责任书名称" prop="responsibilityName" width="180">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click.prevent="
                  $router.push({
                    name: 'responsibilityFeedback',
                    query: {
                      id: scope.row.id,
                      status: scope.row.status,
                      mode: 'view',
                    },
                  })
                "
                >{{ scope.row.responsibilityName }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column label="类别" prop="departmentName" 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="userGroupName" width="150" />
          <el-table-column label="计划完成时间" prop="planEndTime" width="150" />
          <el-table-column fixed="right" min-width="200" label="操作">
            <template #default="scope">
              <div style="display: flex">
                <el-button
                  v-if="
                    scope.row.status === 2 &&
                    (scope.row.departmentName !== '员工' || scope.row.departmentName !== '常驻供应商')
                  "
                  type="primary"
                  link
                  @click="
                    $router.push({
                      name: 'signAgreeDept',
                      query: {
                        id: scope.row.id,
                        status: scope.row.status,
                      },
                    })
                  "
                >
                  签署
                </el-button>
                <el-button
                  v-if="
                    scope.row.status === 2 &&
                    (scope.row.departmentName === '员工' || scope.row.departmentName === '常驻供应商')
                  "
                  type="primary"
                  link
                  @click="handleConfirm(scope)"
                >
                  确认
                </el-button>
                <el-dropdown trigger="click">
                  <el-button
                    type="primary"
                    link
                    @click="
                      $router.push({
                        name: 'responsibilityFeedback',
                        query: {
                          id: scope.row.id,
                          status: scope.row.status,
                        },
                      })
                    "
                  >
                    反馈
                  </el-button>
                  <!-- <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        @click="
                          $router.push({
                            name: 'signAgreeDept',
                            query: {
                              id: scope.row.id,
                              status: scope.row.status,
                            },
                          })
                        "
                        >待反馈材料</el-dropdown-item
                      >
                      <el-dropdown-item
                        @click="
                          $router.push({
                            name: 'signAgreeDept',
                            query: {
                              id: scope.row.id,
                              status: scope.row.status,
                            },
                          })
                        "
                        >审核不通过</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template> -->
                </el-dropdown>
                <el-button type="primary" link @click="handleDownloadLink(scope)">下载</el-button>
              </div>
            </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>
  <!-- <IssueSafetyResponsibility
    :groupList="groupList"
    :currentRowData="currentRowData"
    ref="issueSafetyResponsibilityRef"
    @submit="handleSubmit"
  /> -->
  <el-dialog title="批量签署" v-if="batchSignDialogVisible" v-model="batchSignDialogVisible" width="600">
    <el-form-item label="">
      <UploadFiles label="上传附件" :maxCount="1" @uploadSuccess="handleUploadSuccess" :fileList="attachment" />
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseBatchSign">取消</el-button>
        <el-button type="primary" @click="handleSafetyResponsibilityDeptBatchSign" :loading="submitLoading">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { onMounted, ref, reactive } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    safetyResponsibilityDeptQueryPage,
    safetyResponsibilityAdminDelete,
    safetyResponsibilityAdminIssuedSafety,
    safetyResponsibilityDeptSignOrFeedback,
    safetyResponsibilityDeptBatchSign,
  } from '@/api/production-safety/responsibility-implementation';
  import { omit } from 'lodash-es';
  import { queryUserGroupPage } from '@/api/system/person-group';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';

  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';

  import { unformatAttachment } from '@/components/UploadFiles/utils';
  import { downloadFile } from '@/views/disaster/utils';

  // import IssueSafetyResponsibility from './components/IssueSafetyResponsibility.vue';
  const router = useRouter();
  const batchSignDialogVisible = ref(false);
  const selectedRows = ref([]);
  const activeTab = ref('');
  const groupList = ref<any[]>([]);
  const submitLoading = ref(false);
  const { id: userId } = useUserInfoHook();

  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      responsibilityName: '',
      departmentName: '',
      status: '',
      date: '',
      responsibilityPersonId: userId,
    },
  });

  const multipleTableRef = ref<any>();
  const tableData = reactive({
    data: [],
    total: 0,
  });

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

  const selectable = (row) => {
    return row.status === 2 && (row.departmentName !== '员工' || row.departmentName !== '常驻供应商');
  };

  const handleSelectionChange = (val) => {
    selectedRows.value = val;
    console.log('当前勾选的数据：', selectedRows.value);
  };

  const handleUploadSuccess = (fileList) => {
    attachment.value = fileList;
  };

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

  const handleOpenBatchSign = () => {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择需要批量签署的责任书');
      return;
    }
    if (!selectedRows.value.every((item: any, i, data: any[]) => item.departmentName === data[0]?.departmentName)) {
      ElMessage.warning('请选择相同类别的责任书');
      return;
    }
    batchSignDialogVisible.value = true;
  };

  const handleCloseBatchSign = () => {
    attachment.value = [];
    selectedRows.value = [];
    batchSignDialogVisible.value = false;
    multipleTableRef.value.clearSelection();
  };

  const handleSafetyResponsibilityDeptBatchSign = async () => {
    if (!attachment.value.length) {
      ElMessage.warning('请上传附件');
      return;
    }
    submitLoading.value = true;

    const attachments = await formatAttachmentList(attachment.value);
    safetyResponsibilityDeptBatchSign({
      ids: selectedRows.value.map((item: any) => item.id)?.join(','),
      attachment: JSON.stringify(attachments),
    })
      .then(() => {
        ElMessage.success('批量签署成功');
        queryTableList();
        handleCloseBatchSign();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  };

  const handleConfirm = (scope) => {
    safetyResponsibilityDeptSignOrFeedback({
      id: scope.row.id,
      updateType: 0,
    })
      .then(() => {
        ElMessage.success('确认成功');
        router.push({
          name: 'responsibilityAgreeManageDept',
        });
      })
      .finally(() => {});
  };
  // const handleIssueSafetyResponsibility = (scope) => {
  //   currentRowData.value = scope.row;
  //   issueSafetyResponsibilityRef.value.dialogShow();
  // };

  const handleSizeChange = (value) => {};
  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) => {
  //   safetyResponsibilityAdminDelete(scope.row.id).then(() => {
  //     ElMessage.success('删除成功!');
  //     queryTableList();
  //   });
  // };
  const queryTableList = () => {
    safetyResponsibilityDeptQueryPage({
      ...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 = () => {
    Object.assign(queryParams, {
      pageNumber: 1,
      pageSize: 10,
      queryParam: {
        responsibilityName: '',
        departmentName: '',
        status: '',
        date: '',
        responsibilityPersonId: '',
      },
    });
    queryTableList();
  };

  // const handleSubmit = (formData) => {
  //   issueSafetyResponsibilityRef.value.submitLoading = true;
  //   safetyResponsibilityAdminIssuedSafety({
  //     ...formData,
  //     userGroupId: formData.userGroupId.join(','),
  //     // planStartTime: dayjs(formData.planStartTime).format('YYYY-MM-DD'),
  //     // planEndTime: dayjs(formData.planEndTime).format('YYYY-MM-DD'),
  //     id: currentRowData.value.id,
  //   })
  //     .then(() => {
  //       queryTableList();
  //       issueSafetyResponsibilityRef.value.dialogHide();
  //       currentRowData.value = {};
  //     })
  //     .finally(() => {
  //       issueSafetyResponsibilityRef.value.submitLoading = false;
  //     });
  // };

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