<template>
  <PageWrapper contentBackground>
    <template #footer>
      <a-tabs v-model:activeKey="tableType" @change="changeTable">
        <a-tab-pane :key="0" tab="四维看看" />
        <a-tab-pane :key="1" tab="四维看见" />
        <a-tab-pane :key="2" tab="四维深时" />
        <a-tab-pane :key="3" tab="四维双目Lite" /> </a-tabs
    ></template>
    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <!-- <a-button type="primary" @click="exportExcel"> 导出1</a-button> -->
        </template>

        <template #href="{ record }">
          <a v-if="record.sceneName" target="_blank" :href="record.thumb">{{record.sceneName}}</a>
          <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-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,
                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 @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 {
    operateSceneList,
    sceneMove,
    sceneDelete,
    sceneReset,
    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';
  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 { createMessage, createConfirm } = useMessage();
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const tableType = ref<Recordable>(0); //0看看 、1看见、2深时
      const tabList = ref<Array>(['四维看看', '四维看见', '四维深时', '四维双目Lite']);
      const columns: BasicColumn[] = [
        {
          title: '场景标题',
          dataIndex: 'sceneName',
          slots: { customRender: 'href' },
          width: 150,
        },
        {
          title: '场景码',
          dataIndex: 'num',
          ellipsis: true,
          width: 180,
        },
        {
          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.algorithmTime &&
              h(Time, {
                value: record.algorithmTime,
                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: 'status',
          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 == -2 ? '封存' : 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: { type: tableType },
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        rowKey: 'num',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      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: '复制成功',
                });
              })
          },
        });
      }
      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,canDownload.value);
        canDownload.value = true;
        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 {
            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 getTypeCheckPerm(val){
        let myType = tableType.value
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`)
      }
      return {
        registerTable,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        changeTable,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        getTypeCheckPerm,
      };
    },
  });
</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>
