<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="" key="all" />
        <el-tab-pane label="院领导" name="院领导" key="a" />
        <el-tab-pane label="所/中心/职能部门/直属研究部/分公司" name="所/中心/职能部门/直属研究部/分公司" key="b" />
        <el-tab-pane label="所/中心级部门" name="所/中心级部门" key="c" />
        <el-tab-pane label="科室" name="科室" key="d" />
        <el-tab-pane label="员工" name="员工" key="e" />
        <el-tab-pane label="常驻供应商" name="常驻供应商" key="f" />
      </el-tabs>
    </header>
    <main class="safety-platform-container__main">
      <div style="margin-bottom: 20px">
        <el-button
          type="primary"
          @click="
            $router.push({
              name: 'createResponsibilityAgree',
            })
          "
          :icon="Plus"
          >添加责任书
        </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-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 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="180" />
          <el-table-column label="下发数" prop="issuedQuantity" width="120" >
            <template #default="scope">
              {{ scope.row.status == 1 ? '-' : scope.row.issuedQuantity }}
            </template>
          </el-table-column>
          <el-table-column label="签署人数" prop="signedQuantity" width="120">
            <template #default="scope">
              {{ scope.row.status == 1 ? '-' : scope.row.signedQuantity }}
            </template>
          </el-table-column>
          <el-table-column label="签署比例" prop="signedRatio" width="120">
            <template #default="scope">
              {{ scope.row.status == 1 ? '-' : scope.row.signedRatio }}
            </template>
          </el-table-column>
          <el-table-column label="责任人所在部门" prop="deptName" width="180" />
          <el-table-column label="分组名称" prop="userGroupName" width="150">
            <template #default="scope">
              {{ scope.row.status == 1 ? '-' : scope.row.userGroupName }}
            </template>
          </el-table-column>
          <el-table-column label="计划完成时间" prop="planEndTime" width="150">
            <template #default="scope">
              {{ scope.row.status == 1 ? '-' : scope.row.planEndTime }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" min-width="300" label="操作">
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 1 || scope.row.status === 2 || scope.row.status === 3"
                type="primary"
                link
                @click="
                  $router.push({
                    name: 'editResponsibilityAgree',
                    query: {
                      id: scope.row.id,
                    },
                  })
                "
              >
                编辑
              </el-button>
              <!-- <el-button v-if="scope.row.status === 4">审核</el-button> -->
              <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-button
                v-if="scope.row.status === 1 || scope.row.status === 2"
                type="primary"
                link
                @click="handleIssueSafetyResponsibility(scope)"
                >下发
              </el-button>
              <!-- <el-popconfirm v-if="scope.row.status === 4">
                <el-button type="primary" link @click="handleScrap">作废</el-button>
              </el-popconfirm> -->

              <el-button
                v-if="scope.row.status !== 1"
                type="primary"
                link
                @click="
                  $router.push({
                    name: 'viewRecipients',
                    query: {
                      id: scope.row.id,
                      status: scope.row.status,
                    },
                  })
                "
                >下发对象</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>
  <IssueSafetyResponsibility
    v-if="dialogOpen"
    v-model.visible="dialogOpen"
    :groupList="groupList"
    :currentDepartmentKey="currentDepartmentKey"
    :departmentOptions="departmentOptions"
    :currentRowData="currentRowData"
    @submit="handleSubmit"
  />
</template>
<script lang="ts" setup>
  import { onMounted, ref, reactive, computed, watch } from 'vue';
  import dayjs from 'dayjs';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import { Plus } from '@element-plus/icons-vue';
  import {
    safetyResponsibilityAdminqueryPage,
    safetyResponsibilityAdminDelete,
    safetyResponsibilityAdminIssuedSafety,
  } from '@/api/production-safety/responsibility-implementation';
  import { omit } from 'lodash-es';
  import { queryUserGroupPage } from '@/api/system/person-group';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import { getAllDepartments } from '@/api/auth/dept';

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

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

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

  const filterDeptsByLevel = (data, maxLevel, level = 1) => {
    if (!data || !Array.isArray(data)) return [];

    return data.map((item) => {
      const { children, ...rest } = item;
      if (level < maxLevel && children.length > 0) {
        return {
          ...item,
          children: filterDeptsByLevel(children, maxLevel, level + 1),
        };
      }
      if (level < maxLevel) {
        return { ...rest, disabled: true };
      }
      return rest;
    });
  };

  const currentDepartmentKey = computed(() => {
    switch (currentRowData.value.departmentName) {
      case '院领导':
        return 'A';
      case '所/中心/职能部门/直属研究部/分公司':
        return 'B';
      case '所/中心级部门':
        return 'C';
      case '科室':
        return 'D';
      case '员工':
      case '常驻供应商':
        return 'E';
      default:
        return 'default';
    }
  });
  const departmentOptions = computed(() => {
    switch (currentDepartmentKey.value) {
      // 院领导: A
      case 'B': // 所/中心/职能部门/直属研究部/分公司
        return filterDeptsByLevel(deptsOptions.value, 1);
      case 'C': //所/中心级部门
        return filterDeptsByLevel(deptsOptions.value, 2);
      case 'D': // 科室
        return filterDeptsByLevel(deptsOptions.value, 3);
      case 'E': // 员工、常驻供应商
        return filterDeptsByLevel(deptsOptions.value, 4);
      default:
        return deptsOptions.value;
    }
  });

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

  const getDeptData = () => {
    return getAllDepartments().then((res) => {
      deptsOptions.value = formatDeptTree(res);
    });
  };

  const handleIssueSafetyResponsibility = (scope) => {
    currentRowData.value = scope.row;
    dialogOpen.value = true;
  };

  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) => {
    safetyResponsibilityAdminDelete(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };
  const queryTableList = () => {
    safetyResponsibilityAdminqueryPage({
      ...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) => {
      res.records.forEach(item=>{
        // 未下发
        if(item.status === 1){
            item.issuedQuantity = '-'
            item.signedQuantity = '-'
            item.signedRatio = '-'
        }
      })
      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, submitLoading) => {
    submitLoading.value = true;

    safetyResponsibilityAdminIssuedSafety({
      ...formData,
      adminId: currentRowData.value.id,
      userGroupId: formData?.userGroupId?.join(',') ?? undefined,
      deptId: JSON.stringify(formData.deptId),
      signPerson: Array.isArray(formData.signPerson) ? formData.signPerson.join(',') : undefined,
      departmentId: formData.deptId.map((item) => (Array.isArray(item) ? item[item.length - 1] : item)).join(','),
    })
      .then(() => {
        queryTableList();
        dialogOpen.value = false;
        currentRowData.value = {};
      })
      .finally(() => {
        submitLoading.value = false;
      });
  };
  watch(
    () => activeTab.value,
    (a) => {
      queryParams.queryParam.departmentName = a;
      queryTableList();
    },
  );

  onMounted(() => {
    Promise.all([getDeptData(), handleQueryUserGroupPage()]).then(() => {
      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;
  }
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
</style>
