<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" :columns="columnsFun">
          <template #toolbar>
            <a-button type="primary"  @click="handleAdd" v-if="getCheckPerm('diversity-Add') && tableType == 0"> 新增</a-button>
          </template>

          <template #href="{ record }">
            <a
              v-if="record.fusionTitle"
              target="_blank"
              :title="record.fusionTitle"
              :href="`/code/index.html?caseId=${record.fusionId}#/show`"
              >{{ record.fusionTitle }}</a
            >
            <span v-else>-</span>
          </template>
          <template #action="{ record }">
            <TableAction
              stopButtonPropagation
              :actions="[
                {
                  label: '迁移',
                  ifShow: getTypeCheckPerm('diversity-move') && tableType == 0,
                  onClick: handleMove.bind(null, record),
                },
                {
                  label: '编辑',
                  ifShow: getTypeCheckPerm('diversity-edit'),
                  disabled: !record.editAuth,
                  onClick: handlegotoEdit.bind(null, record),
                },
                {
                  label: '权限',
                  disabled: !record.isAuth,
                  ifShow: getTypeCheckPerm('diversity-powers'),
                  onClick: handlePowers.bind(null, record),
                },
                //{
                //  label: '下载',
                //  ifShow: getTypeCheckPerm('diversity-download') && !record.isOpen,
                //  disabled:  tableType == 1,
                //  onClick: createConfirmDownload.bind(null, record),
                //},
                {
                  label: '删除',
                  ifShow: getTypeCheckPerm('diversity-delete') && !record.isOpen && tableType == 0,
                  disabled: !record.editAuth,
                  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" @update="reload" />
      <AddModal @register="registerAddModal" @update="reload" />
      <PowersModal @register="registerPowersModal" />
    </PageWrapper>
  </div>
</template>
<script lang="ts">
  import { defineComponent, h, computed, ref, onMounted } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    FormProps,
  } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import AddModal from './addCaseModal.vue'
  import DownLoadModal from './DownLoadModal.vue';
  import MoveModal from './MoveModal.vue';
  import PowersModal from '/@/views/productOperation/modal/PowersModal.vue';
  import { Time } from '/@/components/Time';
  import { Descriptions, Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import {
    caseFusionList,
    caseFusionAdd,
    caseFusionDel,
  } from '/@/api/operate/case';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    components: {
      DownLoadModal,
      MoveModal,
      PowersModal,
      BasicTable,
      TableAction,
      PageWrapper,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      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<number>(0); //0看看 、1看见、2深时
      const columns = () => [
        {
          title: '标题',
          dataIndex: 'sceneName',
          fixed: 'left',
          ellipsis: true,
          slots: { customRender: 'href' },
          // resizable: true,
          width: 300,
        },
        // {
        //   title: '所属案件',
        //   dataIndex: 'caseTitle',
        //   slots: { customRender: 'caseTitle' },
        //   ellipsis: true,
        //   width: 140,
        // },
        {
          title: '人员编号',
          dataIndex: 'ryNo',
          ellipsis: true,
          width: 140,
        },
        {
          title: '姓名',
          dataIndex: 'ryNickName',
          ellipsis: true,
          width: 140,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 150,
          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: 230,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        schemas: [
          {
            field: 'fusionTitle',
            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, setPagination, getColumns, setColumns }] = useTable({
        api: caseFusionList,
        title: `多元融合列表`,
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        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: 'fusionId',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      function changeTable(val: number) {
        tableType.value = val;
        setColumns(columns())
        setPagination({ current: 1 });
        reload();
      }
      async function handleAdd() {
        console.log('addPowes', getColumns(), columns());
        let res = await caseFusionAdd({});
        console.log('handleAdd', res);
        handlegotoEdit(res)
      }
      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 () => {
          caseFusionDel({ fusionId: record.fusionId }).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);
          }
        });
      }
      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 = `/code/index.html?caseId=${record.fusionId}#/fuseEdit/merge`;
        window.open(url);
      }
      function handlePowers(record: Recordable) {
        console.log('handlePowers', record);
        openPowersModal(true, {
          ...record,
          sourceType: 'fusion',
          caseId: undefined,
          tableType: tableType.value,
        });
        setTimeout(() => {
          setColumns(columns())
        }, 2000)
      }
      onMounted(() => {
        setColumns(columns())
      });
      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,
        columnsFun: columns(),
        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;
            }
          }
        }
      }
    }
    :deep(.ant-table-cell-content){
      display: block !important;
    }
  }
  // .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>
