import {
  Image,
  Cell,
  CellGroup,
  Tag,
  Button,
  Stepper,
  Icon,
  Popup,
  showConfirmDialog,
  showToast
} from 'vant';
import { computed, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import iconGift from './images/icon-gift.png';
import shopEmpty from './images/shop-empty.png';
import iconDateMember from './images/icon-date-member.png';
import MSticky from '@/components/m-sticky';
import MVideo from '@/components/m-video';
import { useRoute, useRouter } from 'vue-router';
import RegisterModal from './register-modal';
import { useStudentRegisterStore } from '@/store/modules/student-register-store';
import request from '@/helpers/request';
import { browser, moneyFormat } from '@/helpers/utils';
import deepClone from '@/helpers/deep-clone';
import OWxTip from '@/components/m-wx-tip';
import MDialog from '@/components/m-dialog';

export default defineComponent({
  name: 'student-register',
  setup() {
    const route = useRoute();
    const studentRegisterStore = useStudentRegisterStore();
    const router = useRouter();
    // 初始化学校编号
    studentRegisterStore.setShoolId(route.query.sId as any);
    const forms = reactive({
      schoolId: route.query.sId as any,
      paymentType: '', // 支付类型
      popupShow: false,
      details: [] as any[],
      schoolType: '', // 学校类型
      gradeYear: '', // 学制
      bugGoods: false, // 是否购买AI
      registerType: '', // 报名类型
      giftVipDay: 0, // 赠送天数
      submitLoading: false,
      showMore: true,
      showTips: false,
      showButton: false,
      showMessage: '请使用微信扫描二维码'
    });

    const getRegisterGoods = async () => {
      try {
        const { data } = await request.get(
          '/edu-app/open/userOrder/registerGoods/' + forms.schoolId,
          {
            noAuthorization: true // 是否请求接口的时候添加toekn
          }
        );
        // 默认选中商品
        studentRegisterStore.setVip(data.details || []);
        forms.details = deepClone(data.details || []);
        if (forms.details.length > 0) {
          forms.giftVipDay = forms.details[0].membershipDays;
        }
        forms.bugGoods = data.bugGoods;
        forms.schoolType = data.schoolType;
        forms.gradeYear = data.gradeYear;
        forms.registerType = data.registerType;
        if (browser().weixin) {
          if (data.registerType !== 'BUG_GOODS' || data.schoolStatus === 0) {
            forms.showTips = true;
            forms.showMessage = '二维码已经失效，详情请咨询学校老师';
            forms.showButton = false;
          }
        } else {
          forms.showTips = true;
        }
      } catch {}
    };

    // 计算金额
    const calcPrice = computed(() => {
      let amount: number = 0; //现价
      let originAmount: number = 0; // 原价
      const vipList: any[] = studentRegisterStore.getVip;
      vipList.forEach((vip: any) => {
        amount += Number(vip.currentPrice);
        originAmount += Number(vip.originalPrice);
      });

      const goodsList: any[] = studentRegisterStore.getGoods;
      goodsList.forEach((good: any) => {
        amount += Number(good.price) * good.quantity;
        originAmount += Number(good.originalPrice) * good.quantity;
      });
      return {
        amount,
        originAmount
      };
    });

    // 删除商品
    const onGoodsRemove = (item: any) => {
      showConfirmDialog({
        message: '是否删除该商品',
        confirmButtonColor: '#FF8633'
      }).then(() => {
        studentRegisterStore.deleteGoods(item.productSkuId);
      });
    };

    // 登记成功之后购买
    const onRegisterSubmit = async () => {
      try {
        forms.submitLoading = true;

        // 检测token是否失效
        // const Authorization = storage.get(ACCESS_TOKEN) || '';
        // const authInfo = await request.post('/edu-app/open/user/verification', {
        //   noAuthorization: true,
        //   data: { token: Authorization }
        // });
        // // 判断当前token是否失效
        // if (!authInfo.data) {
        //   storage.remove(ACCESS_TOKEN);
        //   studentRegisterStore.deleteToken();
        //   forms.popupRegister = true;
        //   return;
        // }

        // // 请求是否有待支付订单，如果有则自动关闭
        // const status = await paymentOrderUnpaid();
        // if (status) return;
        // const schoolInfo = await request.get(
        //   '/edu-app/userPaymentOrder/registerStatus/' + forms.schoolId
        // );
        // const vipList = studentRegisterStore.getVip;

        // if (schoolInfo.data.hasBuyCourse && vipList.length > 0) {
        //   // setTimeout(() => {
        //   //   showToast('您已购买乐器AI学练工具，请勿重复购买');
        //   // }, 100);
        //   forms.dialogConfirmStatus = true;
        //   return;
        // }
        // await paymentContinue();

        router.push({
          path: '/student-register-form',
          query: {
            schoolId: forms.schoolId
          }
        });
      } finally {
        forms.submitLoading = false;
      }
    };

    onMounted(async () => {
      try {
        getRegisterGoods();
      } catch {}
    });

    return () => (
      <div class={styles['student-register']}>
        <div class={styles.studentSection} style={{ marginTop: '18px' }}>
          <div class={styles.titleTool}></div>
          {forms.details.map((item: any) => (
            <CellGroup
              class={styles.goodsSection}
              onClick={() => {
                if (studentRegisterStore.selectedVip(item.goodsId)) {
                  studentRegisterStore.deleteVip(item.goodsId);
                } else {
                  studentRegisterStore.setVip([item]);
                }
              }}>
              <Cell border={false} class={styles.goodsCell}>
                {{
                  icon: () => <Image class={styles.img} src={item.goodsUrl} />,
                  title: () => (
                    <div class={styles.section}>
                      <div class={styles.sectionContent}>
                        <h2>
                          <img
                            src={iconDateMember}
                            class={styles.iconDateMember}
                          />
                        </h2>

                        <p
                          class={[
                            styles.model,
                            forms.showMore ? styles.more : ''
                          ]}>
                          {item.description}
                        </p>
                        {item.description &&
                        item.description.length >= 36 &&
                        forms.showMore ? (
                          <span
                            class={styles.moreBtn}
                            onClick={(e: MouseEvent) => {
                              e.stopPropagation();
                              forms.showMore = false;
                            }}>
                            查看更多
                            <Icon name="arrow-down" color="#aaa" />
                          </span>
                        ) : (
                          ''
                        )}

                        {/* <div class={styles.sbtnGroup}>
                          <span
                            class={styles.btnDetail}
                            onClick={(e: MouseEvent) => {
                              e.stopPropagation();
                              router.push('/student-digital-tools');
                            }}>
                            查看详情
                          </span>
                          <span
                            class={styles.btnVideo}
                            onClick={(e: MouseEvent) => {
                              e.stopPropagation();
                              forms.popupShow = true;
                            }}>
                            介绍视频
                          </span>
                        </div> */}
                      </div>

                      <i
                        class={
                          studentRegisterStore.selectedVip(item.goodsId)
                            ? styles.selected
                            : styles.noSelected
                        }></i>
                    </div>
                  )
                }}
              </Cell>
              <Cell border={false} class={styles.priceCell}>
                {{
                  title: () => (
                    <div class={styles.sPriceGroup}>
                      <div class={styles.tg}>
                        团购价：
                        <span>
                          <i>¥ </i>
                          {moneyFormat(item.currentPrice)}
                        </span>
                      </div>
                      {item.currentPrice < item.originalPrice && (
                        <del>¥{moneyFormat(item.originalPrice)}</del>
                      )}
                    </div>
                  )
                }}
              </Cell>
              {item.membershipDays > 0 && (
                <Cell border={false} class={styles.giftCell}>
                  {{
                    title: () => (
                      <div class={styles.gift}>
                        <img src={iconGift} class={styles.iconGift} />
                        现在购买赠送 <span>{item.membershipDays || 0}</span>
                        天有效期
                      </div>
                    )
                  }}
                </Cell>
              )}
            </CellGroup>
          ))}
        </div>

        {forms.bugGoods && (
          <>
            <div class={styles.studentSection}>
              <div class={styles.titleBuy}></div>
              {studentRegisterStore.getGoods &&
              studentRegisterStore.getGoods.length <= 0 ? (
                <div class={styles.goodsEmpty}>
                  <img src={shopEmpty} class={styles.shopImg} />
                  <div class={styles.goodsContainer}>
                    <h2>
                      为你的<span>音乐之旅</span>做好准备
                    </h2>
                    <p class={styles.tips}>快去选购乐器吧～</p>
                    <Button
                      class={styles.goSelect}
                      type="primary"
                      onClick={() => {
                        router.push('/goods-list');
                      }}>
                      进入商城选购
                      <Icon name="arrow" />
                    </Button>
                  </div>
                </div>
              ) : (
                studentRegisterStore.getGoods.map((goods: any) => (
                  <CellGroup class={styles.goodsSection}>
                    <Cell border={false} class={styles.goodsCell}>
                      {{
                        icon: () => (
                          <Image class={styles.img} src={goods.pic} />
                        ),
                        title: () => (
                          <div class={styles.section}>
                            <div class={styles.sectionContent}>
                              <h2>
                                {goods.name}
                                <Tag class={styles.brandName}>
                                  {goods.brandName}
                                </Tag>
                              </h2>
                              <p class={[styles.model]}>
                                规格：{goods.spDataJson}
                              </p>
                              <p class={[styles.model]}>{goods.productSn}</p>

                              <Stepper
                                min={1}
                                max={99}
                                v-model={goods.quantity}
                                disableInput
                              />
                            </div>

                            <i
                              class={styles.delete}
                              onClick={() => onGoodsRemove(goods)}></i>
                          </div>
                        )
                      }}
                    </Cell>
                    <Cell border={false} class={styles.priceCell}>
                      {{
                        title: () => (
                          <div class={styles.sPriceGroup}>
                            <div class={styles.tg}>
                              团购价：
                              <span>
                                <i>¥ </i>
                                {moneyFormat(goods.price)}
                              </span>
                            </div>
                            {goods.price < goods.originalPrice && (
                              <del>¥{moneyFormat(goods.originalPrice)}</del>
                            )}
                          </div>
                        )
                      }}
                    </Cell>
                  </CellGroup>
                ))
              )}
            </div>
            {studentRegisterStore.getGoods &&
              studentRegisterStore.getGoods.length > 0 && (
                <Button
                  class={styles.addButton}
                  block
                  onClick={() => {
                    router.push('/goods-list');
                  }}>
                  <Icon name="add-o" />
                  进入商城选购
                </Button>
              )}
          </>
        )}

        <MSticky position="bottom">
          <div class={styles.paymentContainer}>
            <div class={styles.payemntPrice}>
              <span class={styles.needPrice}>
                <i style="font-style: normal">¥ </i>
                <span>{moneyFormat(calcPrice.value.amount)}</span>
              </span>
              {calcPrice.value.originAmount > calcPrice.value.amount ? (
                <del class={styles.allPrice}>
                  ¥ {moneyFormat(calcPrice.value.originAmount)}
                </del>
              ) : (
                ''
              )}
            </div>
            <div
              class={styles.paymentBtn}
              onClick={() => {
                const vipList = studentRegisterStore.getVip;
                const goodsList = studentRegisterStore.getGoods;
                if (vipList.length <= 0 && goodsList.length <= 0) {
                  setTimeout(() => {
                    showToast('请选择需要购买的商品');
                  }, 100);
                  return;
                }
                onRegisterSubmit();
              }}>
              <Button
                disabled={forms.submitLoading}
                loading={forms.submitLoading}>
                确认购买
              </Button>
            </div>
          </div>
        </MSticky>

        <Popup v-model:show={forms.popupShow} class={styles.videoPopup}>
          {forms.popupShow && (
            <MVideo src={'https://oss.dayaedu.com/daya/202105/SWmqmvW.mp4'} />
          )}
        </Popup>

        {/* 是否在微信中打开 */}
        <OWxTip
          show={forms.showTips}
          message={forms.showMessage}
          showButton={forms.showButton}
          buttonText="刷新"
          onConfirm={() => window.location.reload()}
        />
      </div>
    );
  }
});
