<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.appListPicUrl || '/resource/img/pic_bg@2x.png']"
        />
      </template>
      <template #link="{ record }">
        <a target="_blank" :href="record.webSite">{{ record.webSite }}</a>
      </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),
              },
            },
            {
              color: 'error',
              label: t('routes.scenes.editor'),
              onClick: openSceneEditor.bind(null, record),
            },
            {
              label: '编辑场景',
              onClick: openSceneEditorModal.bind(null, record),
            },
            {
              color: 'error',
              label: t('routes.scenes.makeLiveCover'),
              ifShow: record.lived !== true,
              onClick: generateDefaultLiveRoom.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <DownloadModal @register="registerDownloadModal" />
    <EditorModal @register="registerEditorModal" @reload="reload" />
  </div>
</template>
<script lang="ts">
  import { defineComponent } 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';
  import {
    ListApi,
    // generateSceneEditTokenApi,
    downloadSceneDataAPi,
    generateDefaultLiveRoomApi,
  } 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 EditorModal from './editorModal.vue';

  export default defineComponent({
    components: { BasicTable, TableAction, TableImg, DownloadModal, EditorModal },
    setup() {
      const { createMessage } = useMessage();
      const [registerDownloadModal, { openModal: openDownloadModal }] = useModal();
      const [registerEditorModal, { openModal: openEditorModal }] = useModal();
      const { t } = useI18n();
      const userStore = useUserStore();
      const { getCheckRole } = userStore;
      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: '封面',
          dataIndex: 'appListPicUrl',
          ellipsis: true,
          slots: { customRender: 'cover' },
          width: 150,
        },
        {
          title: t('routes.scenes.childName'),
          dataIndex: 'childName',
          width: 200,
        },
        {
          title: t('routes.scenes.viewCount'),
          dataIndex: 'viewCount',
          width: 180,
        },
        {
          title: t('routes.scenes.createTime'),
          dataIndex: 'createTime',
          width: 180,
        },
        {
          title: t('routes.scenes.isShow'),
          dataIndex: 'isShow',
          width: 180,
          customRender: ({ record }) => {
            const enable = record.isShow == 1;
            const text = enable ? t('common.yes') : t('common.no');
            return text;
          },
        },
        {
          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' },
          ifShow: !getCheckRole('tourist'),
          width: 330,
          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,
            },
            componentProps: {
              maxLength: 100,
            },
          },
          {
            field: 'sceneName',
            label: t('routes.scenes.sceneName'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
          {
            field: 'childName',
            label: t('routes.scenes.childName'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              lg: 6,
              xl: 6,
              xxl: 6,
              sm: 12,
              xs: 24,
            },
          },
        ],
      };
      // { getForm }
      const [registerTable, { reload }] = 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
      });
      async function openSceneEditor(record: Recordable) {
        try {
          const url = record.webSite.replace('smobile', 'epc') + '&menu=business&token=';
          const userStore = useUserStore();
          const token = userStore.getToken;
          console.log(token);
          // const data = await generateSceneEditTokenApi({
          //   sceneNum: record.num,
          //   userName: userStore.getUserInfo?.userName,
          // });
          window.open(url + token);
        } catch (error) {
          console.log('error', error);
        }
      }
      function openSceneEditorModal(record: Recordable) {
        openEditorModal(true, record);
      }
      async function handleDownloadScene(record: Recordable) {
        const res = await downloadSceneDataAPi({
          sceneNum: record.num,
        });
        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]
         *
         * */

        if (downloadUrl?.length > 0) {
          if (downloadUrl === 'success') {
            await openDownloadModal(true, record);
          } else {
            downloadByUrl({
              url: downloadUrl as any as string,
              target: '_self',
            });
          }
        }
      }
      async function generateDefaultLiveRoom(record: Recordable) {
        let res = await generateDefaultLiveRoomApi({
          sceneNum: record.num,
        });
        console.log('generateDefaultLiveRoom', res);
        if (res) {
          createMessage.success(t('common.optSuccess'));
          reload();
        }
      }
      return {
        registerTable,
        createMessage,
        t,
        reload,
        openSceneEditor,
        openEditorModal,
        registerEditorModal,
        handleDownloadScene,
        registerDownloadModal,
        generateDefaultLiveRoom,
        openSceneEditorModal,
      };
    },
  });
</script>
