<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">责任区域(非区域执行人)</div>
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <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: 'areaAddResponsibilities:nonPublic',
            })
          "
          :icon="Plus"
          >添加
        </el-button>
        <el-button @click="batchImportVisible = true">导入</el-button>
      </div>
      <div class="search-form">
        <el-form :inline="true">
          <el-form-item label="区域名称">
            <el-input v-model="queryParams.queryParam.nameFunction" 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-select>
          </el-form-item>
        </el-form>

        <div>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handleRestParams">重置</el-button>
          <el-button @click="handleDownload">导出</el-button>
        </div>
      </div>

      <div class="table-content">
        <el-table :data="tableData.data">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column label="楼号" prop="buildingNo" width="100" />
          <el-table-column label="楼层" prop="buildingArea" width="100" />
          <el-table-column label="房间/区域" prop="floorRoomNo" width="180" />
          <el-table-column label="功能名称" prop="nameFunction" width="160" />
          <el-table-column label="安全责任所/中心" prop="safetyResponsibleCenter" width="200" />
          <el-table-column label="安全责任所/中心负责人" prop="safetyCenterManagerName" width="200" />
          <el-table-column label="安全责任部门" prop="safetyResponsibleDepartment" width="180" />
          <el-table-column label="安全责任部门负责人" prop="safetyDepartmentManagerName" width="180" />
          <el-table-column label="安全具体责任人" prop="safetySpecificPersonName" width="180" />
          <el-table-column label="安全具体责任人联系方式" prop="safetyPersonContact" width="230" />
          <el-table-column label="是否进行过责任人变更" prop="changed" width="220" />
          <el-table-column label="变更原因" show-overflow-tooltip prop="changeReason" width="170" />
          <el-table-column label="状态" prop="statusName" width="100" />
          <el-table-column fixed="right" min-width="240" label="操作">
            <template #default="scope">
              <template v-if="scope.row.status === 1">
                <el-button
                  type="primary"
                  link
                  @click="
                    $router.push({
                      name: 'areaEditResponsibilities:nonPublic',
                      query: {
                        id: scope.row.id,
                      },
                    })
                  "
                  >编辑
                </el-button>
                <el-popconfirm title="确定要删除吗?" @confirm="handleConfirmDeleteRow(scope)">
                  <template #reference>
                    <el-button type="primary" link>删除</el-button>
                  </template>
                </el-popconfirm>

                <el-button
                  type="primary"
                  link
                  @click="
                    $router.push({
                      name: 'areaChangeResponsibilities:nonPublic',
                      query: {
                        id: scope.row.id,
                      },
                    })
                  "
                  >变更</el-button
                >
              </template>
              <template v-if="scope.row.canChange === true">
                <el-button type="primary" link @click="handleAreaCheckListApprove(scope, 1)">确认</el-button>
                <el-button type="primary" link @click="handleAreaCheckListApprove(scope, 0)">拒绝</el-button>
              </template>
              <template v-if="scope.row.status === 3">
                <el-button type="primary" link>变更</el-button>
              </template>
              <el-button
                type="primary"
                link
                @click="
                  $router.push({
                    name: 'areaViewResponsibilities:nonPublic',
                    query: {
                      id: scope.row.id,
                    },
                  })
                "
                >查看</el-button
              >
              <el-button
                link
                type="primary"
                v-if="scope.row.creatBy === id && scope.row.status === 2"
                @click="handleAreaCheckListApprove(scope, 0)"
              >
                撤回
              </el-button>
              <template v-if="scope.row.changed === '是'">
                <el-button type="primary" link @click="changedList(scope.row)">变更记录</el-button>
              </template>
            </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>
    <!-- 变更记录 -->
    <el-dialog width="70%" v-model="changedVisible" title="公共区域变更记录">
        <div class="table-content">
            <h4>当前信息（变更后）</h4>
            <el-table :data="changedListData.currentRecord">
                <el-table-column type="index" label="编号" width="80" />
                <el-table-column label="楼号" prop="buildingNo" width="100" />
                <el-table-column label="楼层" prop="buildingArea" width="100" />
                <el-table-column label="房间/区域" prop="floorRoomNo" width="180" />
                <el-table-column label="功能名称" prop="nameFunction" width="160" />
                <el-table-column label="安全责任所/中心" prop="safetyResponsibleCenter" width="200" />
                <el-table-column label="安全责任所/中心负责人" prop="safetyCenterManagerName" width="200" />
                <el-table-column label="安全责任部门" prop="safetyResponsibleDepartment" width="180" />
                <el-table-column label="安全责任部门负责人" prop="safetyDepartmentManagerName" width="180" />
                <el-table-column label="安全具体责任人" prop="safetySpecificPersonName" width="180" />
                <el-table-column label="安全具体责任人联系方式" prop="safetyPersonContact" width="230" />
                <el-table-column label="变更原因" show-overflow-tooltip prop="changeReason" width="170" />
                <el-table-column label="状态" prop="statusName" width="100" />
            </el-table>
        </div>
        <div class="table-content">
            <h4>历史记录（变更前）</h4>
            <el-table :data="changedListData.historiesRecords">
                <el-table-column type="index" label="编号" width="80" />
                <el-table-column label="变更时间" prop="createdAt" width="180" />
                <el-table-column label="变更人" prop="safetySpecificPersonName" width="180" />
                <el-table-column label="楼号" prop="buildingNo" width="100" />
                <el-table-column label="楼层" prop="buildingArea" width="100" />
                <el-table-column label="房间/区域" prop="floorRoomNo" width="180" />
                <el-table-column label="功能名称" prop="nameFunction" width="160" />
                <el-table-column label="安全责任所/中心" prop="safetyResponsibleCenter" width="200" />
                <el-table-column label="安全责任所/中心负责人" prop="safetyCenterManagerName" width="200" />
                <el-table-column label="安全责任部门" prop="safetyResponsibleDepartment" width="180" />
                <el-table-column label="安全责任部门负责人" prop="safetyDepartmentManagerName" width="180" />
                <el-table-column label="安全具体责任人" prop="safetySpecificPersonName" width="180" />
                <el-table-column label="安全具体责任人联系方式" prop="safetyPersonContact" width="230" />
                <el-table-column label="变更原因" show-overflow-tooltip prop="changeReason" width="170" />
                <el-table-column label="状态" prop="statusName" width="100" />
            </el-table>
        </div>
    </el-dialog>
  </div>
  <BatchImport
    :visible="batchImportVisible"
    :importApiUrl="importApiUrl"
    :templateUrl="templateUrl"
    :show-template="false"
    :templateName="'责任区域-批量导入模版'"
    @close="() => (batchImportVisible = false)"
    @update="handleUpdate"
  />
</template>
<script lang="ts" setup>
  import { onMounted, ref, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import {
    areaCheckListQueryPage,
    areaCheckListApprove,
    areaCheckListDelete,
    areaCheckListExportArea,
    queryChangedList,
  } from '@/api/production-safety/responsibility-implementation';
  import urlJoin from 'url-join';
  import { BatchImport } from '@/components/batch-import';
  import { Plus } from '@element-plus/icons-vue';

  import { downloadFile } from '@/views/disaster/utils';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { downloadByData } from '@/utils/file/download';

  const router = useRouter();
  const activeTab = ref(2);
  const { id } = useUserInfoHook();

  const queryParams = reactive<any>({
    pageNumber: 1,
    pageSize: 10,
    queryParam: {
      type: 2,
      nameFunction: '',
      status: '',
      responsibilityPersonId: id,
    },
  });

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/areaCheckList/importArea?type=2'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/import-law-regulation-template.xlsx');

  const handleUpdate = () => {
    batchImportVisible.value = false;
    queryTableList();
  };
  const changedVisible = ref(false)
  const changedListData = reactive({
  currentRecord:[],
  historiesRecords:[]
})
  const changedList = async(item)=>{
    await fetchTableList(item.id)
    changedVisible.value = true
  }
  const fetchTableList = async (id)=>{
    let res = await queryChangedList({id})
    if(!res){ return }
    Object.assign(changedListData, {
        currentRecord: res.currentRecord || [],
        historiesRecords: res.historiesRecords || []
    })
  }
  const tableData = reactive({
    data: [],
    total: 0,
  });
  const handleTabChange = (tab) => {
    if (tab === 1) {
      router.push({
        name: 'areaResponsibilities:public',
      });
    } else if (tab === 2) {
      router.push({
        name: 'areaResponsibilities:nonPublic',
      });
    }
  };

  async function handleDownload() {
    try {
      const response = await areaCheckListExportArea(queryParams.queryParam);
        if (response) {
            const fileName = `责任区域(非区域执行人)_${new Date().toISOString().split('T')[0]}.xlsx`;
            downloadByData(response, fileName);
            ElMessage.success('导出成功');
        }
    } catch (e) {
      ElMessage.error('导出失败');
      console.log(e);
    }
  }

  const handleAreaCheckListApprove = (scope, approveType) => {
    areaCheckListApprove({
      id: scope.row.id,
      approveType,
      refuseReason: null,
    }).then(() => {
      if (approveType === 1) {
        ElMessage.success('请尽快修改该责任清单的安全责任所/中心、安全责任部门及相关负责人信息');
      } else {
        ElMessage.success('操作成功!');
      }
      queryTableList();
    });
  };

  const handleSizeChange = (value) => {
    queryParams.pageSize = value;
    queryTableList();
  };
  const handleCurrentChange = (value) => {
    queryParams.pageNumber = value;
    queryTableList();
  };

  const handleConfirmDeleteRow = (scope) => {
    areaCheckListDelete(scope.row.id).then(() => {
      ElMessage.success('删除成功!');
      queryTableList();
    });
  };
  const queryTableList = () => {
    areaCheckListQueryPage(queryParams).then((res) => {
      tableData.data = res.records;
      tableData.total = res.totalRow;
    });
  };
  const handleRestParams = () => {
    Object.assign(queryParams, {
      pageNumber: 1,
      pageSize: 10,
      queryParam: {
        ...queryParams.queryParam,
        status: '',
        nameFunction: '',
      },
    });
    queryTableList();
  };

  onMounted(() => {
    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 {
    display: flex;
    justify-content: flex-end;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
</style>
