<template>
  <PageWrapper contentBackground>
    <template #footer>
      <a-tabs v-model:activeKey="tableType" @change="changeTable">
        <a-tab-pane :key="0" tab="四维看看" :disabled="loading"/>
        <a-tab-pane :key="1" tab="四维看见" :disabled="loading"/>
        <a-tab-pane :key="2" tab="深时点云场景" :disabled="loading"/>
        <a-tab-pane :key="5" tab="深时Mesh场景" :disabled="loading"/>
        <a-tab-pane :key="6" tab="深光点云场景" :disabled="loading"/>
        <a-tab-pane :key="7" tab="深光Mesh场景" :disabled="loading"/>
        <a-tab-pane :key="3" tab="四维双目Lite" :disabled="loading"/> 
        <a-tab-pane :key="4" tab="四维全景" :disabled="loading"/> 
      </a-tabs
    ></template>
    <div class="desc-wrap-BasicTable">
      <BasicTable v-if="tableType == 4" @register="registerTableViewKankan">
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '删除',
                color: 'error',
                ifShow:getTypeCheckPerm('account-productDelete'),
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleQjDelete.bind(null, record),
                  placement: 'topLeft',
                },
              },
            ]"
          />
        </template>
      </BasicTable>
      <BasicTable v-else @register="registerTable">
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '迁移',
                ifShow:getTypeCheckPerm('account-productTransfer'),
                disabled:!(record.status == 1 || record.status == -2),
                onClick: handleMove.bind(null, record),
              },
              {
                label: '解冻',
                disabled: !record.isColdStorage || !(record.status == 1 || record.status == -2),
                ifShow: getTypeCheckPerm('scenes-thaw'),
                onClick: handleColdStorage.bind(null, record),
              },
              {
                label: '下载',
                disabled:!(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                ifShow:getTypeCheckPerm('account-productDownload'),
                onClick: handleDownload.bind(null, record),
              },
              {
                label: '重算',
                disabled: record.status == 0|| (record.status == -2 && record.payStatus != 1),
                ifShow:getTypeCheckPerm('account-productRerun'),
                popConfirm: {
                  title: '是否重算？',
                  confirm: handleReset.bind(null, record),
                },
              },
              {
                label: '复制',
                disabled:!(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                ifShow:getTypeCheckPerm('account-productCopy'),
                onClick: handleCopy.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                disabled:record.status == 0,
                ifShow:getTypeCheckPerm('account-productDelete'),
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topRight',
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <DownLoadModal
      :downloadOption="downloadOption"
      @cancel="afterClose"
      @register="registerDownModal"
      @update="reload"
      cancelText="取消下载"
      okText="下载"
      @cancelDownload="cancelDownload"
      :okButtonProps="{ disabled: canDownload }"
    />
    <MoveModal @register="registerMoveModal" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import DownLoadModal from '/@/views/productOperation/modal/DownLoadModal.vue';
  import MoveModal from '/@/views/productOperation/modal/MoveModal.vue';
  import { overallList, overallDelete } from '/@/api/operate';
  import { Descriptions, Tabs, } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { columns,searchForm,cameraScene,cameraSearchForm, quanjSearchForm } from './data'
  import { useModal } from '/@/components/Modal';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { otherInfoStore } from '/@/store/modules/other'
  import {
    operateSceneList,
    sceneMove,
    sceneDelete,
    qjsceneDelete,
    sceneReset,
    sceneRestStore,
    sceneDownload,
    checkDownLoad,
    downloadProcess,
    sceneCopy,
    rebuildScene,
  } from '/@/api/operate';
  import { message } from 'ant-design-vue';
  export default defineComponent({
    components: {
      DownLoadModal,
      MoveModal,
      BasicTable,
      TableAction,
      PageWrapper,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,

      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const { t } = useI18n();
      const otherInfo = otherInfoStore();
      const OverviewInfo = computed(() => otherInfo.getOverviewInfo);
      const { userName } = OverviewInfo.value
      const { createMessage, createConfirm } = useMessage();
      const timer = ref<NodeJS.Timeout | number | undefined | null>(null);
      const tableType = ref<number>(0); //0看看 、1看见、2深时
      const loading = ref(false);
      function cancelDownload() {
        downloadOption.value = {};
      }
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [registerTableViewKankan, { reload:ViewReload }] = useTable({
        api: overallList,
        title: `作品列表`,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: cameraScene,
        searchInfo: { type: tableType,userName },
        useSearchForm: true,
        formConfig: quanjSearchForm,
        showTableSetting: true,
        showIndexColumn:false,
        rowKey: 'num',
        beforeFetch:(T)=>{
          loading.value = true
          return T
        },
        afterFetch: (T) => {
          loading.value = false
          return T;
        },
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: false,
      });
      const [registerTable, { reload }] = useTable({
        api: operateSceneList,
        title: `场景列表`,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { type: tableType, userName},
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        showIndexColumn:false,
        beforeFetch:(T)=>{
          loading.value = true
          return T
        },
        afterFetch: (T) => {
          loading.value = false
          return T;
        },
        rowKey: 'num',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: false,
      });
      function changeTable(val: string) {
        tableType.value = val;
        reload();
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '复制场景，场景归属在原相机下。<br/>确定要复制场景吗？',
          onOk: async () => {
            sceneCopy({ num: record.num })
              .then(() => {
                message.success({
                  content: '复制成功',
                });
                reload();
              })
          },
        });
      }
      async function handleQjDelete(record: Recordable) {
        qjsceneDelete({ id: record.id })
          .then(() => {
            message.success({
              content: '删除成功',
            });
            ViewReload();
          })
      }
      async function handleDelete(record: Recordable) {
        sceneDelete({ num: record.num })
          .then(() => {
            message.success({
              content: '删除成功',
            });
            reload();
          })
      }
      async function handleColdStorage(record: Recordable) {
        createConfirm({
          title: '删除',
          content: '确定要解冻场景吗？',
          onOk: async () => {
            sceneRestStore({ num: record.num }).then(() => {
              message.success({
                content: '解冻成功',
              });

              reload();
            });
          },
        });
      }
      async function handleMove(record: Recordable) {
        openMoveModal(true, {
          ...record,
        });
      }
      // const timer = ref<NodeJS.Timeout | null = null>(null); //0看看 、1看见、2深时
      const downloadOption = ref<Object>({});
      const canDownload = ref<boolean>(true);
      function handleDownload(record: Recordable) {
        console.log('handleDownload', record);
        let isObj = tableType.value == 4?1:0
        let params = {num: record.num}
        if(tableType.value == 4 || tableType.value == 2){
          params.isObj = isObj
        }
        checkDownLoad(params).then((res) => {
          console.log(res);
          if (res.downloadStatus!= 3) {
            // 未下载过，需要打包
            sceneDownload(params).then((downres) => {
              console.log(downres);
              openDownModal(true, {
                ...record,
              });
              if (downres.downloadStatus == 1) {
                if (timer.value) {
                  afterClose();
                }
                timer.value = setInterval(() => {
                  downloadProcess(params).then((processres) => {
                    if (processres.percent >= 100) {
                      canDownload.value = false;
                      afterClose();
                    }
                    downloadOption.value = processres;
                    console.log(processres);
                  });
                }, 1000);
              }
            });
          } else {
            window.open(res.downloadUrl);
          }
        });
      }
      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}`)
      }
      return {
        registerTableViewKankan,
        registerTable,
        handleDelete,
        handleQjDelete,
        handleCopy,
        loading,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        changeTable,
        reload,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        handleColdStorage,
        cancelDownload,
        ViewReload,
        getTypeCheckPerm,
      };
    },
  });
</script>
<style lang="less" scoped>
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }
</style>
