import { browser } from '@/helpers/utils';
import { defineComponent, reactive } from 'vue';
import styles from './index.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import { postMessage } from '@/helpers/native-message';
import { useRouter } from 'vue-router';
import { Button, Field, Popup, showToast } from 'vant';
import iconKey from './images/icon-key.png';
import num1 from './images/num1.png'
import num2 from './images/num2.png'
import num3 from './images/num3.png'
import num4 from './images/num4.png'
import CodeDialog from './modal/code-dialog';
import request from '@/helpers/request';
import dayjs from 'dayjs';

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

export default defineComponent({
  name: 'activationCode',
  setup() {
    const router = useRouter();
    const state = reactive({
      showPopup: false,
      reslutPopupType: '',
      resultPopupContent: '',
      loading: false,
      activeCodeRecordCode: null as any,
      successInfo: {} as any
    });

    const onSubmit = async () => {
      if (!state.activeCodeRecordCode) {
        showToast('请输入互通码');
        return;
      }
      state.loading = true;
      try {
        const res = await request.post(
          '/edu-app/activationCodeRecord/useActiveCode',
          {
            data: {
              activeCodeRecordCode: state.activeCodeRecordCode
            }
          }
        );
        if (res.code !== 200) {
          if (res.code === 980) {
            // 980:激活码不存在
            state.showPopup = true;
            state.reslutPopupType = 'INVALID';
            state.resultPopupContent = res.message;
          } else if (res.code === 981) {
            // 981：激活码被同一人重复使用
            state.showPopup = true;
            state.reslutPopupType = 'ACTIVATED-TWO';
            state.resultPopupContent = res.message;
          } else if (res.code === 982) {
            // 982:激活码已激活
            state.showPopup = true;
            state.reslutPopupType = 'EXPIRED';
            state.resultPopupContent = res.message;
          } else if (res.code === 983) {
            // 983:激活码已作废
            state.showPopup = true;
            state.reslutPopupType = 'OVERDUE';
            state.resultPopupContent = res.message;
          } else if (res.code === 984) {
            // 984:激活码已过期
            state.showPopup = true;
            state.reslutPopupType = 'CANCELLED';
            state.resultPopupContent = res.message;
          } else  if (res.code === 5442 || res.code === 5443) {
            state.showPopup = true;
            state.reslutPopupType = 'EXPIRED';
            state.resultPopupContent = res.message;
          }
        } else {
          state.showPopup = true;
          state.reslutPopupType = 'ACTIVATED';
          state.successInfo = res.data;
        }
      } catch {}
      state.loading = false;
    };
    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.title}>
                      <i></i>
                    </span>
                  </div>
                  <div
                    class={styles.recordBtn}
                    onClick={() => {
                      router.push('/activationRecord');
                    }}>
                    <i class={styles.iconBook}></i>
                    激活记录
                  </div>
                </div>
              )
            }}
          </MHeader>
        </MSticky>

        <div class={styles.activationContainer}>
          <i class={styles.iconBrid}></i>
          <div class={styles.section}>
            <div class={styles.activationContent}>
              <div class={styles.inputGroup}>
                <Field
                  class={styles.input}
                  leftIcon={iconKey}
                  v-model={state.activeCodeRecordCode}
                  placeholder="请输入您的互通码"
                  clearable
                />

                <div class={styles.btnGroup}>
                  <Button
                    round
                    block
                    loading={state.loading}
                    disabled={state.loading}
                    onClick={() => {
                      onSubmit();
                    }}
                    color="linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)">
                    激活
                  </Button>
                </div>
              </div>
              <div class={styles.tipCotnent}>
                <h2>互通码使用须知：</h2>
                <div class={styles.tips}>
                  <p>
                    <img src={num1} class={styles.num} />
                    互通码只可使用一次，不能重复使用；
                  </p>
                  <p>
                    <img src={num2} class={styles.num} />
                    为确保安全，请勿将互通码泄露，以免造成不必要的损失；
                  </p>
                  <p>
                    <img src={num3} class={styles.num} />
                    互通码请尽快激活使用，避免互通码过期；
                  </p>
                  <p>
                    <img src={num4} class={styles.num} />
                    互通码内容以实际购买页面内容为准。
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <Popup
          show={state.showPopup}
          style={{
            background: 'transparent',
            overflow: 'visible !important'
          }}>
          <CodeDialog
            type={state.reslutPopupType as any}
            onConfirm={() => {
              state.showPopup = false;
            }}>
            {state.reslutPopupType === 'ACTIVATED' && (
              <p>
                您已成功激活{state.successInfo?.times}
                {vipGiftPeriodType[state.successInfo?.type]}
                乐器AI学练工具，有效期至
                <span style={{ color: '#2B85FF' }}>
                  {dayjs(state.successInfo.membershipEndTime).format(
                    'YYYY-MM-DD'
                  )}
                </span>
              </p>
            )}

            {[
              'INVALID',
              'EXPIRED',
              'CANCELLED',
              'OVERDUE',
              'ACTIVATED-TWO'
            ].includes(state.reslutPopupType) && (
              <p style={{ textAlign: 'center', paddingTop: '5px' }}>
                {state.resultPopupContent}
              </p>
            )}
          </CodeDialog>
        </Popup>
      </div>
    );
  }
});
