<template>
  <div class="scren">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleGrounping"> 分组管理</a-button>
        <a-button type="primary" @click="uploadModal(true, {})"> 上传</a-button>
      </template>

      <template #href="{ record }">
        <a
          v-if="record.fileUrl"
          target="_blank"
          :title="record.name"
          @click="floadileUrl(record)">
          {{ record.name }}</a
        >
        <span v-else-if="record.name">{{ record.name }}</span>
        <span v-else>-</span>
      </template>
      <template #action="{ record }">
        <TableAction
          v-if="!record.isShare"
          stopButtonPropagation
          :actions="[
            {
              label: '编辑',
              disabled: !(record.status == 1 || record.status == -2),
              ifShow: getTypeCheckPerm('scenes-edit'),
              onClick: handlegotoEdit.bind(null, record),
            },
            {
              label: '删除',
              //icon: 'ic:outline-delete-outline',
              color: 'error',
              ifShow: getTypeCheckPerm('scenes-delete'),
              onClick: handleDelete.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <grouping @register="registerGroupingModal" @update="reload" />
    <uploadModal @register="registeruploadModal" @update="reload" />
    <detailModal @register="registerdetailModal" @update="reload" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, h, computed, toRefs, ref, onMounted } from 'vue';
  import Icon from '/@/components/Icon/index';
  import dayjs from 'dayjs';
  import { QrCode } from '/@/components/Qrcode/index';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  // import { PageWrapper } from '/@/components/Page';
  import detailModal from './modal/detailModal.vue';
  import uploadModal from './modal/uploadModal.vue';
  import grouping from './modal/grouping.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 { mediaList, getByKey, dictFiledel } from '/@/api/media';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useUserStore } from '/@/store/modules/user';
  import { func } from 'vue-types';
  export default defineComponent({
    components: {
      // DownLoadModal,
      // MoveModal,
      // PowersModal,
      uploadModal,
      detailModal,
      grouping,
      BasicTable,
      TableAction,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,

      // Tabs,
      [Tabs.name]: Tabs,
      // [Tabs.TabPane?.name]: Tabs.TabPane,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const userInfo = computed(() => userStore.getUserInfo);
      const permissionStore = usePermissionStore();
      const { getCheckPerm } = permissionStore;
      const loading = ref(false);
      const tableType = ref<Recordable>(1); //0看看 、1看见、2深时
      const tabList = ref<Array>(['四维看看', '四维看见', '四维深时', '四维双目Lite']);
      const qrCodeUrl = ref({
        show: false,
        ios: 'http://fir.4dage.com/jmjjios?release_id=671efd5d23389f402726113c',
        android: 'http://fir.4dage.com/zpnv?release_id=66d18456f945485fa604e3fc',
      });
      const columns: BasicColumn[] = [
        {
          title: '名称',
          dataIndex: 'name',
          ellipsis: true,
          slots: { customRender: 'href' },
          resizable: true,
          minWidth: 150,
          width: 150,
        },
        {
          title: '文件类型',
          dataIndex: 'fileTypeStr',
          width: 80
        },
        {
          title: '文件格式',
          dataIndex: 'fileFormat',
          width: 100,
          customRender: ({ record }) => {
            return record.fileFormat || '-';
          },
        },
        {
          title: '分组',
          dataIndex: 'dictName',
          width: 80,
        },
        // {
        //   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: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 80,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 50,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        schemas: [
          {
            field: 'name',
            label: '名称',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
          {
            field: 'fileType',
            label: '类型',
            component: 'Select',
            componentProps: {
              labelWidth: 50,
              options: [
                {
                  label: '图片',
                  value: '0',
                  key: '0',
                },
                {
                  label: '视频',
                  value: '1',
                  key: '1',
                },
                {
                  label: '音频',
                  value: '2',
                  key: '2',
                },
                {
                  label: '模型',
                  value: '3',
                  key: '3',
                },
                {
                  label: '其他',
                  value: '4',
                  key: '4',
                }
              ],
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
          {
            field: 'dictId',
            label: '分组',
            component: 'ApiSelect',
            componentProps: {
              api: getByKey,
              labelField: 'dictName',
              valueField: 'id',
              params: {
                type: 1,
              },
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
        ],
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerGroupingModal, { openModal: openGroupingDownModal }] = useModal();
      const [registeruploadModal, { openModal: uploadModal }] = useModal();
      const [registerdetailModal, { openModal: detailModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        api: mediaList,
        title: ``,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { type: tableType },
        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: true,
      });
      function changeTable(val: string) {
        tableType.value = val;
        reload();
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '确定要复制场景吗？',
          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 () => {
            dictFiledel({ id: record.id }).then(() => {
              message.success({
                content: '删除成功',
              });
              reload();
            });
          },
        });
      }
      function handleGrounping(record: Recordable) {
        openGroupingDownModal(true, record);
      }
      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;
        let isObj = tableType.value == 5 || tableType.value == 7 ? 1 : 0;
        checkDownLoad({ num: record.num, isObj }).then((res) => {
          console.log(res);
          if (res.downloadStatus != 3) {
            // 未下载过，需要打包
            sceneDownload({ num: record.num, isObj }).then((res) => {
              console.log(res);
              openDownModal(true, {
                ...record,
              });
              if (res.downloadStatus == 1) {
                if (timer.value) {
                  afterClose();
                }
                timer.value = setInterval(() => {
                  downloadProcess({ num: record.num, isObj }).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 handleEdit(record: Recordable) {
        window.open(record.thumbEdit + '&&token=' + token.value);
      }
      function exportExcel() {}
      async function handleGenerate(record: Recordable) {
        console.log('record', record);
        let data = await sceneDetail({ id: record.id });
        console.log('data', data);
        let { buildObjStatus } = data;
        let toastText =
          buildObjStatus == 2
            ? 'Mesh场景正在计算中，请耐心等待'
            : buildObjStatus == 1
            ? '重新生成Mesh场景将覆盖现有场景信息，计算过程中Mesh场景无法打开，确定要重新生成吗？'
            : '生成obj需要较长时间，请耐心等待';
        // if (data.code === 200) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '生成 obj'),
          content: () => h('span', toastText),
          onOk: async () => {
            if (buildObjStatus !== 2) {
              await buildSceneObj({ id: record.id, sceneNum: record.num });
            }
            createMessage.success(t('common.optSuccess'));
            reload();
          },
        });
        // } else {
        //   createMessage.error(t(`apiCode.errCode${data.code}`));
        // }
      }
      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}`);
      }
      function handlegotoEdit(record: Recordable) {
        detailModal(true, {
          ...record,
        });
      }
      function handlePowers(record: Recordable) {
        openPowersModal(true, {
          ...record,
        });
      }
      function floadileUrl(record) {
        if (record.fileType == 3) {
          afterClose();
        }else{
          return window.open(record.fileUrl);
        }
      }
      onMounted(() => {});
      return {
        registerTable,
        registeruploadModal,
        registerdetailModal,
        uploadModal,
        detailModal,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        loading,
        changeTable,
        reload,
        t,
        openGroupingDownModal,
        registerGroupingModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        handleGenerate,
        getTypeCheckPerm,
        handlegotoEdit,
        handlePowers,
        userInfo,
        qrCodeUrl,
        exportExcel,
        handleGrounping,
        floadileUrl,
      };
    },
  });
</script>
<style lang="less" scoped>
  .scren {
    .noScene {
      position: absolute;
      top: calc(50% - 126px);
      width: 100%;
      text-align: center;
      &-content {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
        line-height: 22px;
        font-style: normal;
        text-transform: none;
        .codelist {
          margin-top: 36px;
          width: 424px;
          height: auto;
          display: flex;
          justify-content: space-between;
          margin: 0 auto;
          .codediv {
            font-weight: 400;
            font-size: 17px;
            color: rgba(0, 0, 0, 0.85);
            line-height: 22px;
            height: auto;
            padding: 24px;
            background: #fff;
            text-align: center;
            .codetext {
              margin-top: 10px;
            }
          }
        }
      }
    }
  }
  // .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>
