import { browser } from '@/helpers/utils';
import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import { useRouter } from 'vue-router';
import { postMessage } from '@/helpers/native-message';
import MSearch from '@/components/m-search';
import { Calendar, List } from 'vant';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
dayjs.extend(isBetween);
import recordItemBg from './images/record-item-bg.png';

const vipGiftPeriodType = {
  DAY: '天',
  MONTH: '个月',
  YEAR: '年'
} as any;

export default defineComponent({
  name: 'activationCode',
  setup() {
    const router = useRouter();
    const state = reactive({
      showPopoverTime: false,
      background: 'transparent',
      loading: false,
      finished: false,
      list: [] as any
    });

    const forms = reactive({
      page: 1,
      rows: 20,
      status: 'ACTIVATED',
      code: null as any,
      activateStartTime: dayjs().subtract(1, 'months').format('YYYY-MM-DD'),
      activateEndTime: dayjs().format('YYYY-MM-DD')
    });

    const getList = async () => {
      state.loading = true;
      try {
        const params = {
          ...forms
        };

        if (forms.activateEndTime && forms.activateStartTime) {
          params.activateEndTime = forms.activateEndTime + ' 23:59:59';
          params.activateStartTime = forms.activateStartTime + ' 00:00:00';
        }
        const res = await request.post('/edu-app/activationCodeRecord/page', {
          data: params
        });
        if (res.code === 200 && Array.isArray(res?.data?.rows)) {
          state.list = [...state.list, ...res.data.rows];
          state.finished = !res.data.next;
          forms.page = res.data.current + 1;
          // state.listState.dataShow = state.list.length > 0;
        } else {
          state.finished = true;
        }
      } catch (error) {
        // console.log('🚀 ~ error:', error);
        state.finished = true;
      }
      state.loading = false;
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <div
        class={[
          styles.hotMusicMore,
          browser().isTablet ? styles.hotMusicMoreTablet : ''
        ]}>
        <MSticky position="top">
          <MHeader border={false} background={'transparent'}>
            {{
              content: () => (
                <div class={styles.woringHeader}>
                  <div>
                    <i
                      onClick={() => {
                        if (browser().isApp) {
                          postMessage({
                            api: 'goBack'
                          });
                        } else {
                          router.back();
                        }
                      }}
                      class={[
                        'van-badge__wrapper van-icon van-icon-arrow-left van-nav-bar__arrow',
                        styles.leftArrow
                      ]}></i>
                    <span class={styles.title2}>
                      <i></i>
                    </span>
                  </div>
                </div>
              )
            }}
          </MHeader>
          <div class={[styles.activationContainer, styles.recordContainer]}>
            <i class={styles.iconBrid}></i>
            <div class={styles.section}>
              <MSearch
                inputBackground="white"
                shape="round"
                placeholder="请输入互通码"
                onSearch={(val: any) => {
                  forms.code = val;
                  forms.page = 1;
                  state.list = [];
                  state.finished = false;
                  getList();
                }}
              />

              <div class={styles.prodSection}>
                <div class={styles.title}>周期选择</div>
                <div
                  class={[
                    styles.times,
                    state.showPopoverTime ? styles.active : ''
                  ]}
                  onClick={() => {
                    state.showPopoverTime = true;
                  }}>
                  {dayjs(forms.activateStartTime).format('YYYY-MM-DD')}至
                  {forms.activateEndTime}
                </div>
              </div>
            </div>
          </div>
        </MSticky>

        <div class={styles.sectionList}>
          <List
            loading={state.loading}
            finished={state.finished}
            finishedText=" "
            onLoad={getList}
            immediateCheck={false}>
            {state.list.length > 0 &&
              state.list.map((item: any) => (
                <div class={styles.sectionItem}>
                  <div class={styles.itemTop}>
                    <div class={styles.itemTitle}>
                      <img src={recordItemBg} class={styles.recordItemBg} />
                      <div class={styles.text}>
                        乐器AI学练工具{item.times}
                        {vipGiftPeriodType[item.type]}
                      </div>
                    </div>
                    <div class={styles.itemCode}>{item.code}</div>
                  </div>
                  <div class={styles.itemTime}>
                    生效时间：
                    <span>{item.efficientTime}</span>
                  </div>
                </div>
              ))}
          </List>

          {!state.loading && state.list.length === 0 && (
            <div style={{ height: '100%' }}>
              <MEmpty description="暂无激活记录~" />
            </div>
          )}
        </div>

        <Calendar
          v-model:show={state.showPopoverTime}
          firstDayOfWeek={1}
          safeAreaInsetBottom
          type="range"
          title="周期选择"
          minDate={new Date('2023-02-27')}
          defaultDate={[
            dayjs(forms.activateStartTime).toDate(),
            dayjs(forms.activateEndTime).toDate()
          ]}
          style={{
            height: '70%'
          }}
          onConfirm={(item: any) => {
            forms.activateStartTime = dayjs(item[0]).format('YYYY-MM-DD');
            forms.activateEndTime = dayjs(item[1]).format('YYYY-MM-DD');
            state.showPopoverTime = false;

            forms.page = 1;
            state.list = [];
            state.finished = false;
            getList();
          }}
        />
      </div>
    );
  }
});
