<template>
  <div class="p-4">
    <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox' }">
      <template #toolbar>
        <a-button
          type="primary"
          v-show="
            getCheckRole(['super', 'plat_admin']) ||
            (getCheckRole(['company_admin', 'staff']) && getEquity([2]))
          "
          @click="handleAddLiveScene"
        >
          创建房间</a-button
        >
      </template>
      <template #cover="{ record }">
        <TableImg
          :size="150"
          :simpleShow="true"
          :imgList="[record.appListPicUrl || '/resource/img/pic_bg@2x.png']"
        />
      </template>
      <template #Time="{ record }">
        <Time :value="record.createTime" mode="datetime" />
      </template>
      <template #liveEndTime="{ record }">
        <Time v-if="record.liveEndTime" :value="record.liveEndTime" mode="datetime" />
        <span v-else>-</span>
      </template>

      <template #liveTime="{ record }">
        <Time :value="record.effectiveStartTime" mode="datetime" />
        <br />
        <Time :value="record.effectiveEndTime" mode="datetime" />
      </template>

      <template #houseType="{ record }">
        {{ renderHouseType(Number(record.type)) }}
      </template>

      <template #action="{ record }">
        <TableAction :actions="renderActions(record)" />
      </template>
    </BasicTable>
    <roomDetail @success="reload" @register="registerModal" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, toRaw } from 'vue';
  import dayjs from 'dayjs';
  import {
    BasicTable,
    useTable,
    BasicColumn,
    FormProps,
    TableAction,
    TableImg,
  } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Time } from '/@/components/Time';
  // import { LiveSceneDeleteApi } from '/@/api/scene/live';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import roomDetail from './roomDetail.vue';
  import { listRoomsApi, dismissRoom, deleteRoom } from '/@/api/scene/list';

  export default defineComponent({
    components: { BasicTable, TableAction, TableImg, roomDetail, Time },
    emits: ['register'],
    setup() {
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const { getCheckRole, getEquity } = userStore;
      const { t } = useI18n();
      const [registerModal, { openModal: addopenModal }] = useModal();
      const permList = computed(() => userStore.getPermList);
      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          fixed: 'left',
          width: 100,
        },
        {
          title: t('routes.room.anchorRoom'),
          dataIndex: 'name',
          ellipsis: false,
          width: 130,
        },
        {
          title: t('routes.room.brandName'),
          dataIndex: 'brandName',
          ellipsis: false,
          width: 130,
        },
        {
          title: t('routes.room.capacities'),
          dataIndex: 'capacities',
          // slots: { customRender: 'houseType' },
          width: 100,
          customRender: ({ record }) => {
            return record.capacities || '-';
          },
        },
        {
          title: '主持人',
          dataIndex: 'anchorUserName',
          width: 140,
        },
        {
          title: '助理',
          dataIndex: 'assistantUserName',
          width: 140,
          customRender: ({ record }) => {
            return record.assistantUserName || '-';
          },
        },
        {
          title: '助理手机号',
          dataIndex: 'assistantPhone',
          width: 140,
          customRender: ({ record }) => {
            return record.assistantPhone || '-';
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          slots: { customRender: 'Time' },
          width: 150,
        },
        {
          title: '开播时间段',
          dataIndex: 'effectiveStartTime',
          slots: { customRender: 'liveTime' },
          width: 180,
        },
        {
          title: '房间结束时间',
          dataIndex: 'liveEndTime',
          slots: { customRender: 'liveEndTime' },
          width: 140,
        },
        {
          title: '创建人',
          dataIndex: 'createUserName',
          width: 180,
        },
        {
          title: t('routes.room.roomStatus'),
          dataIndex: 'state',
          width: 180,
          customRender: ({ record }) => {
            const enable = record.state;
            const text = renderRoomType(enable); // ? t('routes.room.statusText.1') : t('routes.room.statusText.0');
            return text;
          },
        },
        {
          title: t('common.operation'),
          dataIndex: '',
          slots: { customRender: 'action' },
          ifShow:
            (!getCheckRole(['host', 'tourist']) && getEquity(2)) ||
            getCheckRole(['super', 'plat_admin']),
          width: 100,
          fixed: 'right',
        },
      ];

      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'name',
            label: t('routes.room.anchorRoom'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'anchorUserName',
            label: t('routes.room.anchorUserName'),
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'state',
            label: t('routes.room.listRoomsState'),
            component: 'Select',
            colProps: {
              xl: 5,
              xxl: 5,
            },
            defaultValue: '',
            componentProps: {
              options: [
                {
                  label: t('common.all'),
                  value: '',
                  key: '0',
                },
                {
                  label: t('routes.room.statusText.101'),
                  value: 101,
                  key: '101',
                },
                {
                  label: t('routes.room.statusText.102'),
                  value: 102,
                  key: '102',
                },
                {
                  label: t('routes.room.statusText.103'),
                  value: 103,
                  key: '103',
                },
              ],
            },
          },
        ],
      };

      function renderHouseType(type: number): string {
        switch (type) {
          case 0:
            return '新房';
          case 1:
            return '二手房';
          case 2:
            return '公寓';
          case 3:
            return '民宿';
          case 4:
            return '装修';
          default:
            return t(`routes.room.houseType.9`);
        }
      }

      function renderRoomType(type: number): string {
        switch (type) {
          case 0:
            return '新房';
          case 1:
            return '二手房';
          case 2:
            return '公寓';
          case 3:
            return '民宿';
          case 4:
            return '装修';
          case 101:
            return t('routes.room.statusText.101');
          case 102:
            return t('routes.room.statusText.102');
          case 103:
            return t('routes.room.statusText.103');
          default:
            return t(`routes.room.houseType.9`);
        }
      }

      const [registerTable, { reload }] = useTable({
        title: t(`routes.room.liveBroadcast`),
        api: listRoomsApi,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        rowKey: 'id',
        pagination: { pageSize: 20 },
        clickToRowSelect: false,
        fetchSetting: {
          pageField: 'page',
          sizeField: 'limit',
          listField: 'list',
          totalField: 'totalCount',
        },
        sortFn: (sortInfo) => {
          console.log('sortInfo', sortInfo);
          let order = sortInfo.order && sortInfo.order.replace('end', '');
          return { ...sortInfo, sidx: sortInfo.field, order: order };
        },
      });

      function handleBindAnchor(record: Recordable) {
        createConfirm({
          width: 500,
          iconType: 'warning',
          title: '温馨提示',
          content: `关闭房间后，房间内的所有人都会退出房间，是否继续关闭？<br>（关闭后，房间状态将改为已结束）`,
          onOk: async () => {
            handleDismissRoom(record);
          },
        });
      }
      function openTargetModal(record: Recordable) {
        addopenModal(true, {
          isUpdate: true,
          record: {
            ...toRaw(record),
            launchPeriod: [
              record.effectiveStartTime &&
                dayjs(record.effectiveStartTime).format('YYYY-MM-DD HH:mm:ss'),
              record.effectiveEndTime &&
                dayjs(record.effectiveEndTime).format('YYYY-MM-DD HH:mm:ss'),
            ],
          },
        });
      }
      function handleAddLiveScene() {
        addopenModal(true, {});
      }

      function handleSeeLiveScene(record: Recordable) {
        let setRecord = toRaw(record);
        addopenModal(true, {
          isSetData: true,
          record: {
            ...setRecord,
            brandId: setRecord.brandName,
            anchorUserId: setRecord.anchorUserName,
            assistantUserId: setRecord.assistantUserName,
            launchPeriod: [
              record.effectiveEndTime &&
                dayjs(record.effectiveEndTime).format('YYYY-MM-DD HH:mm:ss'),
              record.effectiveStartTime &&
                dayjs(record.effectiveStartTime).format('YYYY-MM-DD HH:mm:ss'),
            ],
          },
        });
      }
      function handleDtelRoom(record) {
        createConfirm({
          width: 500,
          iconType: 'warning',
          title: '删除房间',
          content: `删除房间后，房间信息及数据将进行销毁，是否继续删除？`,
          onOk: async () => {
            handleDeleteLiveScene(record);
          },
        });
      }

      function renderActions(record: Recordable) {
        if (record.state == '101') {
          return [
            {
              label: '结束房间',
              color: 'error',
              onClick: handleBindAnchor.bind(null, record),
            },
          ];
        } else if (record.state == '102') {
          //未开播
          return [
            {
              color: 'warning',
              label: '编辑',
              onClick: openTargetModal.bind(null, record),
            },
            {
              color: 'error',
              label: '删除',
              onClick: handleDtelRoom.bind(null, record),
            },
          ];
        } else {
          //103：已结束
          return [
            {
              color: 'warning',
              label: '查看',
              onClick: handleSeeLiveScene.bind(null, record),
            },
            {
              color: 'error',
              label: '删除',
              onClick: handleDtelRoom.bind(null, record),
            },
          ];
        }
      }
      async function handleDismissRoom(record: Recordable) {
        await dismissRoom({ id: record.id });
        createMessage.success(t('common.optSuccess'));
        reload();
      }

      async function handleDeleteLiveScene(record: Recordable) {
        await deleteRoom({ id: record.id });
        createMessage.success(t('common.optSuccess'));
        reload();
      }
      return {
        registerTable,
        createMessage,
        handleDtelRoom,
        renderActions,
        renderRoomType,
        renderHouseType,
        t,
        registerModal,
        handleBindAnchor,
        permList,
        reload,
        openTargetModal,
        handleAddLiveScene,
        handleSeeLiveScene,
        handleDeleteLiveScene,
        getCheckRole,
        getEquity,
      };
    },
  });
</script>
