<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="3" tab="四维双目Lite" :disabled="loading"/> </a-tabs
    ></template>
    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="back">返回</a-button>
        </template>
        
        <template #herf="{ record }">
          <a :href="record.thumb" target="_blank">{{record.sceneName}}</a>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '迁移',
                //icon: 'bx:move-horizontal',
                ifShow:getTypeCheckPerm('customer-scenes-move') && tableType != 3,
                disabled:!(record.status == 1 || record.status == -2),
                onClick: handleMove.bind(null, record),
              },
              {
                label: '下载',
                disabled:!(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                ifShow:getTypeCheckPerm('customer-scenes-download') && tableType != 3,
                //icon: 'carbon:download',
                onClick: handleDownload.bind(null, record),
              },
              {
                label: '重算',
                disabled: record.status == 0|| (record.status == -2 && record.payStatus != 1),
                ifShow:getTypeCheckPerm('customer-scenes-recalculate') && tableType != 3,
                //icon: 'bx:reset',
                popConfirm: {
                  title: '是否重算？',
                  confirm: handleReset.bind(null, record),
                },
              },
              {
                label: '复制',
                disabled:!(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                ifShow:getTypeCheckPerm('customer-scenes-copy'),
                //icon: 'akar-icons:copy',
                onClick: handleCopy.bind(null, record),
              },
              {
                label: '删除',
                //icon: 'ic:outline-delete-outline',
                disabled:record.status == 0,
                ifShow:getTypeCheckPerm('customer-scenes-delete'),
                color: 'error',
                //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 @register="registerMoveModal" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, reactive, toRefs, ref } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import DownLoadModal from './modal/DownLoadModal.vue';
  import MoveModal from './modal/MoveModal.vue';
  import { Time } from '/@/components/Time';
  import { Descriptions, Tabs, Progress } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useRouter } from 'vue-router';
  import {
    operateSceneList,
    sceneMove,
    sceneDelete,
    sceneReset,
    sceneDownload,
    checkDownLoad,
    downloadProcess,
    sceneCopy,
    rebuildScene,
  } from '/@/api/operate';
  import { message } from 'ant-design-vue';
  import { func } from 'vue-types';
  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 router = useRouter();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const loading = ref(false);
      const companyId: Number = router.currentRoute.value.params.id - 0;
      const { createMessage, createConfirm } = useMessage();
      const tableType = ref<Recordable>(0); //0看看 、1看见、2深时
      const tabList = ref<Array>(['四维看看', '四维看见', '四维深时', '四维双目Lite']);
      const columns: BasicColumn[] = [
        {
          title: '场景标题',
          dataIndex: 'sceneName',
          slots: { customRender: 'herf' },
          width: 150,
        },
        {
          title: '场景码',
          dataIndex: 'num',
          ellipsis: false,
          width: 80,
        },
        {
          title: '拍摄时间',
          dataIndex: 'createTime',
          width: 180,
          customRender: ({ record }) => {
            return (
              record.createTime &&
              h(Time, {
                value: record.createTime,
                mode: 'datetime',
              })
            );
          },
        },
        {
          title: '计算完成时间',
          dataIndex: 'amount',
          width: 180,
          customRender: ({ record }) => {
            return (
              record.createTime &&
              h(Time, {
                value: record.createTime,
                mode: 'datetime',
              })||'-'
            );
          },
        },
        {
          title: 'SN码',
          dataIndex: 'snCode',
          width: 180,
        },
        {
          title: '场景大小',
          dataIndex: 'sceneSize',
          width: 80,
          customRender: ({ record }) => {
            return (record.sceneSize && record.sceneSize != 0)?h(
              'span',
              { class: 'sceneSize' },
              Math.ceil(record.sceneSize / 1024 / 1024) + 'M',
            ):'-';
          },
        },
        {
          title: '是否复制',
          dataIndex: 'isCopy',
          width: 80,
          customRender: ({ record }) => {
            return record.isCopy ? '是' : '否';
          },
        },
        {
          title: '复制时间',
          dataIndex: 'copyTime',
          width: 180,
          customRender: ({ record }) => {
            return record.copyTime
              ? h(Time, {
                  value: record.copyTime,
                  mode: 'datetime',
                })
              : '-';
          },
        },
        {
          title: '绑定账号',
          dataIndex: 'userName',
          width: 100,
        },
        {
          title: '浏览量',
          dataIndex: 'viewCount',
          width: 80,
        },
        {
          title: '状态',
          dataIndex: 'statusString',
          width: 80,
          // customRender: ({ record }) => {
          //   let str;
          //   switch (record.status - 0) {
          //     case 0:
          //       str = '计算中';
          //       break;
          //     case 1:
          //       str = '计算成功';
          //       break;
          //     case -2:
          //       str = '计算成功';
          //       break;
          //     case -1:
          //       str = '计算失败';
          //       break;
          //   }
          //   return record.payStatus == 1 ? '封存' : str;
          // },
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 250,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'sceneName',
            label: '场景标题',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
          {
            field: 'snCode',
            label: 'SN码',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
          {
            field: 'userName',
            label: '绑定账号',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
        ],
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        api: operateSceneList,
        // title: `场景列表`,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { companyId,type:tableType },
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        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,
      });
      function changeTable(val: string) {
        tableType.value = val;
        reload();
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '复制场景，场景归属在原相机下。<br/>确定要复制场景吗？',
          onOk: async () => {
            sceneCopy({ num: record.num })
              .then((res) => {
                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 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 handleDownload(record: Recordable) {
        console.log('handleDownload', record);

        checkDownLoad({ num: record.num }).then((res) => {
          console.log(res);
          if (res.downloadStatus != 3) {
            // 未下载过，需要打包
            sceneDownload({ num: record.num }).then((res) => {
              console.log(res);
              openDownModal(true, {
                ...record,
              });
              if (res.downloadStatus == 1) {
                if (timer.value) {
                  afterClose();
                }
                timer.value = setInterval(() => {
                  downloadProcess({ num: record.num }).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 {
          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 back() {
        router.push('/customer/index');
      }
      function getTypeCheckPerm(val){
        let myType = tableType.value
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`)
      }
      return {
        getTypeCheckPerm,
        registerTable,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        loading,
        changeTable,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        back,
      };
    },
  });
</script>
<style lang="less" scoped>
  .desc-wrap-BasicTable {
    background-color: #f0f2f5;
    .vben-basic-table-form-container {
      padding: 0;
    }
  }
</style>
