<template>
  <PageWrapper contentBackground>
    <!-- <template #footer>
      <a-tabs v-model:activeKey="tableType" @change="changeTable">
        <a-tab-pane :key="0" :tab="t('routes.scene.tableType.0')" />
        <a-tab-pane :key="1" :tab="t('routes.scene.tableType.1')" />
        <a-tab-pane :key="2" :tab="t('routes.scene.tableType.2')" />
        <a-tab-pane :key="5" :tab="t('routes.scene.tableType.5')" />
        <a-tab-pane :key="6" :tab="t('routes.scene.tableType.6')" />
        <a-tab-pane :key="7" :tab="t('routes.scene.tableType.7')" />
      </a-tabs></template
    > -->
    <div class="desc-wrap-BasicTable">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" @click="handleMove"> 同步场景</a-button>
        </template>

        <template #href="{ record }">
          <a v-if="record.title && record.webSite" target="_blank" :href="record.webSite">{{
            record.title
          }}</a>
          <span v-else-if="record.title">{{ record.title }}</span>
          <span v-else>-</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: '查看',
                disabled: record.status != 1,
                onClick: handleSee.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </div>
    <DownLoadModal
      :downloadOption="downloadOption"
      @cancel="afterClose"
      @register="registerDownModal"
      @update="reload"
      :cancelText="t('routes.scene.canlenDown')"
      :okText="t('routes.scene.down')"
      @cancelDownload="cancelDownload"
      :okButtonProps="{ disabled: canDownload }"
    />
    <!-- <MoveModal @register="registerMoveModal" /> -->
    <SyncModal @register="registerMoveModal" @update="reload" />
  </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 SyncModal from './modal/SyncModal.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,
    caseDelApi,
    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,
      SyncModal,
      [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 columns: BasicColumn[] = [
        {
          title: t('routes.scene.sceneName'),
          dataIndex: 'sceneName',
          slots: { customRender: 'href' },
          width: 300,
        },
        {
          title: t('routes.scene.num'),
          dataIndex: 'num',
          ellipsis: true,
          width: 180,
        },
        {
          title: t('routes.scene.createTime'),
          dataIndex: 'createTime',
          width: 180,
          customRender: ({ record }) => {
            return (
              record.createTime &&
              h(Time, {
                value: record.createTime,
                mode: 'datetime',
              })
            );
          },
        },
        {
          title: t('routes.scene.amount'),
          dataIndex: 'amount',
          width: 210,
          customRender: ({ record }) => {
            return (
              (record.algorithmTime &&
                h(Time, {
                  value: record.algorithmTime,
                  mode: 'datetime',
                })) ||
              '-'
            );
          },
        },
        // {
        //   title: t('routes.scene.snCode'),
        //   dataIndex: 'snCode',
        //   width: 180,
        // },
        // {
        //   title: t('routes.scene.sceneSize'),
        //   dataIndex: 'sceneSize',
        //   width: 120,
        //   customRender: ({ record }) => {
        //     return record.sceneSize && record.sceneSize != 0
        //       ? h('span', { class: 'sceneSize' }, Math.ceil(record.sceneSize / 1024 / 1024) + 'M')
        //       : '-';
        //   },
        // },
        // {
        //   title: t('routes.scene.isCopy'),
        //   dataIndex: 'isCopy',
        //   width: 130,
        //   customRender: ({ record }) => {
        //     return record.isCopy ? t('common.yes') : t('common.no');
        //   },
        // },
        // {
        //   title: t('routes.scene.copyTime'),
        //   dataIndex: 'copyTime',
        //   width: 140,
        //   customRender: ({ record }) => {
        //     return (
        //       (record.copyTime &&
        //         h(Time, {
        //           value: record.copyTime,
        //           mode: 'datetime',
        //         })) ||
        //       '-'
        //     );
        //   },
        // },
        // {
        //   title: t('routes.scene.userName'),
        //   dataIndex: 'userName',
        //   width: 140,
        // },
        // {
        //   title: t('routes.scene.viewCount'),
        //   dataIndex: 'viewCount',
        //   width: 80,
        // },
        {
          title: t('routes.scene.status'),
          dataIndex: 'status',
          width: 110,
          customRender: ({ record }) => {
            let str;
            switch (record.status - 0) {
              case 0:
                str = t('routes.scene.statusType.0');
                break;
              case 1:
                str = t('routes.scene.statusType.1');
                break;
              case -2:
                str = t('routes.scene.statusType.-2');
                break;
              case -1:
                str = t('routes.scene.statusType.-1');
                break;
            }
            return record.payStatus == -2 ? t('routes.scene.statusType.-3') : str;
          },
        },
        {
          title: t('common.operating'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
          ifShow: true,
          fixed: 'right',
          flag: 'ACTION',
          width: 180,
        },
      ];
      const searchForm: Partial<FormProps> = {
        labelWidth: 80,
        schemas: [
          {
            field: 'sceneName',
            label: t('routes.scene.sceneName'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            label: t('routes.scene.num'),
            field: 'num',
            labelWidth: 60,
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'snCode',
            label: t('routes.scene.snCode'),
            component: 'Input',
            labelWidth: 50,
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 4,
              xxl: 4,
            },
          },
          {
            field: 'userName',
            label: t('routes.scene.userName'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 4,
              xxl: 4,
            },
          },
        ],
      };
      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,
        // rowSelection: { type: 'checkbox' },
        formConfig: searchForm,
        showTableSetting: true,
        showIndexColumn: false,
        rowKey: 'num',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: false,
      });
      function changeTable(val: string) {
        tableType.value = val;
        reload();
      }
      async function handleCopy(record: Recordable) {
        createConfirm({
          title: t('routes.scene.copyTipsTitle'),
          content: t('routes.scene.copyTipsText'),
          onOk: async () => {
            sceneCopy({ num: record.num }).then(() => {
              message.success({
                content: t('routes.scene.copySccuse'),
              });
              reload();
            });
          },
        });
      }
      async function handleDelete(record: Recordable) {
        console.log('handleDelete', record);
        createConfirm({
          iconType: 'warning',
          title: '警告',
          content: `此操作将对${record.title}进行删除, 是否继续?`,
          onOk: async () => {
            await caseDelApi([record.id]);
            reload();
          },
        });
      }
      async function handleMove() {
        openMoveModal(true, {});
      }
      function handleSee(record) {
        window.open(record.webSite);
      }
      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(t('routes.scene.downErr'));
                      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) {
        createConfirm({
          title: t('routes.scene.reset'),
          content: t('routes.scene.resetTips'),
          onOk: async () => {
            rebuildScene({ num: record.num }).then(() => {
              message.success({
                content: t('common.optSuccess'),
              });
              reload();
            });
          },
        });
      }
      function getTypeCheckPerm(val) {
        let myType = tableType.value;
        return getCheckPerm(val) || getCheckPerm(`${val}-${myType}`);
      }
      return {
        registerTable,
        handleDelete,
        handleCopy,
        handleSee,
        handleMove,
        handleDownload,
        handleReset,
        tableType,
        changeTable,
        reload,
        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>
