<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-tab-pane :key="3" :tab="t('routes.scene.tableType.3')" />  -->
      </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.sceneName && record.webSite" target="_blank" :href="record.webSite">{{
            record.sceneName
          }}</a>
          <span v-else-if="record.sceneName">{{ record.sceneName }}</span>
          <span v-else>-</span>
        </template>
        <template #action="{ record }">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                label: t('routes.scene.transfer'),
                disabled: !(record.status == 1 || record.status == -2),
                onClick: handleMove.bind(null, record),
              },
              {
                label: t('routes.scene.copy'),
                disabled: !(record.status == 1 || (record.status == -2 && record.payStatus == 1)),
                onClick: handleCopy.bind(null, record),
              },
              {
                label: t('routes.scene.reset'),
                disabled: record.status == 0 || (record.status == -2 && record.payStatus != 1),
                onClick: handleReset.bind(null, record),
                //popConfirm: {
                //  title: t('routes.scene.resetTips'),
                //  confirm: handleReset.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" />
  </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 { 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,
} 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,
    [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: 150,
      },
      {
        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: 130,
      autoAdvancedLine: 1,
      actionColOptions: {
        span: 24,
      },
      schemas: [
        {
          field: 'sceneName',
          label: t('routes.scene.sceneName'),
          component: 'Input',
          componentProps: {
            maxLength: 100,
          },
          colProps: {
            xl: 7,
            xxl: 7,
          },
        },
        {
          label: t('routes.scene.num'),
          field: 'num',
          component: 'Input',
          componentProps: {
            maxLength: 100,
          },
          colProps: {
            xl: 7,
            xxl: 7,
          },
        },
        {
          field: 'snCode',
          label: t('routes.scene.snCode'),
          component: 'Input',
          componentProps: {
            maxLength: 100,
          },
          colProps: {
            xl: 7,
            xxl: 7,
          },
        },
        {
          field: 'userName',
          label: t('routes.scene.userName'),
          component: 'Input',
          componentProps: {
            maxLength: 100,
          },
          colProps: {
            xl: 7,
            xxl: 7,
          },
        },
        {
          field: 'timeList',
          label: t('routes.scene.createTime'),
          component: 'RangePicker',
          componentProps: {
            maxLength: 100,
            valueFormat: 'YYYY-MM-DD',
            format: 'YYYY-MM-DD',
          },
          colProps: {
            xl: 7,
            xxl: 7,
          },
        },
      ],
    };
    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,
      formConfig: searchForm,
      showTableSetting: true,
      showIndexColumn: false,
      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: 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({
      //   title: '删除',
      //   content: '确定要删除场景吗？',
      //   onOk: async () => {
      sceneDelete({ num: record.num }).then(() => {
        message.success({
          content: t('routes.scene.deleteSccuse'),
        });
        reload();
      });
      //   },
      // });
    }
    async function handleMove(record: Recordable) {
      openMoveModal(true, {
        ...record,
      });
    }
    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,
      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>
