<template>
  <PageWrapper contentBackground>
    <template #footer>
      <a-tabs v-model:activeKey="tableType">
        <a-tab-pane :key="0" tab="用户作品" />
        <a-tab-pane v-if="!isDev" :key="1" tab="看见全景VR" />
      </a-tabs>
    </template>
    <div class="desc-wrap-BasicTable">
      <BasicTable v-if="tableType == 0" @register="registerTable">
        <template #toolbar>
          <!-- <a-button type="primary" @click="handleMoveAll"> 批量迁移</a-button> -->
        </template>
        <template #href="{ record }">
          <a v-if="record.name" target="_blank" :href="record.share">{{ record.name }}</a>
          <span v-else>-</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '删除',
                color: 'error',
                ifShow: getCheckPerm('projects-delete'),
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleDelete.bind(null, record),
                  placement: 'topLeft',
                },
              },
            ]"
          />
        </template>
      </BasicTable>
      <BasicTable v-else @register="registerTableScene" ref="tableRef">
        <template #toolbar>
          <a-button type="primary" v-if="getTypeCheckPerm('scenes-move-batch')" @click="handleMoveAll"> 批量迁移</a-button>
        </template>
        <template #status="{ record }">
          <span v-if="record.status != '-1'">{{ record.statusString }}</span>
          <Tooltip v-else placement="right">
            <template #title>
              <span>失败原因:{{ record.buildErrorReason }}</span>
              <p>
                <span>serverPath：{{ record.dataSource }}</span>
              </p>
            </template>
            <span
              >{{ record.statusString }}
              <Icon icon="mdi:warning-octagon-outline" />
            </span>
          </Tooltip>
        </template>
        <template #href="{ record }">
          <a
            v-if="record.name"
            target="_blank"
            :href="record.webSite || record.thumb"
            >{{ record.name }}</a
          >
          <!-- <span v-else-if="record.name">{{ record.name }}</span> -->
          <span v-else>-</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '迁移',
                disabled: record.calcStatus != 1, //计算中计算失败不予迁移
                ifShow: getTypeCheckPerm('scenes-move') && tableType != 3,
                onClick: handleMove.bind(null, record),
              },
              {
                label: '优先级',
                ifShow: getTypeCheckPerm('scenes-priority') && record.calcStatus == -4,
                onClick: handlePriority.bind(null, record),
              },
              {
                label: '解冻',
                disabled: !record.isColdStorage || !record.calcStatus == 1,
                ifShow: getTypeCheckPerm('scenes-thaw'),
                onClick: handleColdStorage.bind(null, record),
              },
              {
                label: '重算',
                disabled: record.calcStatus == 0 || (record.status == 1 && record.payStatus != 1),
                ifShow: getTypeCheckPerm('scenes-recalculate') && tableType != 3,
                popConfirm: {
                  title: '是否重算？',
                  confirm: handleReset.bind(null, record),
                },
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                color: 'error',
                ifShow: getTypeCheckPerm('scenes-delete'),
                disabled: record.calcStatus == 0,
                //onClick: handleDelete.bind(null, record),
                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 @update="reload" @register="registerMoveModal" />
    <priorityMoadl
      @clearSelected="clearSelectedRowKeys"
      @update="reload"
      @register="registerPriority"
    />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, reactive, toRefs, ref, computed } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  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 { Switch } from 'ant-design-vue';
  import { overallList, overallDelete, cameraSceneList, sceneDelete } from '/@/api/operate';
  import { message } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import DownLoadModal from './modal/DownLoadModal.vue';
  import MoveModal from './modal/MoveModal.vue';
  import priorityMoadl from './modal/priorityMoadl.vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useUserStore } from '/@/store/modules/user';
  import { getquanjingSchemas, getVrColumns, getviewColumns, getviewSchemas } from './data';
  import {
    operateSceneList,
    sceneMove,
    sceneDelete,
    sceneReset,
    sceneRestStore,
    sceneDownload,
    checkDownLoad,
    downloadProcess,
    sceneCopy,
    rebuildScene,
  } from '/@/api/operate';
  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      PageWrapper,
      DownLoadModal,
      MoveModal,
      priorityMoadl,
      TableImg,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage, createConfirm } = useMessage();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const tableType = ref<Number>(0); //0看看 、1看见、2深时
      const loading = ref(false);
      const userStore = useUserStore();
      const isDev = computed(() => userStore.getSystemEnv);
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        actionColOptions: {
          span: 24,
        },
        schemas: getviewSchemas(),
      };
      const searchFormSs: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        actionColOptions: {
          span: 24,
        },
        schemas: getquanjingSchemas(),
      };
      const [registerPriority, { openModal: openPriorityModal }] = useModal();
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [
        registerTableScene,
        { reload: reload1, setColumns, getSelectRowKeys, clearSelectedRowKeys },
      ] = useTable({
        api: cameraSceneList,
        title: `全景VR列表`,
        columns: getVrColumns(),
        rowSelection: { type: 'checkbox' },
        searchInfo: { type: tableType },
        useSearchForm: true,
        formConfig: searchFormSs,
        showTableSetting: true,
        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: true,
      });
      const [registerTable, { reload: reload0 }] = useTable({
        api: overallList,
        title: '作品列表',
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: getviewColumns(),
        searchInfo: { type: 1 },
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        rowKey: 'num',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      async function handleDelete(record: Recordable) {
        console.log('handleDelete', record);
        if (tableType.value == 1) {
          sceneDelete({ num: record.num }).then(() => {
            message.success({
              content: '删除成功',
            });

            reload1();
          });
        } else {
          overallDelete({ id: record.id }).then(() => {
            message.success({
              content: '删除成功',
            });

            reload0();
          });
        }
      }

      function getTypeCheckPerm(val) {
        let myType = tableType.value;
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`);
      }
      function reload() {
        reload0();
        reload1();
      }
      function handlePriority(record) {
        openPriorityModal(true, record);
      }
      function handleMoveAll() {
        let numList = getSelectRowKeys() || [];
        if (numList.length == 0) {
          return createMessage.error('请选择批量迁移的场景');
        }
        openMoveModal(true, {
          numList,
        });
      }
      function cancelDownload() {
        downloadOption.value = {
          percent: 0,
        };
      }
      async function handleColdStorage(record: Recordable) {
        createConfirm({
          title: '删除',
          content: '确定要解冻场景吗？',
          onOk: async () => {
            sceneRestStore({ num: record.num }).then(() => {
              message.success({
                content: '已提交解冻',
              });

              reload();
            });
          },
        });
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '复制场景，场景归属在原相机下。<br/>确定要复制场景吗？',
          onOk: async () => {
            sceneCopy({ num: record.num }).then(() => {
              message.success({
                content: '复制成功',
              });
              reload();
            });
          },
        });
      }
      async function handleMove(record: Recordable) {
        openMoveModal(true, {
          num: record.num,
          sceneName: record.name,
          lable: '作品标题',
        });
      }
      let timer: null = ref(null);
      const downloadOption = ref<Object>({});
      const canDownload = ref<boolean>(true);
      function handleDownload(record: Recordable) {
        let isObj = tableType.value == 5 || tableType.value == 7 ? 1 : 0;
        let params = { num: record.num, isObj: 0 };
        if (tableType.value == 4 || tableType.value == 5 || tableType.value == 7) {
          params.isObj = isObj;
        }
        canDownload.value = true;
        checkDownLoad(params).then((res) => {
          if (res.downloadStatus != 3) {
            // 未下载过，需要打包
            sceneDownload(params).then((res) => {
              console.log(res);
              openDownModal(true, {
                ...record,
                isObj: params.isObj,
              });
              if (res.downloadStatus == 1) {
                if (timer.value) {
                  afterClose();
                }
                timer.value = setInterval(() => {
                  downloadProcess(params).then((res) => {
                    if (res.status == '1003') {
                      createMessage.error('下载失败');
                      afterClose();
                      return;
                    }
                    if (res.percent >= 100) {
                      canDownload.value = false;
                      afterClose();
                      window.open(res.url);
                      closeModal();
                      cancelDownload();
                      return;

                    }
                    downloadOption.value = res;
                    console.log(res);
                  });
                }, 1000);
              }
            });
          } else {
            canDownload.value = false;
            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 exportExcel() {
      //   createConfirm({
      //     iconType: 'warning',
      //     title: () => h('span', '温馨提示'),
      //     content: () => h('span', '确定当前标签下的订单记录?'),
      //     onOk: async () => {
      //       // await DownExport();
      //     },
      //   });
      // }
      return {
        registerTable,
        registerTableScene,
        handleDelete,
        handleMove,
        handleDownload,
        handleReset,
        getCheckPerm,
        getTypeCheckPerm,
        tableType,
        loading,
        reload,
        handleMoveAll,
        handlePriority,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        registerPriority,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        handleColdStorage,
        handleCopy,
        clearSelectedRowKeys,
        isDev,
      };
    },
  });
</script>
