<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-tabs>
    </template>
    <div class="desc-wrap-BasicTable">
      <BasicTable
        @register="registerTable"
        ref="tableRef"
        :rowSelection="tableType == 3 ? false : rowSelection"
      >
        <template #toolbar>
          <a-button type="primary" @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.sceneName && record.thumb"
            target="_blank"
            :href="record.webSite || record.thumb"
            >{{ record.sceneName }}</a
          >
          <span v-else-if="record.sceneName">{{ record.sceneName }}</span>
          <span v-else>-</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '迁移',
                disabled: !(record.status == 1 || record.status == -2),
                ifShow: getTypeCheckPerm('scenes-move') && tableType != 3,
                onClick: handleMove.bind(null, record),
              },
              {
                label: '优先级',
                ifShow: getTypeCheckPerm('scenes-priority') && record.status == -4,
                onClick: handlePriority.bind(null, record),
              },
              {
                label: '解冻',
                disabled: !record.isColdStorage || !(record.status == 1 || record.status == -2),
                ifShow: getTypeCheckPerm('scenes-thaw'),
                onClick: handleColdStorage.bind(null, record),
              },
              {
                label: '下载',
                ifShow: getTypeCheckPerm('scenes-download') && tableType != 3,
                disabled: !(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                //icon: 'carbon:download',
                onClick: handleDownload.bind(null, record),
              },
              {
                label: '重算',
                disabled: record.status == 0 || (record.status == -2 && record.payStatus != 1),
                ifShow:
                  getTypeCheckPerm('scenes-recalculate') && tableType != 3 && record.status != -4,
                popConfirm: {
                  title: '是否重算？',
                  confirm: handleReset.bind(null, record),
                },
              },
              {
                label: '复制',
                disabled: !(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                ifShow: getTypeCheckPerm('scenes-copy') && tableType != 3,
                onClick: handleCopy.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                color: 'error',
                ifShow: getTypeCheckPerm('scenes-delete'),
                disabled: record.status == 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, unref } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableActionType,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import DownLoadModal from './modal/DownLoadModal.vue';
  import MoveModal from './modal/MoveModal.vue';
  import priorityMoadl from './modal/priorityMoadl.vue';
  import { Time } from '/@/components/Time';
  import { Icon } from '/@/components/Icon';
  import { Descriptions, Tabs, Progress, Tooltip } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import {
    operateSceneList,
    sceneMove,
    sceneDelete,
    sceneReset,
    sceneRestStore,
    sceneDownload,
    checkDownLoad,
    downloadProcess,
    sceneCopy,
    rebuildScene,
  } from '/@/api/operate';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { func } from 'vue-types';
  import { truncate } from 'fs/promises';
  import { getSchemas, getColumns } from './data';
  export default defineComponent({
    components: {
      DownLoadModal,
      MoveModal,
      BasicTable,
      TableAction,
      priorityMoadl,
      PageWrapper,
      Icon,
      Tooltip,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage, createConfirm } = useMessage();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const loading = ref(false);
      const tableRef = ref<Nullable<TableActionType>>(null);
      const tableType = ref<Number>(0); //0看看 、1看见、2深时
      const rowSelection = ref({
        type: 'checkbox',
      });
      const searchFormSs: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        actionColOptions: {
          span: 24,
        },
        schemas: getSchemas(),
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerPriority, { openModal: openPriorityModal }] = useModal();
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [
        registerTable,
        { setProps, reload, setColumns, getSelectRowKeys, clearSelectedRowKeys },
      ] = useTable({
        api: operateSceneList,
        title: `场景列表`,
        columns: getColumns(false),
        // 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,
      });
      function getTableAction() {
        const tableAction = unref(tableRef);
        if (!tableAction) {
          console.log('tableAction', tableAction, tableRef);
          throw new Error('tableAction is null');
        }
        return tableAction;
      }

      function changeTable(val: string) {
        tableType.value = val;
        setColumns(getColumns(val == 2));
        clearSelectedRowKeys();
        reload();
      }
      function handlePriority(record) {
        openPriorityModal(true, record);
      }
      function handleMoveAll() {
        let numList = getSelectRowKeys() || [];
        if (numList.length == 0) {
          return createMessage.error('请选择批量迁移的场景');
        }
        openMoveModal(true, {
          numList,
        });
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '复制场景，场景归属在原相机下。<br/>确定要复制场景吗？',
          onOk: async () => {
            sceneCopy({ num: record.num }).then(() => {
              message.success({
                content: '复制成功',
              });
              reload();
            });
          },
        });
      }
      async function handleDelete(record: Recordable) {
        console.log('handleDelete', record);
        // createConfirm({
        //   title: '删除',
        //   content: '确定要删除场景吗？',
        //   onOk: async () => {
        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,
        });
      }
      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();
                    }
                    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: '操作成功',
          });
          setTimeout(() => {
            reload();
          }, 500);
        });
      }
      function getTypeCheckPerm(val) {
        let myType = tableType.value;
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`);
      }
      return {
        registerTable,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        handleColdStorage,
        handleMoveAll,
        handlePriority,
        tableType,
        loading,
        reload,
        changeTable,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        registerPriority,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        getTypeCheckPerm,
        rowSelection,
        clearSelectedRowKeys,
      };
    },
  });
</script>
<style lang="less" scoped>
  // .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>
