<template>
  <div class="scren">
    <PageWrapper contentBackground>
      <template #footer>
        <a-tabs v-model:activeKey="tableType" @change="changeTable">
          <Tabs.TabPane :key="0" tab="方位图" :disabled="loading" />
          <Tabs.TabPane :key="1" tab="平面图" :disabled="loading" /> </a-tabs
      ></template>
      <div class="desc-wrap-BasicTable">
        <BasicTable v-show="tableType" @register="registerTable">
          <template #toolbar>
            <a-button
              type="primary"
              v-if="getTypeCheckPerm('overview-add')"
              @click="handleAdd('overview')"
            >
              新增</a-button
            >
          </template>

          <template #href="{ record }">
            <!-- <a
              v-if="!!record.listCover || record.mapUrl"
              target="_blank"
              :title="record.title"
              :href="!!record.listCover || record.mapUrl"
              >{{ record.title || '-' }}</a
            > -->
            <span>{{ record.title || '-' }}</span>
          </template>
          <template #action="{ record }">
            <TableAction
              stopButtonPropagation
              :actions="[
                {
                  label: '复制',
                  ifShow: getTypeCheckPerm('overview-copy') && !!record.listCover,
                  onClick: handleCopy.bind(null, record),
                },
                {
                  label: '重命名',
                  ifShow: getTypeCheckPerm('overview-rename') && !!record.listCover,
                  onClick: handlegoRename.bind(null, record),
                },
                {
                  label: '编辑',
                  ifShow: getTypeCheckPerm('overview-edit'),
                  onClick: handlegotoEdit.bind(null, record),
                },
                {
                  label: '下载',
                  ifShow: getTypeCheckPerm('overview-download') && !!record.listCover,
                  onClick: createConfirmDownload.bind(null, record),
                },
                {
                  label: '删除',
                  ifShow: getTypeCheckPerm('overview-delete'),
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
        <BasicTable v-show="!tableType" @register="registerTable1">
          <template #toolbar>
            <a-button
              type="primary"
              v-if="getTypeCheckPerm('tabulation-add')"
              @click="handleAdd('tabulation')"
            >
              新增</a-button
            >
          </template>

          <template #href="{ record }">
            <!-- <a
              v-if="!!record.listCover || record.mapUrl"
              target="_blank"
              :title="record.title"
              :href="!!record.listCover || record.mapUrl"
              >{{ record.title || '-' }}</a
            > -->
            <span>{{ record.title || '-' }}</span>
          </template>
          <template #action="{ record }">
            <TableAction
              stopButtonPropagation
              :actions="[
                {
                  label: '复制',
                  ifShow: getTypeCheckPerm('tabulation-copy') && !!record.listCover,

                  onClick: handleCopy.bind(null, record),
                },
                {
                  label: '重命名',
                  ifShow: getTypeCheckPerm('tabulation-rename') && !!record.listCover,
                  onClick: handlegoRename.bind(null, record),
                },
                {
                  label: '编辑',
                  ifShow: getTypeCheckPerm('tabulation-edit'),
                  onClick: handlegotoEdit.bind(null, record),
                },
                {
                  label: '下载',
                  ifShow: getTypeCheckPerm('tabulation-download') && !!record.listCover,
                  onClick: createConfirmDownload.bind(null, record),
                },
                {
                  label: '删除',
                  ifShow: getTypeCheckPerm('tabulation-delete'),
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
      </div>
      <DownLoadModal
        :downloadOption="downloadOption"
        @cancel="afterClose"
        @register="registerDownModal"
        @update="reload"
        cancelText="取消下载"
        okText="下载"
        @cancelDownload="cancelDownload"
        :okButtonProps="{ disabled: canDownload }"
      />
      <MoveModal @register="registerMoveModal" />
      <AddModal @register="registerAddModal" @update="reload" />
      <AddRenameModal :tableType="tableType" @register="registerRenameModal" @update="reload" />
      <PowersModal @register="registerPowersModal" />
    </PageWrapper>
  </div>
</template>
<script lang="ts">
  import { defineComponent, h, computed, ref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction, BasicColumn, FormProps } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import AddModal from './addCaseModal.vue';
  import AddRenameModal from './reName.vue';
  import DownLoadModal from './DownLoadModal.vue';
  import MoveModal from '/@/views/productOperation/modal/MoveModal.vue';
  import PowersModal from '/@/views/productOperation/modal/PowersModal.vue';
  import { Time } from '/@/components/Time';
  import { Descriptions, Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useModal } from '/@/components/Modal';
  import {
    caseOverviewList,
    caseOverviewDel,
    caseTabulationList,
    caseTabulationCopy,
    caseOverviewCopy,
    caseTabulationDel,
  } from '/@/api/operate/case';
  import { caseOverviewAdd, caseTabulationAdd } from '/@/api/operate/draw.ts';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    components: {
      DownLoadModal,
      MoveModal,
      PowersModal,
      BasicTable,
      TableAction,
      PageWrapper,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      AddModal,
      AddRenameModal,
      // Tabs,
      [Tabs.name]: Tabs,
      // [Tabs.TabPane?.name]: Tabs.TabPane,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const userInfo = computed(() => userStore.getUserInfo);
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const loading = ref(false);
      const tableType = ref<number>(0); //0看看 、1看见、2深时
      const columns: BasicColumn[] = [
        {
          title: '标题',
          dataIndex: 'title',
          ellipsis: true,
          resizable: true,
          minWidth: 150,
          width: 300,
        },
        {
          title: '来源',
          dataIndex: 'resource',
          ellipsis: true,
          width: 100,
          customRender: ({ record }) => {
            return record.isCopy ? '复制' : record.resource || '-';
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 230,
          customRender: ({ record }) => {
            return (
              record.createTime &&
              h(Time, {
                value: record.createTime,
                mode: 'datetime',
              })
            );
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 250,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        schemas: [
          {
            field: 'title',
            label: '名称',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
        ],
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerAddModal, { openModal: openAddModal }] = useModal();
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [registerRenameModal, { openModal: openRenameModal }] = useModal();
      const [registerPowersModal, { openModal: openPowersModal }] = useModal();
      const [registerTable, { reload: reload1 }] = useTable({
        api: caseOverviewList,
        title: ``,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { isShare: tableType },
        useSearchForm: true,
        formConfig: searchForm,
        showIndexColumn: false,
        showTableSetting: true,
        beforeFetch: (T) => {
          loading.value = true;
          return T;
        },
        afterFetch: (T) => {
          loading.value = false;
          return T;
        },
        rowKey: 'id',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      const [registerTable1, { reload: reload2 }] = useTable({
        api: caseTabulationList,
        title: ``,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { isShare: tableType },
        useSearchForm: true,
        formConfig: searchForm,
        showIndexColumn: false,
        showTableSetting: true,
        beforeFetch: (T) => {
          loading.value = true;
          return T;
        },
        afterFetch: (T) => {
          loading.value = false;
          return T;
        },
        rowKey: 'id',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      function changeTable(val: number) {
        tableType.value = val;
        reload();
      }
      function handlegoRename(record) {
        openRenameModal(
          true,
          tableType.value
            ? { overviewId: record.id, newTitle: record.title }
            : { tabulationId: record.id, newTitle: record.title },
        );

        // createPrompt({
        //   title: '请输入邮箱',
        //   required: true,
        //   label: '邮箱',
        //   defaultValue: '默认邮箱',
        //   onOK: async (email: string) => {
        //     message.success('填写的邮箱地址为' + email);
        //   },
        //   inputType: 'Input',
        // });
      }

      async function handleAdd(type) {
        // openAddModal(true, {});
        if (type == 'overview') {
          let record = await caseOverviewAdd({ type: 0 });
          // handlegotoEdit(record);
          // window.open(`/draw/#/overview`);
          // window.open(`/draw/#/overview?caseId=${caseId.value}`);
        } else {
          // window.open(`/draw/#/tabulation?caseId=${caseId.value}&tabulationId=${res.id}`);
          let record = await caseTabulationAdd({ type: 1 });
          // handlegotoEdit(record);
          // window.open(`/draw/#/tabulation`);
        }
        reload();
        // router.push({ path: '/scene/add' });
      }
      function reload() {
        reload1();
        reload2();
      }

      async function handleCopy(record: Recordable) {
        let url = tableType.value == 1 ? caseOverviewCopy : caseTabulationCopy;
        let param =
          tableType.value == 1
            ? { overviewIds: [record.id], isCopy: 1 }
            : {
                tabulationIds: [record.id],
                isCopy: 1,
              };
        createConfirm({
          title: '复制',
          content: '确定要复制吗？',
          onOk: async () => {
            url(param).then(() => {
              message.success({
                content: '复制成功',
              });
              reload();
            });
          },
        });
      }
      async function handleDelete(record: Recordable) {
        let url = tableType.value == 1 ? caseOverviewDel : caseTabulationDel;
        let param =
          tableType.value == 1
            ? { overviewId: record.id }
            : {
                tabulationId: record.id,
              };
        createConfirm({
          title: '删除',
          content: '确定要删除吗？',
          onOk: async () => {
            url(param).then(() => {
              message.success({
                content: '删除成功',
              });

              reload();
            });
          },
        });
      }
      async function handleMove(record: Recordable) {
        openMoveModal(true, {
          ...record,
        });
        // sceneMove({ snCode: record.snCode, num: record.num })
        //   .then(() => {
        //     message.success({
        //       content: '迁移成功',
        //     });
        //   })
        //   .catch(() => {
        //     message.success({
        //       content: '迁移失败',
        //     });
        //   });
      }
      let timer: null = ref(null);
      const downloadOption = ref<Object>({});
      const canDownload = ref<boolean>(true);
      function createConfirmDownload(record: Recordable) {
        handleDownload(record);
        // createConfirm({
        //   title: '提示',
        //   okText: '继续',
        //   content: '是否确定下载。',
        //   onOk: async () => {
        //   },
        // });
      }

      function handleDownload(record: Recordable) {
        console.log('handleDownload', record, record.listCover || record.mapUrl);
        downloadByUrl({
          url: record.listCover || record.mapUrl,
          target: '_blank',
          fileName: record.title,
        });
      }
      function getExtension(name) {
        if (!name) return;
        return name.substring(name.lastIndexOf('.'));
      }
      function handleEdit(record: Recordable) {
        window.open(record.thumbEdit + '&&token=' + token.value);
      }
      async function handleGenerate(record: Recordable) {
        console.log('record', record);
        let data = await sceneDetail({ id: record.id });
        console.log('data', data);
        let { buildObjStatus } = data;
        let toastText =
          buildObjStatus == 2
            ? 'Mesh场景正在计算中，请耐心等待'
            : buildObjStatus == 1
            ? '重新生成Mesh场景将覆盖现有场景信息，计算过程中Mesh场景无法打开，确定要重新生成吗？'
            : '生成obj需要较长时间，请耐心等待';
        // if (data.code === 200) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '生成 obj'),
          content: () => h('span', toastText),
          onOk: async () => {
            if (buildObjStatus !== 2) {
              await buildSceneObj({ id: record.id, sceneNum: record.num });
            }
            createMessage.success(t('common.optSuccess'));
            reload();
          },
        });
        // } else {
        //   createMessage.error(t(`apiCode.errCode${data.code}`));
        // }
      }
      function afterClose() {
        clearInterval(timer.value);
        timer.value = null;
      }
      function handleReset(record: Recordable) {
        console.log('handleReset', record);
        rebuildScene({ num: record.num }).then(() => {
          message.success({
            content: '操作成功',
          });
          reload();
        });
      }
      function getTypeCheckPerm(val) {
        let myType = tableType.value;
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`);
      }
      function handlegotoEdit(record) {
        if (!tableType.value) {
          window.open(`/draw/#/tabulation?tabulationId=${record.id}`);
        } else {
          window.open(`/draw/#/overview?overviewId=${record.id}`);
        }
      }
      function handlePowers(record: Recordable) {
        openPowersModal(true, {
          ...record,
          tableType: tableType.value,
        });
      }
      onMounted(() => {});
      return {
        registerTable,
        registerTable1,
        registerPowersModal,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        loading,
        changeTable,
        t,
        openDownModal,
        registerRenameModal,
        registerDownModal,
        registerMoveModal,
        registerAddModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        handleGenerate,
        getTypeCheckPerm,
        handlegotoEdit,
        handlePowers,
        userInfo,
        handleAdd,
        reload,
        getCheckPerm,
        handlegoRename,
        createConfirmDownload,
      };
    },
  });
</script>
<style lang="less" scoped>
  .scren {
    .noScene {
      position: absolute;
      top: calc(50% - 126px);
      width: 100%;
      text-align: center;
      &-content {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
        line-height: 22px;
        font-style: normal;
        text-transform: none;
        .codelist {
          margin-top: 36px;
          width: 424px;
          height: auto;
          display: flex;
          justify-content: space-between;
          margin: 0 auto;
          .codediv {
            font-weight: 400;
            font-size: 17px;
            color: rgba(0, 0, 0, 0.85);
            line-height: 22px;
            height: auto;
            padding: 24px;
            background: #fff;
            text-align: center;
            .codetext {
              margin-top: 10px;
            }
          }
        }
      }
    }
  }
  // .tableHeader {
  //   height: 50px;
  //   display: flex;
  //   align-items: center;

  //   .item {
  //     font-size: 14px;
  //     color: #666;
  //     margin-right: 10px;
  //     cursor: pointer;
  //     &.active {
  //       font-weight: bold;
  //       color: #222;
  //     }
  //   }
  // }
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }
</style>
