<template>
  <div class="scren">
    <div class="noScene" v-if="qrCodeUrl.show">
      <div class="noScene-content">
        <p>您还没有场景，请使用手机扫二维码安装App后连接相机拍摄后上传</p>
        <div class="codelist">
          <div class="codediv">
            <QrCode
              :value="qrCodeUrl.android"
              class="enter-x flex justify-center xl:justify-start"
              :width="128"
            />
            <div class="codetext">
              <Icon icon="uiw:android" :size="20" />
              Android
            </div>
          </div>
          <div class="codediv">
            <QrCode
              :value="qrCodeUrl.ios"
              class="enter-x flex justify-center xl:justify-start"
              :width="128"
            />
            <div class="codetext">
              <Icon icon="ic:twotone-apple" :size="20" />
              iOS
            </div>
          </div>
        </div>
      </div>
    </div>
    <PageWrapper v-else 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="3" tab="四维双目Lite" :disabled="loading"/> 
        <a-tab-pane :key="4" tab="四维全景" :disabled="loading"/>  -->
          -->
          <!-- <Tabs.TabPane :key="1" tab="四维看见" :disabled="loading" />
          <Tabs.TabPane :key="2" tab="深时点云场景" :disabled="loading" />
          <Tabs.TabPane :key="5" tab="深时Mesh场景" :disabled="loading" />
          <Tabs.TabPane :key="6" tab="深光点云场景" :disabled="loading" />
          <Tabs.TabPane :key="7" tab="深光Mesh场景" :disabled="loading" />  -->
        </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.status == 1 || (record.status == -2 && record.payStatus == 1)"
              target="_blank"
              :title="record.sceneName"
              :href="record.webSite"
              >{{ record.sceneName }}</a
            >
            <span v-else-if="record.sceneName">{{ record.sceneName }}</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') && tableType != 3 && record.editAuth,
                  onClick: handlegotoEdit.bind(null, record),
                },
                {
                  label: '权限',
                  disabled: !(record.status == 1 || record.status == -2) || !record.isAuth,
                  ifShow: getTypeCheckPerm('scenes-powers'),
                  onClick: handlePowers.bind(null, record),
                },
                {
                  label: '迁移',
                  disabled: !(record.status == 1 || record.status == -2),
                  ifShow:
                    getTypeCheckPerm('scenes-move') &&
                    tableType != 3 &&
                    (record.userName == userInfo.userName ||
                      userInfo.roleId == 1 ||
                      userInfo.roleId == 45 ||
                      userInfo.roleId == 48),
                  onClick: handleMove.bind(null, record),
                },
                {
                  label: '下载',
                  ifShow:
                    getTypeCheckPerm('scenes-download') &&
                    tableType != 3 &&
                    (record.userName == userInfo.userName ||
                      userInfo.roleId == 1 ||
                      userInfo.roleId == 45 ||
                      userInfo.roleId == 48),
                  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 &&
                    (userInfo.roleId == 1 || userInfo.roleId == 45 || userInfo.roleId == 48),
                  popConfirm: {
                    title: '是否重算？',
                    confirm: handleReset.bind(null, record),
                  },
                },
                {
                  label: '复制',
                  disabled: !(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                  ifShow:
                    getTypeCheckPerm('scenes-copy') &&
                    tableType != 3 &&
                    (record.userName == userInfo.userName ||
                      userInfo.roleId == 1 ||
                      userInfo.roleId == 45 ||
                      userInfo.roleId == 48),
                  onClick: handleCopy.bind(null, record),
                },
                {
                  label: '生成 obj',
                  ifShow:
                    getTypeCheckPerm('scenes-creatobj') &&
                    record.status == -2 &&
                    (tableType == 2 || tableType == 6) &&
                    (record.userName == userInfo.userName ||
                      userInfo.roleId == 1 ||
                      userInfo.roleId == 45 ||
                      userInfo.roleId == 48),
                  onClick: handleGenerate.bind(null, record),
                },
                {
                  label: '删除',
                  //icon: 'ic:outline-delete-outline',
                  color: 'error',
                  ifShow:
                    getTypeCheckPerm('scenes-delete') &&
                    (record.userName == userInfo.userName ||
                      userInfo.roleId == 1 ||
                      userInfo.roleId == 45 ||
                      userInfo.roleId == 48),
                  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" />
      <PowersModal @register="registerPowersModal" />
      <caseListModal @register="registerCaseListModal" />
    </PageWrapper>
  </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 DownLoadModal from './modal/DownLoadModal.vue';
  import MoveModal from './modal/MoveModal.vue';
  import PowersModal from './modal/PowersModal.vue';
  import caseListModal from './modal/caseListModal.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,
    buildSceneObj,
    sceneDetail,
    sceneCount,
    getCaseByNum,
  } from '/@/api/operate';
  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,
      caseListModal,
      BasicTable,
      TableAction,
      PageWrapper,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      QrCode,
      Icon,
      // 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>(0); //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: 'sceneName',
          ellipsis: true,
          slots: { customRender: 'href' },
          resizable: true,
          minWidth: 150,
          width: 150,
        },
        {
          title: '人员编号',
          dataIndex: 'userName',
          width: 100,
        },
        {
          title: t('routes.staff.userName'),
          dataIndex: 'nickName',
          width: 100,
          customRender: ({ record }) => {
            return record.nickName || '-';
          },
        },
        {
          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: 'type',
          defaultHidden: true,
          width: 120,
          customRender: ({ record }) => {
            let str;
            switch (record.type) {
              case 0:
                str = '四维现勘 Kankan';
                break;
              case 1:
                str = '四维现勘 Minion';
                break;
              case 2:
                str = '四维现勘 Mega/点云';
                break;
              case 5:
                str = '四维现勘 Mega';
                break;
              case 6:
                str = '四维现勘 Meta/点云';
                break;
              case 7:
                str = '四维现勘 Meta';
                break;
              case 8:
                str = '四维现勘 PanoX';
                break;
            }
            return str;
          },
        },
        {
          title: '场景码',
          dataIndex: 'num',
          ellipsis: true,
          width: 180,
          defaultHidden: true,
        },
        {
          title: '拍摄时间',
          dataIndex: 'createTime',
          width: 180,
          customRender: ({ record }) => {
            return (
              record.createTime &&
              h(Time, {
                value: record.createTime,
                mode: 'datetime',
              })
            );
          },
        },
        {
          title: '是否复制',
          dataIndex: 'isCopy',
          width: 80,
          defaultHidden: true,
          customRender: ({ record }) => {
            return record.isCopy ? '是' : '否';
          },
        },
        {
          title: '计算完成时间',
          dataIndex: 'amount',
          width: 180,
          customRender: ({ record }) => {
            return (
              (record.algorithmTime &&
                h(Time, {
                  value: record.algorithmTime,
                  mode: 'datetime',
                })) ||
              '-'
            );
          },
        },
        {
          title: 'SN码',
          dataIndex: 'snCode',
          defaultHidden: true,
          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: 'copyTime',
          width: 180,
          defaultHidden: true,
          customRender: ({ record }) => {
            return record.copyTime
              ? h(Time, {
                  value: record.copyTime,
                  mode: 'datetime',
                })
              : '-';
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          // fixed: 'right',
          flag: 'ACTION',
          width: 400,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 80,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        schemas: [
          {
            field: 'sceneName',
            label: '场景标题',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'ryNo',
            label: '人员编号',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
          {
            field: 'num',
            label: '场景码',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
          {
            field: 'userName',
            label: 'SN 码',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'type',
            label: '相机类型',
            component: 'Select',
            defaultValue: '7',
            componentProps: {
              // allowClear: false,
              options: [
                {
                  label: '四维现勘 Kankan',
                  value: '0',
                  key: '0',
                },
                {
                  label: '四维现勘 Minion',
                  value: '1',
                  key: '1',
                },
                {
                  label: '四维现勘 Mega/点云',
                  value: '2',
                  key: '2',
                },
                {
                  label: '四维现勘 Mega',
                  value: '5',
                  key: '5',
                },
                {
                  label: '四维现勘 Meta/点云',
                  value: '6',
                  key: '6',
                },
                {
                  label: '四维现勘 Meta',
                  value: '7',
                  key: '7',
                },
                {
                  label: '四维现勘 PanoX',
                  value: '8',
                  key: '8',
                },
              ],
            },
            colProps: {
              xl: 6,
              xxl: 6,
            },
          },
        ],
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [registerPowersModal, { openModal: openPowersModal }] = useModal();
      const [registerCaseListModal, { openModal: openCaseListModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        api: operateSceneList,
        title: `场景列表`,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { sceneType: 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 () => {
        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;
        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);
      }
      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) {
        let url = record.webSite.replace('smg', 'epg');
        if (!record.editAuthTime || (record.editAuthTime && dayjs() < dayjs(record.editAuthTime))) {
          window.open(url);
        } else {
          createMessage.error('编辑权限已过期');
        }
      }
      async function handlePowers(record: Recordable) {
        let res = await getCaseByNum({ num: record.num });
        if (res && res.length) {
          openCaseListModal(true, {
            list: res,
          });
        } else {
          openPowersModal(true, {
            ...record,
          });
        }
      }
      onMounted(() => {
        sceneCount({}).then((res) => {
          console.log('res', res);
          if (res == 0) {
            qrCodeUrl.value.show = true;
          }
        });
        fetch('http://4dkk.4dage.com/apps/customApp/udrive_preview/Android/version.json')
          .then((response) => response.json())
          .then((data) => {
            qrCodeUrl.value.android = data.link;
          });

        fetch('http://4dkk.4dage.com/apps/customApp/udrive_preview/iOS/version.json')
          .then((response) => response.json())
          .then((data) => {
            qrCodeUrl.value.ios = data.link;
          });
      });
      return {
        registerTable,
        registerPowersModal,
        registerCaseListModal,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        loading,
        changeTable,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        handleGenerate,
        getTypeCheckPerm,
        handlegotoEdit,
        handlePowers,
        userInfo,
        qrCodeUrl,
      };
    },
  });
</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>
