<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" v-auth="'yztsjsj:add'">添加</a-button>
        <a-button type="primary" @click="onExportXls" v-auth="'yztsjsj:export'">导出</a-button>
        <a-button type="primary" @click="getMdb" v-auth="'yztsjsj:mdbgdb'">下载文件(mdb、gdb)</a-button>
        <a-button type="primary" @click="handleShls" v-auth="'yztsjsj:shls'">审核历史</a-button>
        <a-button type="primary" @click="handleZgSh(true)" v-auth="'yztsjsj:zgbmsh'" v-if="userStore.userInfo.userType == 2">自然资源部门审核</a-button>
        <a-button type="primary" @click="handleZgSh(false)" v-auth="'yztsjsj:zgbmshls'">自然资源部门审核</a-button>
        <a-button type="primary" @click="handleStUp" v-auth="'yztsjsj:stbmtj'">生态部门提交</a-button>
        <a-button type="primary" @click="handleFileCheck" v-auth="'yztsjsj:wjjc'">文件检查</a-button>
        <a-button type="primary" @click="handleCheckResultDownload" v-auth="'yztsjsj:jcjgxz'">检查结果下载</a-button>
        <!-- <div style="color: red; text-align: right; flex: 1; line-height: 32px">注：本次数据为全量数据，生成的结果为前一天数据结果！</div> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>

    <!-- 表单区域 -->
    <AddModal @register="registerModal" @success="handleSuccess"></AddModal>
    <!-- 审核历史区域 -->
    <ShlsModal @register="registerModalShls"></ShlsModal>
    <!-- 自然资源部门审核区域 -->
    <ZgShModal @register="registerModalZgSh" @success="handleSuccess"></ZgShModal>
    <!-- 生态部门提交区域 -->
    <StUpdateModal @register="registerModalStUp" @success="handleSuccess"></StUpdateModal>
  </div>
  <!--查看详情前置 -->
  <a-modal v-model:visible="open" :centered="true" title="信息">
    <template #footer>
      <a-button key="submit" type="primary" @click="open = false">确定</a-button>
    </template>
    <div class="py-10 ml-6">该地块还未进行填报，没有详情可以查看</div>
  </a-modal>

  <!-- 下载 mdb/gdb：先弹窗展示生成时间，再下载或重新生成 -->
  <a-modal
    v-model:visible="mdbModalOpen"
    wrapClassName="mdb-download-modal-wrap"
    :footer="null"
    :width="520"
    :centered="true"
    destroyOnClose
    @cancel="onMdbModalCancel"
  >
    <template #title>
      <span class="mdb-download-title">文件下载</span>
    </template>
    <a-spin :spinning="jdfjLoading">
      <template v-if="mdbModalStep === 'main'">
        <div class="mdb-download-main">
          <div class="mdb-download-row">
            <span class="mdb-download-label">文件生成时间：</span>
            <span>{{ fileGenTime }}</span>
          </div>
          <div class="mdb-download-row">
            <span class="mdb-download-label">文件下载：</span>
            <a-button type="primary" @click="handleMdbDownload">
              <template #icon><DownloadOutlined /></template>
              下载
            </a-button>
          </div>
          <div class="mdb-download-regen">
            <a-button type="primary" size="large" :loading="reloadLoading" @click="handleMdbRegenerate">重新生成</a-button>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="mdb-download-done">
          <p class="mdb-download-done-text">已开始重新生成，生成结果请稍等待！</p>
          <a-button type="primary" size="large" @click="closeMdbModal">关闭</a-button>
        </div>
      </template>
    </a-spin>
  </a-modal>

  <!-- 文件检查：确认后重新生成并检查 -->
  <a-modal
    v-model:visible="fileCheckModalOpen"
    wrapClassName="file-check-modal-wrap"
    :footer="null"
    :width="520"
    :centered="true"
    destroyOnClose
    @cancel="onFileCheckModalCancel"
  >
    <template #title>
      <span class="file-check-modal-title">文件检查</span>
    </template>
    <template v-if="fileCheckStep === 'confirm'">
      <div class="file-check-confirm">
        <p class="file-check-confirm-text">是否重新生成gdb、mdb文件并进行检查？</p>
        <div class="file-check-confirm-actions">
          <a-button size="large" @click="onFileCheckModalCancel">取消</a-button>
          <a-button type="primary" size="large" :loading="fileCheckReloadLoading" @click="handleFileCheckConfirm">
            确认
          </a-button>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="file-check-done">
        <p class="file-check-done-line">已开始重新生成，文件生成后将进行检查</p>
        <p class="file-check-done-line">检查结果请稍等待！</p>
        <a-button type="primary" size="large" class="file-check-done-close" @click="closeFileCheckModal">关闭</a-button>
      </div>
    </template>
  </a-modal>

  <!-- 检查结果下载：校验中则提示稍候 -->
  <a-modal
    v-model:visible="checkResultWaitModalOpen"
    wrapClassName="check-result-wait-modal-wrap"
    :footer="null"
    :width="480"
    :centered="true"
    destroyOnClose
    @cancel="checkResultWaitModalOpen = false"
  >
    <template #title>
      <span class="check-result-wait-title">检查结果下载</span>
    </template>
    <div class="check-result-wait-body">
      <p class="check-result-wait-text">还未生成结果，请耐心等待！</p>
      <a-button type="primary" size="large" @click="checkResultWaitModalOpen = false">关闭</a-button>
    </div>
  </a-modal>
</template>

<script lang="ts" name="directory-yztsj-shiji" setup>
  import { ref } from 'vue';
  import { DownloadOutlined } from '@ant-design/icons-vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, searchFormSchema } from './data';
  import {
    list,
    getDownloadMdb,
    deleteOne,
    getExportUrl,
    cityCheckSubmit,
    cityZgbmCheck,
    checkSuccessDownLoad,
    findJdfj,
    reloadGenerated,
  } from './api';
  import { downloadFile, getDkDetail } from '/@/api/common/api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import AddModal from './modules/AddModal.vue';
  import ShlsModal from './modules/ShlsModal.vue';
  import StUpdateModal from './modules/StUpdateModal.vue';
  import ZgShModal from './modules/ZgShModal.vue';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '/@/store/modules/user';
  import { getNd, getJd } from '/@/utils/ndjd';
  const userStore: any = useUserStore();
  const { createMessage } = useMessage();
  let router = useRouter();
  //注册model
  const [registerModal, { openModal }] = useModal();
  const [registerModalShls, { openModal: openModalShls }] = useModal();
  const [registerModalStUp, { openModal: openModalStUp }] = useModal();
  const [registerModalZgSh, { openModal: openModalZgSh }] = useModal();
  //注册table数据
  const { tableContext, onExportXls } = useListPage({
    tableProps: {
      title: '市级审核数据',
      api: list,
      columns,
      canResize: false,
      clickToRowSelect: true,
      //定义rowSelection的类型，默认是checkbox多选，可以设置成radio单选
      rowKey: 'id',
      rowSelection: { type: 'radio' },
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: false,
      },
      showIndexColumn: true,
      actionColumn: {
        width: 160,
        fixed: 'right',
      },
    },
    exportConfig: {
      name: '一张图数据管理——市级审核',
      url: getExportUrl,
    },
  });
  const open = ref(false);
  /** mdb/gdb 下载弹窗 */
  const mdbModalOpen = ref(false);
  const mdbModalStep = ref<'main' | 'regenerated'>('main');
  const fileGenTime = ref('--');
  const jdfjLoading = ref(false);
  const reloadLoading = ref(false);

  /** 文件检查弹窗：确认 → 调 reloadGenerated → 成功提示 */
  const fileCheckModalOpen = ref(false);
  const fileCheckStep = ref<'confirm' | 'done'>('confirm');
  const fileCheckReloadLoading = ref(false);

  const checkResultWaitModalOpen = ref(false);

  const [registerTable, { reload, getDataSource }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;

  function isFileCheckingStatus(res: unknown): boolean {
    if (res == null) return false;
    const s = typeof res === 'string' ? res : String(res);
    return s.includes('文件校验中');
  }

  function handleFileCheckConfirm() {
    fileCheckReloadLoading.value = true;
    reloadGenerated({ nd: getNd(), jd: getJd() })
      .then(() => {
        fileCheckStep.value = 'done';
      })
      .finally(() => {
        fileCheckReloadLoading.value = false;
      });
  }

  function onFileCheckModalCancel() {
    fileCheckStep.value = 'confirm';
    fileCheckModalOpen.value = false;
  }

  function closeFileCheckModal() {
    onFileCheckModalCancel();
  }

  function parseJdfjTime(res: unknown): string {
    if (res == null || res === '') return '--';
    if (typeof res === 'string') return res;
    if (typeof res === 'object') {
      const o = res as Record<string, unknown>;
      const keys = ['wjscsj', 'scsj', 'fileGenTime', 'createTime', 'sj', 'time'];
      for (const k of keys) {
        const v = o[k];
        if (v != null && v !== '') return String(v);
      }
    }
    return '--';
  }

  function openMdbDownloadModal() {
    mdbModalStep.value = 'main';
    mdbModalOpen.value = true;
    jdfjLoading.value = true;
    findJdfj({ nd: getNd(), jd: getJd() })
      .then((res) => {
        fileGenTime.value = res?.fjscsj || '--';
      })
      .catch(() => {
        fileGenTime.value = '--';
      })
      .finally(() => {
        jdfjLoading.value = false;
      });
  }

  function onMdbModalCancel() {
    mdbModalStep.value = 'main';
    mdbModalOpen.value = false;
  }

  function closeMdbModal() {
    onMdbModalCancel();
  }

  function handleMdbDownload() {
    getDownloadMdb({ nd: getNd(), jd: getJd() }).then((res) => {
      if (res) {
        downloadFile('/sys/common/static' + res, res.split('/')[res.split('/').length - 1]);
      } else {
        createMessage.error('文件下载失败');
      }
    });
  }

  function handleMdbRegenerate() {
    reloadLoading.value = true;
    reloadGenerated({ nd: getNd(), jd: getJd() })
      .then(() => {
        mdbModalStep.value = 'regenerated';
      })
      .finally(() => {
        reloadLoading.value = false;
      });
  }

  //成功回调
  function handleSuccess() {
    selectedRows.value = [];
    selectedRowKeys.value = [];
    reload();
  }
  /**
   * 审核历史
   */
  function handleShls() {
    let arr = getDataSource();
    if (arr.length == 0) {
      createMessage.info('暂无审核数据，请稍后再试');
      return;
    }
    const record: any = arr[0];
    openModalShls(true, {
      isUpdate: false,
      showFooter: true,
      record: record,
    });
  }
  /**
   * 自然资源部门审核
   */
  function handleZgSh(type: boolean) {
    let arr = getDataSource();
    if (arr.length == 0) {
      createMessage.info('暂无需审核数据，请稍后再试');
      return;
    }
    const record: any = arr[0];
    if (type) {
      cityZgbmCheck(null).then((res) => {
        if (res) {
          openModalZgSh(true, {
            isUpdate: true,
            showFooter: true,
            record: record,
          });
        } else {
          openModalZgSh(true, {
            isUpdate: false,
            showFooter: true,
            record: record,
          });
        }
      });
    } else {
      openModalZgSh(true, {
        isUpdate: type,
        showFooter: true,
        record: record,
      });
    }
  }

  /**
   * 生态部门提交
   */
  async function handleStUp() {
    let arr = getDataSource();
    if (arr.length == 0) {
      createMessage.info('暂无提交数据，请稍后再试');
      return;
    }
    const record: any = arr[0];
    const checkRes = await cityCheckSubmit({ jd: record.jd });
    if (!checkRes || (checkRes && checkRes.indexOf('暂不可提交') > -1) || checkRes == 'false') {
      createMessage.warning(checkRes);
      return;
    }

    openModalStUp(true, {
      isUpdate: false,
      showFooter: true,
      record: record,
    });
  }

  function handleFileCheck() {
    fileCheckStep.value = 'confirm';
    fileCheckModalOpen.value = true;
  }

  async function handleCheckResultDownload() {
    const res = await checkSuccessDownLoad({ nd: getNd(), jd: getJd() });
    if (typeof res === 'string' && res.indexOf('/') > -1) {
      downloadFile('/sys/common/static' + res, res.split('/')[res.split('/').length - 1]);
      return;
    }
    if (isFileCheckingStatus(res)) {
      checkResultWaitModalOpen.value = true;
      return;
    }
    createMessage.info((res as string) || '文件校验中');
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    let arr = getDataSource();
    const record: any = arr[0];
    if (record && record.cityStatus == 2) {
      createMessage.info('数据已提交，不能添加新数据');
      return;
    }
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    getDkDetail({ wrdkbm: record.dkdm }).then((res) => {
      handleView(res.dkxx);
    });
  }

  //查看基本信息
  function handleView(record) {
    if (!record.dclx) {
      open.value = true;
      return;
    }
    router.push(`/directory/mlzk/viewSelct?wrdkid=${record.wrdkid}&dksdzt=${record.dksdzt}`);
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    if (record.cityStatus == 2) {
      createMessage.info('数据已提交，不能删除');
      return;
    }
    await deleteOne({ id: record.id }, reload);
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      // {
      //   label: '编辑',
      //   onClick: handleEdit.bind(null, record),
      // },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
        auth: 'yztsjsj:delete',
        ifShow: record.cityStatus != 2,
      },
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
        auth: 'yztsjsj:detail',
      },
    ];
  }

  const getMdb = () => {
    openMdbDownloadModal();
  };
</script>
<style scoped>
  .mdb-download-title {
    font-size: 16px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
    letter-spacing: 0.02em;
  }
  .mdb-download-main {
    padding: 8px 4px 12px;
  }
  .mdb-download-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 0;
    padding: 14px 16px;
    gap: 12px;
    flex-wrap: wrap;
    border-radius: 6px;
    background: #fafafa;
    border: 1px solid #f0f0f0;
  }
  .mdb-download-row + .mdb-download-row {
    margin-top: 12px;
  }
  .mdb-download-label {
    flex-shrink: 0;
    min-width: 112px;
    color: rgba(0, 0, 0, 0.65);
    line-height: 32px;
  }
  .mdb-download-row span:not(.mdb-download-label) {
    color: rgba(0, 0, 0, 0.88);
    line-height: 32px;
    word-break: break-all;
  }
  .mdb-download-regen {
    display: flex;
    justify-content: center;
    margin-top: 28px;
    padding-top: 22px;
    border-top: 1px solid #f0f0f0;
  }
  .mdb-download-done {
    text-align: center;
    padding: 16px 12px 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .mdb-download-done-text {
    margin: 0 0 16px;
    font-size: 15px;
    line-height: 1.65;
    color: rgba(0, 0, 0, 0.75);
    max-width: 360px;
  }

  .file-check-modal-title {
    font-size: 16px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }
  .file-check-confirm {
    padding: 8px 4px 4px;
  }
  .file-check-confirm-text {
    margin: 0 0 28px;
    text-align: center;
    font-size: 15px;
    line-height: 1.7;
    color: rgba(0, 0, 0, 0.78);
    padding: 12px 8px 8px;
  }
  .file-check-confirm-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    padding-top: 8px;
  }
  .file-check-done {
    text-align: center;
    padding: 12px 12px 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .file-check-done-line {
    margin: 0;
    font-size: 15px;
    line-height: 1.75;
    color: rgba(0, 0, 0, 0.75);
    max-width: 400px;
  }
  .file-check-done-line + .file-check-done-line {
    margin-top: 8px;
  }
  .file-check-done-close {
    margin-top: 16px;
  }

  .check-result-wait-title {
    font-size: 16px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
    letter-spacing: 0.02em;
  }
  .check-result-wait-body {
    text-align: center;
    padding: 12px 8px 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .check-result-wait-text {
    margin: 0 0 16px;
    font-size: 15px;
    line-height: 1.75;
    color: rgba(0, 0, 0, 0.78);
    max-width: 380px;
  }
</style>
<style lang="less">
  /* 弹层挂载在 body 下，需非 scoped 才能作用到 ant-modal */
  .mdb-download-modal-wrap {
    .ant-modal-content {
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 8px 28px rgba(0, 0, 0, 0.12);
    }
    .ant-modal-header {
      padding: 18px 28px 16px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 0;
    }
    .ant-modal-body {
      padding: 20px 28px 20px;
    }
    .ant-modal-close {
      top: 14px;
      right: 18px;
    }
  }

  .file-check-modal-wrap {
    .ant-modal-content {
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 8px 28px rgba(0, 0, 0, 0.12);
    }
    .ant-modal-header {
      padding: 18px 28px 16px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 0;
    }
    .ant-modal-body {
      padding: 20px 28px 20px;
    }
    .ant-modal-close {
      top: 14px;
      right: 18px;
    }
  }

  .check-result-wait-modal-wrap {
    .ant-modal-content {
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 8px 28px rgba(0, 0, 0, 0.12);
    }
    .ant-modal-header {
      padding: 18px 28px 16px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 0;
    }
    .ant-modal-body {
      padding: 20px 28px 20px;
    }
    .ant-modal-close {
      top: 14px;
      right: 18px;
    }
  }
</style>
