<template>
  <div class="p-4">
    <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox' }">
      <template #toolbar>
        <!-- <a-button type="primary" @click="() => {}"> 新增</a-button> -->
        <!-- <a-button type="primary" color="warning" @click="() => {}"> 编辑</a-button>
        <a-button type="primary" color="error" @click="() => {}"> 删除</a-button> -->
      </template>

      <template #cover="{ record }">
        <TableImg
          :size="120"
          :simpleShow="true"
          :imgList="[record.thumb || '/resource/img/pic_bg@2x.png']"
        />
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              // icon: 'mdi:briefcase-download',
              label: t('routes.scenes.downloadScene'),
              popConfirm: {
                title: t('routes.scenes.downloadSceneConfirm'),
                confirm: handleDownloadScene.bind(null, record),
              },
            },
            {
              // icon: 'dashicons:editor-kitchensink',
              color: 'error',
              label: t('routes.scenes.editor'),
              onClick: openSceneEditor.bind(null, record),
            },
            // {
            //   // icon: 'dashicons:editor-kitchensink',
            //   color: 'error',
            //   label: t('routes.scenes.makeLiveCover'),
            //   onClick: openSceneEditor.bind(null, record),
            // },
            // {
            //   // icon: 'dashicons:editor-kitchensink',
            //   color: 'error',
            //   label: t('routes.scenes.editor'),
            //   onClick: openSceneEditor.bind(null, record),
            // },
          ]"
        />
      </template>
    </BasicTable>
    <DownloadModal @register="registerDownloadModal" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed } from 'vue';
  import {
    BasicTable,
    useTable,
    BasicColumn,
    FormProps,
    TableAction,
    TableImg,
  } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  // import { uploadApi } from '/@/api/sys/upload';
  // import { Progress } from 'ant-design-vue';
  // import { h } from 'vue';
  // addDownloadNumApi,
  // checkDownloadApi,
  import {
    ListApi,
    generateSceneEditTokenApi,
    downloadSceneDataAPi,
    addDownloadNumApi,
    checkDownloadApi,
  } from '/@/api/scene/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import {
  //   downloadByUrl,
  //   // downloadByData,
  //   // downloadByBase64,
  //   // downloadByOnlineUrl,
  // } from '/@/utils/file/download';

  import { useUserStore } from '/@/store/modules/user';
  import DownloadModal from './downloadModal.vue';
  import { useLocaleStore } from '/@/store/modules/locale';
  const localeStore = useLocaleStore();

  export default defineComponent({
    components: { BasicTable, TableAction, TableImg, DownloadModal },
    setup() {
      const { createMessage } = useMessage();
      const [registerDownloadModal, { openModal: openDownloadModal }] = useModal();
      const { t } = useI18n();
      const isJA = computed(() => localeStore.getLocale === 'ja');
      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          width: 80,
          defaultHidden: true,
        },
        {
          title: t('routes.scenes.sceneName'),
          dataIndex: 'sceneName',
          ellipsis: false,
          width: 120,
        },
        {
          title: t('routes.corporation.enterpriseName'),
          dataIndex: 'companyName',
          ellipsis: false,
          width: 120,
        },
        {
          title: t('routes.scenes.webSite'),
          dataIndex: 'webSite',
          slots: { customRender: 'link' },
          width: 180,
        },
        {
          title: t('routes.scenes.appListPicUrl'),
          dataIndex: 'thumb',
          slots: { customRender: 'cover' },
          width: 150,
        },
        {
          title: t('routes.scenes.childName'),
          dataIndex: 'childName',
          width: 120,
        },
        {
          title: t('routes.scenes.viewCount'),
          dataIndex: 'viewCount',
          width: 180,
        },
        {
          title: t('routes.scenes.createTime'),
          dataIndex: 'createTime',
          width: 180,
        },

        {
          title: t('routes.scenes.num'),
          dataIndex: 'num',
          width: 180,
        },

        // {
        //   title: t('routes.scenes.process'),
        //   dataIndex: '',
        //   width: 180,
        //   slots: { customRender: 'process' },
        //   ifShow: false,
        // },

        {
          title: t('common.operation'),
          dataIndex: '',
          slots: { customRender: 'action' },
          width: isJA.value ? 300 : 180,
          fixed: 'right',
        },
      ];

      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'companyName',
            label: t('routes.corporation.enterpriseName'),
            component: 'Input',
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
          {
            field: 'sceneName',
            label: t('routes.scenes.sceneName'),
            component: 'Input',
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
          {
            field: 'childName',
            label: t('routes.scenes.childName'),
            component: 'Input',
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
        ],
      };
      // { getForm }
      const [registerTable] = useTable({
        title: t('routes.scenes.sceneList'),
        api: ListApi,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        clickToRowSelect: false,
        showIndexColumn: false,
        rowKey: 'id',
        //TODO
        fetchSetting: {
          pageField: 'page',
          sizeField: 'limit',
          listField: 'list',
          totalField: 'total',
        },
      });
      async function openSceneEditor(record: Recordable) {
        try {
          const url = record.webSite.replace('smobile', 'epc') + '&menu=business&token=';
          const userStore = useUserStore();
          const data = await generateSceneEditTokenApi({
            sceneNum: record.num,
            userName: userStore.getUserInfo?.phone,
          });
          console.log('generateSceneEditTokenApi', data);
          window.open(url + data);
        } catch (error) {
          console.log('error', error);
        }
      }

      async function handleDownloadScene(record: Recordable) {
        await addDownloadNumApi({
          sceneNum: record.num,
        });
        const checker = await checkDownloadApi({
          sceneNum: record.num,
        });
        const res = await downloadSceneDataAPi({
          sceneNum: record.num,
        });
        console.log('res', res);

        // const downloadUrl = res as any as string;
        // console.log('downloadUrl', downloadUrl, res);
        /**
         * mark 2022-03-22 message return success 是要进入openDownloadModal轮询，非表面「成功」字意思。
         * message return url 指已下载，转mimeType download
         *
         * notice: 过往 downloadUrl 是 boolean / string
         *  现在 downloadUrl 是 string[success] / string[url]
         *
         * */
        // await openDownloadModal(true, record);
        // downloadByUrl({
        //   url: downloadUrl as any as string,
        //   target: '_self',
        // });
        if (checker.downloadStatus === 0) {
          await openDownloadModal(true, record);
        }
      }
      return {
        registerTable,
        createMessage,
        t,
        openSceneEditor,
        handleDownloadScene,
        registerDownloadModal,
      };
    },
  });
</script>
