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 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 { moneyFormat } from '@/helpers/utils';
import deepClone from '@/helpers/deep-clone';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import OWxTip from '@/components/m-wx-tip';
import MDialog from '@/components/m-dialog';
import { CurrentTime, useCountDown } from '@vant/use';

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,
      popupShow: false,
      popupRegister: false,
      details: [] as any[],
      schoolType: '', // 学校类型
      gradeYear: '', // 学制
      bugGoods: false, // 是否购买AI
      submitLoading: false,
      dialogStatus: false,
      dialogMessage: '',
      countDownTime: 60 * 1000,
      dialogConfig: {} as any
    });

    const countDown = useCountDown({
      // 倒计时 60 秒
      time: forms.countDownTime,
      onChange(current: CurrentTime) {
        forms.dialogMessage = `有待支付订单，请在${Math.ceil(
          current.total / 1000
        )}s后重试`;
      },
      onFinish() {
        forms.dialogStatus = false;
      }
    });

    // 查询未支付订单
    const paymentOrderUnpaid = async () => {
      let result = false;
      try {
        const { data } = await request.get('/edu-app/userPaymentOrder/unpaid');
        // 判断是否有待支付订单

        if (!data.id) return false;

        // 判断是否可以取消订单
        if (data.cancelPayment) {
          await request.post(
            '/edu-app/userPaymentOrder/cancelPayment/' + data.orderNo
          );
          return false;
        } else {
          forms.countDownTime = data.cancelTimes;
          countDown.reset(Number(data.cancelTimes));
          countDown.start();
          forms.dialogMessage = `有待支付订单，请在${Math.ceil(
            countDown.current.value.total / 1000
          )}s后重试`;
          forms.dialogStatus = true;
          forms.dialogConfig = data;
          result = true;
        }
      } catch {
        //
      }
      return result;
    };

    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 || []);

        forms.bugGoods = data.bugGoods;
        forms.schoolType = data.schoolType;
        forms.gradeYear = data.gradeYear;
      } 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;
        const goodsList = studentRegisterStore.getGoods;

        if (schoolInfo.data.hasBuyCourse && vipList.length > 0) {
          setTimeout(() => {
            showToast('您已购买数字化器乐学练工具，请勿重复购买');
          }, 100);
          return;
        }

        const params: any[] = [];
        vipList.forEach((vip: any) => {
          params.push({
            goodsId: vip.goodsId,
            goodsNum: 1,
            goodsType: vip.goodsType,
            paymentCashAmount: vip.currentPrice, // 现金支付金额
            paymentCouponAmount: 0 // 优惠券金额
          });
        });

        goodsList.forEach((goods: any) => {
          params.push({
            goodsId: goods.productId,
            goodsNum: goods.quantity,
            goodsType: 'INSTRUMENTS',
            paymentCashAmount: goods.price, // 现金支付金额
            paymentCouponAmount: 0, // 优惠券金额
            goodsSkuId: goods.productSkuId
          });
        });

        // 创建订单
        const { data } = await request.post(
          '/edu-app/userPaymentOrder/executeOrder',
          {
            hideLoading: false,
            data: {
              paymentType: 'adapay',
              bizId: forms.schoolId, // 乐团编号
              orderType: 'SCHOOL_REGISTER',
              paymentCashAmount: calcPrice.value.amount || 0,
              paymentCouponAmount: 0,
              goodsInfos: params,
              orderName: '学生登记',
              orderDesc: '学生登记'
            }
          }
        );

        router.push({
          path: '/order-detail',
          query: {
            pm: 1, // h5乐团报名
            config: JSON.stringify({
              ...data.paymentConfig,
              paymentType: data.paymentType
            }),
            orderNo: data.orderNo
          }
        });
      } finally {
        forms.submitLoading = false;
      }
    };

    onMounted(() => {
      getRegisterGoods();
    });

    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>
                          {item.goodsName}
                          <Tag class={styles.brandName}>12个月</Tag>
                        </h2>

                        <p class={[styles.model]}>{item.description}</p>

                        <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, index: number) => (
                    <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}
                                />
                              </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>
              <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;
                }
                if (!studentRegisterStore.getToken) {
                  forms.popupRegister = true;
                } else {
                  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://daya.ks3-cn-beijing.ksyun.com/202105/SWmqmvW.mp4'}
            />
          )}
        </Popup>

        <Popup
          v-model:show={forms.popupRegister}
          class={styles.registerPopup}
          position="bottom"
          round>
          <RegisterModal
            schoolId={forms.schoolId}
            schoolType={forms.schoolType}
            gradeYear={forms.gradeYear}
            onClose={() => (forms.popupRegister = false)}
            onSubmit={onRegisterSubmit}
          />
        </Popup>

        <MDialog
          title="提示"
          v-model:show={forms.dialogStatus}
          message={forms.dialogMessage}
          allowHtml={true}
          confirmButtonText="继续支付"
          onConfirm={() => {
            const paymentConfig = forms.dialogConfig.paymentConfig;
            router.push({
              path: '/order-detail',
              query: {
                pm: 1, // h5乐团报名
                config: JSON.stringify(paymentConfig.paymentConfig),
                orderNo: paymentConfig.orderNo
              }
            });
            countDown.pause();
          }}
          onCancel={(val: any) => {
            countDown.pause();
          }}
        />

        {/* 是否在微信中打开 */}
        <OWxTip />
      </div>
    );
  }
});
