<template>
  <div class="scren">
    <PageWrapper contentBackground>
      <template #footer>
        <a-tabs v-model:activeKey="tableType" @change="changeTable">
          <Tabs.TabPane :key="0" tab="案件管理" :disabled="loading" />
          <Tabs.TabPane :key="1" tab="案件共享" :disabled="loading" />
        </a-tabs
      ></template>
      <div class="desc-wrap-BasicTable">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <a-button type="primary"  @click="handleAdd" v-if="getCheckPerm('case-Add') && tableType == 0"> 新增案件</a-button>
          </template>

          <template #href="{ record }">
            <a
              v-if="record.caseTitle"
              target="_blank"
              :title="record.caseTitle"
              :href="`/code/index.html?caseId=${record.caseId}#/show`"
              >{{ record.caseTitle }}</a
            >
            <span v-else>-</span>
          </template>
          <template #action="{ record }">
            <TableAction
              stopButtonPropagation
              :actions="[
                {
                  label: '编辑',
                  disabled: tableType == 1 && !record.isEdit,
                  ifShow: getTypeCheckPerm('case-edit'),
                  onClick: handlegotoEdit.bind(null, record),
                },
                {
                  label: '权限',
                  disabled: tableType == 1 && !record.isAuth,
                  ifShow: getTypeCheckPerm('case-powers'),
                  onClick: handlePowers.bind(null, record),
                },
                {
                  label: '下载',
                  ifShow: getTypeCheckPerm('case-download') && !record.isOpen,
                  //  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',
                  disabled:  tableType == 1,
                  onClick: createConfirmDownload.bind(null, record),
                },
                {
                  label: '删除',
                  ifShow: getTypeCheckPerm('case-delete') && !record.isOpen,
                  //icon: 'ic:outline-delete-outline',
                  disabled: tableType == 1,
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
      </div>
      <DownLoadModal
        :downloadOption="downloadOption"
        @cancel="afterClose"
        @register="registerDownModal"
        @update="reload"
        cancelText="取消下载"
        okText="下载"
        @cancelDownload="cancelDownload"
        :okButtonProps="{ disabled: canDownload }"
      />
      <MoveModal @register="registerMoveModal" />
      <AddModal @register="registerAddModal"  @update="reload"/>
      <PowersModal @register="registerPowersModal" />
    </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 AddModal from './addCaseModal.vue'
  import DownLoadModal from './DownLoadModal.vue';
  import MoveModal from '/@/views/productOperation/modal/MoveModal.vue';
  import PowersModal from '/@/views/productOperation/modal/PowersModal.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,
    caseCheckDown,
    downloadProcess,
    sceneCopy,
    rebuildScene,
    buildSceneObj,
    sceneDetail,
    sceneCount,
    caseDelApi,
    caseListApi,
    caseProcess,
    caseDown,
  } 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,
      BasicTable,
      TableAction,
      PageWrapper,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      QrCode,
      AddModal,
      // 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 columns: BasicColumn[] = [
        {
          title: '标题',
          dataIndex: 'sceneName',
          ellipsis: true,
          slots: { customRender: 'href' },
          resizable: true,
          minWidth: 150,
          width: 300,
        },
        // {
        //   title: '场景码',
        //   dataIndex: 'num',
        //   ellipsis: true,
        //   width: 180,
        // },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 230,
          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: 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: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 400,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        schemas: [
          {
            field: 'caseTitle',
            label: '案件名称',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
        ],
      };
      function cancelDownload() {
        downloadOption.value = {};
      }
      const [registerAddModal, { openModal: openAddModal }] = useModal();
      const [registerDownModal, { openModal: openDownModal }] = useModal();
      const [registerMoveModal, { openModal: openMoveModal }] = useModal();
      const [registerPowersModal, { openModal: openPowersModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        api: caseListApi,
        title: ``,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        searchInfo: { isShare: tableType },
        useSearchForm: true,
        formConfig: searchForm,
        showIndexColumn: false,
        showTableSetting: true,
        beforeFetch: (T) => {
          loading.value = true;
          return T;
        },
        afterFetch: (T) => {
          loading.value = false;
          return T;
        },
        rowKey: 'caseId',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },               
        canResize: true,
      });
      function changeTable(val: string) {
        tableType.value = val;
        reload();
      }
      function handleAdd() {
        openAddModal(true, {})
        // router.push({ path: '/scene/add' });
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: '复制场景',
          content: '确定要复制场景吗？',
          onOk: async () => {
            sceneCopy({ num: record.num }).then(() => {
              message.success({
                content: '复制成功',
              });
              reload();
            });
          },
        });
      }
      async function handleDelete(record: Recordable) {
        createConfirm({
          title: '删除',
          content: '确定要删除吗？',
          onOk: async () => {
          caseDelApi({ caseId: record.caseId }).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 createConfirmDownload(record: Recordable) {
        createConfirm({
          title: '提示',
          okText: '继续',
          content: '案件资源过大会导致离线包下载失败，请尽可能缩小案件资源后再下载。',
          onOk: async () => {
            handleDownload(record)
          },
        });
      }

      function handleDownload(record: Recordable) {
        console.log('handleDownload', record, canDownload.value);
        canDownload.value = true;
        let isObj = tableType.value == 5 || tableType.value == 7 ? 1 : 0;
        caseCheckDown({ caseId: record.caseId }).then((res) => {
          console.log(res);
          if (res.downloadStatus != 3) {
            // 未下载过，需要打包
            caseDown({ caseId: record.caseId }).then((res) => {
              console.log(res);
              openDownModal(true, {
                ...record,
              });
              if (res.downloadStatus == 1) {
                if (timer.value) {
                  afterClose();
                }
                timer.value = setInterval(() => {
                  caseProcess({ caseId: record.caseId, }).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) {
        window.open(`/mix3d/#/home/${record.caseId}`);
        // let url = record.webSite.replace('smg', 'epg');
        // if (!record.editAuthTime || (record.editAuthTime && dayjs() < dayjs(record.editAuthTime))) {
        //   window.open(url);
        // } else {
        //   createMessage.error('编辑权限已过期');
        // }
      }
      function handlePowers(record: Recordable) {
        openPowersModal(true, {
          ...record,
        });
      }
      onMounted(() => {
      });
      return {
        registerTable,
        registerPowersModal,
        handleDelete,
        handleCopy,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        loading,
        changeTable,
        t,
        openDownModal,
        registerDownModal,
        registerMoveModal,
        registerAddModal,
        afterClose,
        timer,
        canDownload,
        downloadOption,
        cancelDownload,
        handleGenerate,
        getTypeCheckPerm,
        handlegotoEdit,
        handlePowers,
        userInfo,
        handleAdd,
        reload,
        getCheckPerm,
        createConfirmDownload,
      };
    },
  });
</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>
