import { Button, Cell, Icon, Image, showConfirmDialog } from 'vant';
import { defineComponent } from 'vue';
import styles from './index.module.less';
import request from '@/helpers/request';
import iconStudent from '@common/images/icon-student.png';
// import iconMemberLogo from './images/member_logo.png';
import iconGift from '../student-register/images/icon-gift.png';
import { moneyFormat } from '@/helpers/utils';
import OHeader from '@/components/m-header';
import member1 from './images/member-1.png';
import member2 from './images/member-2.png';
import ODialog from '@/components/m-dialog';
import { useEventListener, useWindowScroll } from '@vueuse/core';

export default defineComponent({
  name: 'MemberCenter',
  data() {
    return {
      functionList: [] as any,
      selectMember: {} as any,
      users: {} as any,
      memberStatus: false,
      background: 'transparent',
      color: '#fff'
    };
  },
  computed: {
    userInfo() {
      const users: any = this.users;
      return {
        username: users?.nickname || '',
        phone: users?.phone || '',
        avatar: users?.avatar,
        id: users?.id,
        isVip: users?.vipMember,
        membershipGiftDays: users?.membershipGiftDays,
        membershipDays: users?.membershipDays,
        membershipEndTime: users?.membershipEndTime
      };
    }
  },
  async mounted() {
    useEventListener(document, 'scroll', () => {
      const { y } = useWindowScroll();
      if (y.value > 52) {
        this.background = '#fff';
        this.color = '#323333';
      } else {
        this.background = 'transparent';
        this.color = '#fff';
      }
    });
    try {
      const userInfo = await request.get('/edu-app/student/member');
      this.users = userInfo.data || {};

      const { data } = await request.post(`/edu-app/cityFeeSetting/member`);
      this.selectMember = data;

      this.paymentOrderUnpaid();
    } catch {
      //
    }
    //
  },
  methods: {
    // 查询未支付订单
    async paymentOrderUnpaid() {
      try {
        const { data } = await request.get('/edu-app/userPaymentOrder/unpaid', {
          requestType: 'form',
          params: {
            paymentType: 'VIP'
          }
        });
        // 判断是否有待支付订单
        if (data.id) {
          showConfirmDialog({
            message: '您有待支付的订单,是否继续支付',
            cancelButtonText: '取消订单',
            confirmButtonText: '继续支付'
          })
            .then(() => {
              const paymentConfig = data.paymentConfig;
              this.$router.push({
                path: '/order-detail',
                query: {
                  config: JSON.stringify(paymentConfig.paymentConfig),
                  orderNo: paymentConfig.orderNo
                }
              });
            })
            .catch(async () => {
              try {
                await request.post(
                  '/edu-app/userPaymentOrder/cancelPayment/' + data.orderNo
                );
              } catch {
                //
              }
            });
        }
      } catch {
        //
      }
    },
    calcSalePrice(item: any) {
      // discount
      if (item.discount === 1) {
        const tempPrice = Number(
          (item.salePrice - item.discountPrice).toFixed(2)
        );
        return tempPrice >= 0 ? tempPrice : 0;
      }
      return item.salePrice;
    },
    // 购买
    async onSubmit() {
      try {
        const selectMember = this.selectMember;
        const params: any = [
          {
            goodsId: selectMember.id,
            goodsNum: 1,
            goodsType: 'VIP',
            paymentCashAmount: selectMember.salePrice, // 现金支付金额
            paymentCouponAmount: 0 // 优惠券金额
          }
        ]; // 支付参数

        // 创建订单
        const { data } = await request.post(
          '/edu-app/userPaymentOrder/executeOrder',
          {
            data: {
              orderType: 'VIP',
              paymentCashAmount: this.selectMember.salePrice || 0,
              paymentCouponAmount: 0,
              goodsInfos: params,
              orderName: '数字化器乐学练工具',
              orderDesc: '数字化器乐学练工具'
            }
          }
        );
        const res = await request.get(
          '/edu-app/userPaymentOrder/detail/' + data.orderNo
        );
        if (res.data.status !== 'WAIT_PAY' && res.data.status !== 'PAYING') {
          this.$router.push({
            path: '/payment-result',
            query: {
              orderNo: data.orderNo
            }
          });
        } else {
          this.$router.push({
            path: '/order-detail',
            query: {
              config: JSON.stringify(data.paymentConfig),
              orderNo: data.orderNo
            }
          });
        }
      } catch (e: any) {
        //
        console.log(e);
      }
    }
  },
  render() {
    return (
      <div class={styles['member-center']}>
        <OHeader
          background={this.background}
          color={this.color}
          border={false}
        />
        <div class={styles.member_container}>
          <Cell
            class={[styles.userMember]}
            labelClass={styles.timeRemaining}
            center
            v-slots={{
              icon: () => (
                <div class={styles.userImgSection}>
                  <Image
                    class={styles.userImg}
                    src={this.userInfo.avatar || iconStudent}
                    fit="cover"
                  />
                </div>
              ),
              title: () => (
                <div class={styles.userInfo}>
                  <span class={styles.name}>{this.userInfo.username}</span>
                  {!!this.userInfo.isVip && (
                    <Image
                      class={styles.level}
                      src="https://daya.ks3-cn-beijing.ksyun.com/202107/ScSTL1D.png"
                    />
                  )}
                  {this.userInfo.phone && (
                    <span
                      class={styles.phone}
                      v-html={`（${this.userInfo.phone}）`}></span>
                  )}
                </div>
              ),
              label: () => (
                <div class={styles.member_time}>
                  <>
                    {this.userInfo.isVip ? (
                      <div>
                        使用有效期剩余
                        <span class={styles.remaining}>
                          {this.userInfo.membershipDays}
                        </span>
                        天
                      </div>
                    ) : (
                      <div>您还未开通器乐学练工具哟</div>
                    )}
                  </>
                </div>
              )
            }}></Cell>
        </div>

        <div class={[styles.memberContainer]}>
          <div
            class={[
              styles.memberItem,
              this.users.membershipGiftDays > 0 ? styles.memberGift : ''
            ]}>
            <p class={[styles.title]}>
              <strong>数字化</strong>器乐学练工具
              <span>12个月</span>
            </p>
            <div class={styles.priceGroup}>
              <p class={styles.price}>
                <span>￥</span>
                {moneyFormat(this.selectMember.salePrice)}
              </p>
              {this.selectMember.salePrice <
                this.selectMember.originalPrice && (
                <del class={styles.originalPrice}>
                  ￥{moneyFormat(this.selectMember.originalPrice)}
                </del>
              )}
            </div>
            {this.users.membershipGiftDays > 0 && (
              <Cell border={false} class={styles.giftCell}>
                {{
                  title: () => (
                    <div class={styles.gift}>
                      <img src={iconGift} class={styles.iconGift} />
                      现在购买赠送{' '}
                      <span>{this.users.membershipGiftDays || 0}</span>
                      天有效期
                    </div>
                  )
                }}
              </Cell>
            )}
          </div>

          <div class={styles.memberImgs}>
            <img src={member1} />
            <img src={member2} />
          </div>
        </div>

        <div class={styles.btnGroup}>
          <div class={styles.priceSection}>
            工具领取：
            <div class={styles.price}>
              <span class={styles.priceUnit}>￥</span>
              <span class={styles.priceNum}>
                {moneyFormat(this.calcSalePrice(this.selectMember) || 0)}
              </span>
            </div>
          </div>
          {this.userInfo.id ? (
            <Button round class={styles.btn} onClick={this.onSubmit}>
              立即领取
            </Button>
          ) : (
            ''
          )}
        </div>

        <ODialog
          v-model:show={this.memberStatus}
          title="待激活团练宝"
          message="为让团员有效使用乐团学习工具，首次加入乐团且购买团练宝的团员，团练宝的生效时间为乐团首次训练之日，具体训练时间可查看课表。"
          messageAlign="left"
          dialogMarginTop="env(safe-area-inset-top)"
          confirmButtonText="我知道了"
        />
      </div>
    );
  }
});
