<template>
  <PageWrapper contentBackground fixed-height>
    <template #footer>
      <a-tabs v-model:activeKey="tableType" @change="changeTable">
        <a-tab-pane :key="0" :tab="t('routes.scenes.4dkk')" :disabled="loading" />
        <a-tab-pane :key="1" :tab="t('routes.scenes.4dkj')" :disabled="loading" />
        <a-tab-pane :key="2" :tab="t('routes.scenes.4dssdy')" :disabled="loading" />
        <a-tab-pane :key="4" :tab="t('routes.scenes.obj')" :disabled="loading" />
        <a-tab-pane :key="5" :tab="t('routes.scenes.4dsg')" :disabled="loading" />
        <a-tab-pane :key="6" :tab="t('routes.scenes.4dsgobj')" :disabled="loading" />
        <!-- <a-tab-pane :key="3" tab="四维双目Lite" :disabled="loading"/>  -->
      </a-tabs>
    </template>
    <div class="desc-wrap-BasicTable">
      <BasicTable
        @register="registerTable"
        :rowSelection="{ type: 'checkbox', getCheckboxProps: getCheckboxProps }"
        @fetch-success="handleFetchSuccess"
      >
        <template #toolbar>
          <a-button v-if="isPatchAuth" type="primary" @click="handlePatchSelect">
            {{ t('routes.archive.patchArchive') }}</a-button
          >
          <!-- <a-button type="primary" color="warning" @click="() => {}"> 编辑</a-button>
        <a-button type="primary" color="error" @click="() => {}"> 删除</a-button> -->
        </template>
        <template #mapShow="{ record }">
          <Switch
            v-model:checked="record.mapShow"
            :disabled="record.status !== -2"
            :checkedValue="1"
            :unCheckedValue="0"
            @click="handleUpdateSwitch(record)"
          />
        </template>
        <template #cover="{ record }">
          <TableImg
            :size="120"
            :simpleShow="true"
            :imgList="[record.thumb || '/resource/img/header.jpg']"
          />
        </template>
        <template #link="{ record }">
          <template v-if="record.payStatus != -2">
            <a
              v-if="record.status !== 0"
              :href="record.webSite + `&lang=${isJA ? 'ja' : 'zh'}`"
              target="_blank"
            >
              {{ record.webSite }}</a
            >
            <span v-else>{{ record.webSite }}</span>
          </template>
        </template>
        <template #payStatus="{ record }">
          <span v-if="record.payStatus != -2"> {{ t('routes.archive.payStatus0') }}</span>
          <span v-else>{{ t('routes.archive.payStatus1') }}</span>
        </template>
        <template #action="{ record }">
          <TableAction
            v-if="record.payStatus != -2"
            :actions="[
              {
                color: 'error',
                icon: 'mage:edit-fill',
                tooltip: t('routes.scenes.editor'),
                disabled: record.status != -2,
                onClick: openSceneEditor.bind(null, record),
                ifShow: !record.coldStorage,
              },
              {
                label: t('routes.scenes.upgrade'),
                ifShow: record.sceneVersion == 'v3' && record.isMain,
                disabled: record.status != -2,
                onClick: handleUpgrade.bind(null, record),
              },

              {
                icon: 'ic:round-assistant-direction',
                tooltip: t('routes.scenes.assistant'),
                disabled: record.status != -2,
                onClick: needAssistant.bind(null, record),
                ifShow: record.isMain,
              },
              {
                tooltip: t('routes.scenes.copy'),
                icon: 'tabler:copy-check',
                disabled: record.status != -2,
                onClick: handleCopy.bind(null, record),
              },
              {
                tooltip: t('routes.scenes.creatobj'),
                icon: 'carbon:chart-3d',
                ifShow:
                  record.status == -2 &&
                  (tableType == 2 || (tableType == 5 && record.location == 4)) &&
                  record.isMain &&
                  !record.coldStorage,
                onClick: handleGenerate.bind(null, record),
              },
              {
                color: 'error',
                icon: 'material-symbols:delete',
                tooltip: t('routes.scenes.delete'),
                ifShow: record.isDel,
                disabled: record.status != -2,
                popConfirm: {
                  title: t('common.delConfirm'),
                  confirm: handleDelete.bind(null, record),
                },
              },

              {
                tooltip: t('routes.scenes.downloadScene'),
                disabled: record.status != -2,
                ifShow: record.isDownload,
                icon: 'entypo:download',
                popConfirm: {
                  title: t('routes.scenes.downloadSceneConfirm'),
                  confirm: handleDownloadScene.bind(null, record),
                },
              },
              {
                tooltip: t('routes.scenes.migrate'),
                disabled: record.status != -2,
                ifShow: record.isMigrate,
                icon: 'carbon:migrate',
                onClick: handleMigrate.bind(null, record),
              },
              {
                tooltip: t('routes.scenes.downloadSceneE57'),
                disabled: record.status != -2,
                ifShow:
                  (tableType === 2 || tableType === 5) && record.location === 4 && !record.isCopy,
                icon: 'gis:layer-download',
                popConfirm: {
                  placement: 'left',
                  title: t('routes.scenes.downloadSceneConfirmE57'),
                  confirm: handleDownloadSceneE57.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
      <DownloadModal @register="registerDownloadModal" />
      <DownloadE57Modal @register="registerDownloadE57Modal" />
      <AssistantModal @register="registerAssistantModal" @success="reload" />
      <MigrateModal
        @register="registerMigrateModal"
        @success="handleMigrateSuccess"
        @cancel="handleMigrateCancel"
      />
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, computed, h, ref } from 'vue';
  import { openUrl } from '/@/utils/auth';
  import { PageWrapper } from '/@/components/Page';
  import {
    BasicTable,
    useTable,
    BasicColumn,
    FormProps,
    TableAction,
    TableImg,
  } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { Switch, Tabs } from 'ant-design-vue';
  import {
    ListApi,
    downloadSceneDataAPi,
    addDownloadNumApi,
    checkDownloadApi,
    DeleteApi,
    UpgradeToV4,
    sceneCopy,
    patchcoldStorageApi,
    generateObjFileAPI,
    updateMapShowApi,
    checkDownloadE57Api,
    downloadSceneDataE57APi,
  } from '/@/api/scene/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    downloadByUrl,
    // downloadByData,
    // downloadByBase64,
    // downloadByOnlineUrl,
  } from '/@/utils/file/download';

  import { useUserStore } from '/@/store/modules/user';
  import DownloadModal from './downloadModal.vue';
  import DownloadE57Modal from './downloadE57Modal.vue';
  import AssistantModal from './assistantModal.vue';
  import { useLocaleStore } from '/@/store/modules/locale';
  import { SceneDownloadParam } from '/@/api/scene/model';
  import { RoleEnum } from '/@/enums/roleEnum';
  import MigrateModal from './migrateModal.vue';

  const localeStore = useLocaleStore();
  console.log('localeStore', localeStore);
  const userStore = useUserStore();

  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      TableImg,
      DownloadModal,
      AssistantModal,
      PageWrapper,
      MigrateModal,
      Switch,
      DownloadE57Modal,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const roleList = userStore.roleList;
      console.log('roleList', roleList);

      const isPatchAuth = computed(() => {
        return (
          roleList.includes(RoleEnum.PLAT_ADMIN) ||
          roleList.includes(RoleEnum.SUPER) ||
          roleList.includes(RoleEnum.HOST)
        );
      });

      const { createMessage, createConfirm } = useMessage();
      const [registerDownloadModal, { openModal: openDownloadModal }] = useModal();
      const [registerDownloadE57Modal, { openModal: openDownloadE57Modal }] = useModal();
      const [registerAssistantModal, { openModal: openAssistantModal }] = useModal();
      const [registerMigrateModal, { openModal: openMigrateModal }] = useModal();
      const { t } = useI18n();
      const loading = ref(false);
      const tableType = ref<Number>(0); //0看看 、1看见、2深时
      const isJA = computed(() => localeStore.getLocale === 'ja');
      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          width: 80,
          defaultHidden: true,
        },
        // {
        //   title: 'isCopy(测试)',
        //   dataIndex: 'isCopy',
        //   ellipsis: false,
        //   width: 80,
        //   customRender: ({ record }) => {
        //     return String(record.isCopy);
        //   },
        // },
        {
          title: t('routes.scenes.sceneName'),
          dataIndex: 'sceneName',
          ellipsis: false,
          width: 120,
        },
        {
          title: t('routes.corporation.enterpriseName'),
          dataIndex: 'companyName',
          ellipsis: false,
          width: 120,
        },
        {
          title: t('routes.scenes.webSite'),
          dataIndex: 'webSite',
          ellipsis: false,
          slots: { customRender: 'link' },
          width: 180,
        },
        {
          title: t('routes.scenes.appListPicUrl'),
          dataIndex: 'thumb',
          ellipsis: true,
          slots: { customRender: 'cover' },
          width: 150,
        },
        {
          title: t('routes.scenes.shootUserName'),
          dataIndex: 'userName',
          ellipsis: false,
          width: 150,
        },
        {
          title: t('routes.scenes.childName'),
          dataIndex: 'childName',
          width: 120,
        },
        {
          title: t('routes.scenes.viewCount'),
          dataIndex: 'viewCount',
          width: 100,
        },
        {
          title: t('routes.scenes.createTime'),
          dataIndex: 'createTime',
          ellipsis: false,
          width: 140,
        },

        {
          title: t('routes.scenes.num'),
          dataIndex: 'num',
          width: 180,
        },
        {
          title: t('routes.scenes.showMap'),
          dataIndex: 'mapShow',
          slots: { customRender: 'mapShow' },
          ifShow: () => {
            console.log('tableType', tableType.value);
            return ![0, 1].includes(Number(tableType.value));
          },
          width: 180,
        },
        {
          title: t('routes.archive.sceneStatus'),
          dataIndex: 'payStatus',
          slots: { customRender: 'payStatus' },
          width: 100,
        },

        // {
        //   title: t('routes.scenes.process'),
        //   dataIndex: '',
        //   width: 180,
        //   slots: { customRender: 'process' },
        //   ifShow: false,
        // },

        {
          title: t('common.operation'),
          dataIndex: '',
          slots: { customRender: 'action' },
          width: 300,
          ellipsis: false,
          fixed: 'right',
        },
      ];

      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'companyName',
            label: t('routes.corporation.enterpriseName'),
            component: 'Input',
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
          {
            field: 'sceneName',
            label: t('routes.scenes.sceneName'),
            component: 'Input',
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
          {
            field: 'childName',
            label: t('routes.scenes.childName'),
            component: 'Input',
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
        ],
      };
      const [registerTable, { reload, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
        title: t('routes.scenes.sceneList'),
        api: ListApi,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        searchInfo: { type: tableType, lang: isJA.value ? 'ja' : 'zh' },
        tableSetting: { fullScreen: true },
        clickToRowSelect: false,
        showIndexColumn: false,
        rowKey: 'num',
        beforeFetch: (T) => {
          loading.value = true;
          return T;
        },
        afterFetch: (T) => {
          loading.value = false;
          return T;
        },
      });
      async function handleGenerate(record: Recordable) {
        if (record.isObj === 1) {
          createConfirm({
            iconType: 'warning',
            title: () => h('span', t('routes.scenes.creatobj')),
            content: () => h('span', t('routes.scenes.objTips.coverData')),
            onOk: async () => {
              await generateObjFileAPI({ num: record.num });
              createMessage.success(t('common.optSuccess'));
              reload();
            },
          });
        } else {
          await generateObjFileAPI({ num: record.num });
          createMessage.success(t('common.optSuccess'));
          reload();
        }

        // let toastText =
        //   buildObjStatus == 2
        //     ? t('routes.scenes.objTips.Modifying')
        //     : buildObjStatus == 1
        //     ? t('routes.scenes.objTips.coverData')
        //     : t('routes.scenes.objTips.updateSuccess');
        // console.log('buildObjStatus', data);
        // if (data.code === 200) {
        //   createConfirm({
        //     iconType: 'warning',
        //     title: () => h('span', t('routes.scenes.creatobj')),
        //     content: () => h('span', toastText),
        //     onOk: async () => {
        //       if (buildObjStatus !== 2) {
        //         await buildSceneObj({ id: record.id });
        //       }

        //     },
        //   });
        // } else {
        //   createMessage.error(t(`apiCode.errCode${data.code}`));
        // }
      }
      function handleLivestream(item) {
        let url = item.webSite;
        let page = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.html'));
        url = url.replace(page, 'rtc-live');
        window.open(url.replace('http://', 'https://') + (isJA.value ? '&lang=ja' : ''), '_blank');
      }
      function handleCopy(item) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('routes.scenes.copyInfi.title')),
          content: () => h('span', t('routes.scenes.copyInfi.content')),
          onOk: async () => {
            await sceneCopy(item.num);
            createMessage.success(t('common.optSuccess'));
            reload();
          },
        });
      }
      function handleUpgrade(item) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('routes.scenes.upgradeMessg.title')),
          content: () => h('span', t('routes.scenes.upgradeMessg.text')),
          onOk: async () => {
            console.log('item', item);
            let res = await UpgradeToV4(item.num);
            console.log('res', res);
            createMessage.success(t('common.optSuccess'));
            reload();
          },
        });
      }
      async function openSceneEditor(record: Recordable) {
        try {
          const langtext = isJA.value ? 'ja' : 'zh';
          const token = userStore.getToken; //&token=${token}
          let url = record.webSite.replace('smobile', 'epc') + `&lang=${langtext}`;
          if (tableType.value == 2 || tableType.value == 5) {
            url = url + `&token=${token}`;
          }
          if (record.isUpgrade == 1) {
            url = url.replace('smg', 'epg');
          }
          openUrl(url);
        } catch (error) {
          console.log('error', error);
        }
      }
      async function handleDelete(record: Recordable) {
        console.log('DeleteApi', record);
        await DeleteApi(record.num);
        createMessage.success(t('common.optSuccess'));
        reload();
      }

      async function handleDownloadScene(record: Recordable) {
        let param: SceneDownloadParam = {
          num: record.num,
          isObj: 0,
        };
        if (tableType.value == 4 || tableType.value == 6) {
          param.isObj = 1;
        }
        await addDownloadNumApi(param);
        // SceneDownloadModel
        const checker = await checkDownloadApi(param);
        if (checker.downloadStatus < 3) {
          const res = await downloadSceneDataAPi(param);
          console.log('res', res);
          openDownloadModal(true, { ...record, isObj: param.isObj });
        } else {
          downloadByUrl({
            url: checker.downloadUrl,
            target: '_self',
          });
        }
      }
      function changeTable(val: Number) {
        tableType.value = val;
        clearSelectedRowKeys();
        reload();
      }

      function needAssistant(record: Recordable) {
        // console.log('record', record);
        openAssistantModal(true, { ...record });
      }
      function handlePatchSelect() {
        const keys = getSelectRowKeys();
        if (keys.length > 0) {
          createConfirm({
            iconType: 'warning',
            title: () => h('span', t('routes.archive.patchArchive')),
            content: () => h('span', t('common.isConfirm')),
            onOk: async () => {
              try {
                await patchcoldStorageApi({
                  numList: keys,
                });
                createMessage.success(t('common.optSuccess'));
                clearSelectedRowKeys();
                reload();
              } catch (error) {}
            },
          });
        } else {
          createMessage.info(t('modal.atLeastOne'));
        }
      }
      function getCheckboxProps(record: any) {
        return {
          disabled: record.payStatus === -2,
        };
      }
      function handleFetchSuccess(item) {
        console.log('handleFetchSuccess', item);
      }
      const handleMigrate = (record: Recordable) => {
        try {
          console.log('record', record);
          openMigrateModal(true, {
            tableType: tableType.value,
            sceneNum: [record.num],
          });
        } catch (error) {
          console.log('error', error);
        }
      };
      const handleMigrateSuccess = () => {
        reload();
      };
      const handleMigrateCancel = () => {
        reload();
      };
      async function handleUpdateSwitch(record: any) {
        const res = await updateMapShowApi({
          num: record.num,
          mapShow: record.mapShow,
        });
        console.log('res', res);
        if (res.code === 0) {
          setTimeout(reload, 100);
        } else {
          if (res.code === 5031) {
            createMessage.error(t('apiCode.errCode5031'));
          }
        }
        setTimeout(reload, 500);
      }

      async function handleDownloadSceneE57(record: Recordable) {
        let param: SceneDownloadParam = {
          num: record.num,
        };
        const checker = await checkDownloadE57Api(param);
        console.log('checker', checker);
        if (checker.downloadStatus < 3) {
          const res = await downloadSceneDataE57APi(param);
          console.log('res', res);
          openDownloadE57Modal(true, { ...record });
        } else {
          downloadByUrl({
            url: checker.downloadUrl,
            target: '_self',
          });
        }
      }

      return {
        reload,
        registerTable,
        createMessage,
        t,
        handleGenerate,
        openSceneEditor,
        handleDownloadScene,
        handleDelete,
        handleLivestream,
        handleUpgrade,
        registerDownloadModal,
        changeTable,
        handleCopy,
        tableType,
        loading,
        isJA,
        needAssistant,
        registerAssistantModal,
        handlePatchSelect,
        getCheckboxProps,
        isPatchAuth,
        handleFetchSuccess,
        registerMigrateModal,
        handleMigrate,
        handleMigrateSuccess,
        handleMigrateCancel,
        handleUpdateSwitch,
        handleDownloadSceneE57,
        registerDownloadE57Modal,
      };
    },
  });
</script>

<style scoped>
  :deep(.ant-table-tbody > tr:has(.ant-checkbox-disabled) > td) {
    opacity: 0.5;
    user-select: none;
    pointer-events: none;
  }
  :deep(.vben-basic-table-action.left) {
    justify-content: center;
  }
</style>
