import { Button, Cell, Icon, Image, Popup, showConfirmDialog, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import request from '@/helpers/request'
import { setLogin, state } from '@/state'
import iconStudent from '@common/images/icon_student.png'
import iconTeacher from '@common/images/icon_teacher.png'
import iconDiscount from './images/icon_discount.png'
import iconMemberLogo from './images/member_logo.png'
// import { orderStatus } from '@/views/order-detail/orderStatus'
import dayjs from 'dayjs'
import { memberType } from '@/constant'
import { moneyFormat } from '@/helpers/utils'
import OHeader from '@/components/o-header'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}

export default defineComponent({
  name: 'MemberCenter',
  data() {
    const query = this.$route.query
    return {
      functionList: [] as any,
      selectMember: {} as any,
      users: {} as any
    }
  },
  computed: {
    userInfo() {
      const users: any = this.users

      return {
        username: users?.nickname || '',
        phone: users?.phone || '',
        avatar: users?.avatar,
        id: users?.id,
        isVip: users?.vipMember,
        membershipDays: users?.membershipDays,
        membershipEndTime: users?.membershipEndTime
      }
    }
  },
  async mounted() {
    try {
      const userInfo = await request.get('/api-student/student/member')
      this.users = userInfo.data || {}
      this.functionList = [
        {
          title: '五线谱<br />跟播',
          icon: getAssetsHomeFile(`1.png`)
        },
        {
          title: '演奏指法<br />跟播',
          icon: getAssetsHomeFile(`2.png`)
        },
        {
          title: '原声/伴奏<br />切换',
          icon: getAssetsHomeFile(`3.png`)
        },
        {
          title: '播放速度<br />调整',
          icon: getAssetsHomeFile(`4.png`)
        },
        {
          title: '五线谱选段<br />播放',
          icon: getAssetsHomeFile(`5.png`)
        },
        {
          title: '智能评测',
          icon: getAssetsHomeFile(`6.png`)
        },
        {
          title: '评测报告',
          icon: getAssetsHomeFile(`7.png`)
        },
        {
          title: '评测音视频<br />云储存',
          icon: getAssetsHomeFile(`8.png`)
        }
      ]

      const { data } = await request.post(`/api-student/cityFeeSetting/member`)
      this.selectMember = data

      this.paymentOrderUnpaid()
    } catch {
      //
    }
    //
  },
  methods: {
    // 查询未支付订单
    async paymentOrderUnpaid() {
      try {
        const { data } = await request.get('/api-student/userPaymentOrder/unpaid', {
          requestType: 'form',
          params: {
            paymentType: 'VIP'
          }
        })
        // 判断是否有待支付订单
        if (data.id) {
          showConfirmDialog({
            message: '您有待支付的订单,是否继续支付',
            cancelButtonText: '取消订单',
            confirmButtonText: '继续支付'
          })
            .then(() => {
              const paymentConfig = data.paymentConfig
              this.$router.push({
                path: '/orderDetail',
                query: {
                  config: JSON.stringify(paymentConfig.paymentConfig),
                  orderNo: paymentConfig.orderNo
                }
              })
            })
            .catch(async () => {
              try {
                await request.post('/api-student/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('/api-student/userPaymentOrder/executeOrder', {
          data: {
            orderType: 'VIP',
            paymentCashAmount: this.selectMember.salePrice || 0,
            paymentCouponAmount: 0,
            goodsInfos: params,
            orderName: '团练宝购买',
            orderDesc: '团练宝购买'
          }
        })

        console.log(data)
        this.$router.push({
          path: '/orderDetail',
          query: {
            config: JSON.stringify(data.paymentConfig),
            orderNo: data.orderNo
          }
        })
      } catch (e: any) {
        //
        console.log(e)
      }
    }
  },
  render() {
    return (
      <div class={styles['member-center']}>
        <OHeader background="#ffe5cc" />
        <div class={styles.member_container}>
          <Cell
            class={styles.userMember}
            labelClass={styles.timeRemaining}
            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}>
            <div class={styles.title}>
              会员<span>VIP</span>
            </div>

            <div class={styles['system-list']}>
              <div class={[styles['system-item'], styles.active]}>
                <p class={[styles.title, 'van-hairline--bottom']}>
                  半年会员
                  <span>（6个月）</span>
                </p>
                <div class={styles.priceGroup}>
                  <p class={styles.price}>
                    <span>￥</span>
                    {moneyFormat(this.selectMember.salePrice)}
                  </p>
                  <del class={styles.originalPrice}>
                    ￥{moneyFormat(this.selectMember.originalPrice)}
                  </del>
                </div>
              </div>
            </div>
          </div>

          <div class={[styles.intro]}>
            <p>
              团练宝会员使用包括平台提供教材的所有训练乐谱，并专享“乐器练习云教练”八大核心功能，孩子在家就能轻松完成乐器自主规范练习。
            </p>
          </div>

          <div class={styles.memberItem}>
            <div class={styles.title}>会员功能</div>

            <div class={styles.member_function}>
              {this.functionList.map((item: any) => (
                <div class={styles.function_item}>
                  <Icon name={item.icon} size={34} />
                  <div class={styles.function_text} v-html={item.title}></div>
                </div>
              ))}
            </div>
          </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>
            {this.selectMember?.discount == 1 && (
              <div class={[styles.discountItem, styles.discountBuy]}>
                <img src={iconDiscount} />
              </div>
            )}
          </div>
          <Button
            color="linear-gradient(220deg, #DFA164 0%, #FAC87E 100%)"
            round
            class={styles.btn}
            onClick={this.onSubmit}
          >
            {this.userInfo.isVip ? '立即续费' : '立即开通'}
          </Button>
        </div>
      </div>
    )
  }
})
