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

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 {
      activityId: query.activityId,
      recomUserId: query.recomUserId,
      apiSuffix:
        state.platformType === 'STUDENT' ? '/api-student' : '/api-teacher',
      agreeStatus: false,
      functionList: [],
      memberList: [],
      selectMember: {} as any,
      params: {
        page: 1,
        rows: 20
      },
      discountTeacher: {
        avatar: '',
        discount: 0,
        username: ''
      }
    }
  },
  computed: {
    userInfo() {
      const users = state.user.data
      return {
        username: users?.username,
        phone: users?.phone,
        avatar: users?.heardUrl,
        memberRankSettingId: users?.memberRankSettingId,
        membershipDays: users?.membershipDays,
        membershipEndTime: users?.membershipEndTime
      }
    }
  },
  async mounted() {
    try {
      const res = await request.post(
        `${this.apiSuffix}/memberPriceSettings/vipPermissions`
      )
      const result = res.data || []
      this.functionList = result.map((item: any) => {
        return {
          title: item.paramName,
          icon: getAssetsHomeFile(`${item.paramValue}.png`)
        }
      })

      const setting = await request.post(
        `${this.apiSuffix}/memberPriceSettings/list`,
        {
          data: {
            activityId: Number(this.activityId),
            userId: this.recomUserId
          }
        }
      )
      const { list, ...more } = setting.data
      this.discountTeacher = {
        ...more
      }
      const settingResult = list || []
      const settingList: any = []
      settingResult.forEach((item: any) => {
        const tempItem = {
          title: '',
          salePrice: item.salePrice,
          originalPrice: item.originalPrice,
          period: item.period,
          id: item.id,
          discount: item.discount,
          discountPrice: item.discountPrice,
          status: false
        }

        tempItem.title = memberType[item.period]

        item.period !== 'DAY' && settingList.push(tempItem)
      })

      if (settingList.length > 0) {
        settingList[0].status = true
        this.selectMember = settingList[0]
      }
      console.log(settingList)
      this.memberList = settingList
    } catch {}
  },
  methods: {
    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
    },
    onSubmit() {
      const member: any = this.selectMember
      // 判断是否有会员
      const startTime = this.userInfo.memberRankSettingId
        ? dayjs(this.userInfo.membershipEndTime).toDate()
        : new Date()
      let endTime = new Date()
      if (member.period === 'MONTH') {
        endTime = dayjs(startTime).add(1, 'month').toDate()
      } else if (member.period === 'QUARTERLY') {
        endTime = dayjs(startTime).add(3, 'month').toDate()
      } else if (member.period === 'YEAR_HALF') {
        endTime = dayjs(startTime).add(6, 'month').toDate()
      } else if (member.period === 'YEAR') {
        endTime = dayjs(startTime).add(1, 'year').toDate()
      }

      orderStatus.orderObject.orderType = 'VIP'
      orderStatus.orderObject.orderName = '小酷Ai' + member.title
      orderStatus.orderObject.orderDesc = '小酷Ai' + member.title
      orderStatus.orderObject.actualPrice = this.calcSalePrice(member)
      orderStatus.orderObject.recomUserId = this.recomUserId
      orderStatus.orderObject.activityId = this.activityId
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'VIP',
          goodsName: '小酷Ai' + member.title,
          id: member.id,
          title: member.title,
          price: this.calcSalePrice(member),
          startTime: dayjs(startTime).format('YYYY-MM-DD'),
          endTime: dayjs(endTime).format('YYYY-MM-DD'),
          recomUserId: this.recomUserId
        }
      ]
      this.$router.push({
        path: '/orderDetail',
        query: {
          orderType: 'VIP'
        }
      })
    }
  },
  render() {
    return (
      <div class={styles['member-center']}>
        <ColHeader 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.memberRankSettingId && (
                    <Image
                      class={styles.level}
                      src="https://daya.ks3-cn-beijing.ksyun.com/202107/ScSTL1D.png"
                    />
                  )}
                  <span
                    class={styles.phone}
                    v-html={`（${this.userInfo.phone}）`}
                  ></span>
                </div>
              ),
              label: () => (
                <div class={styles.member_time}>
                  {this.userInfo.memberRankSettingId ? (
                    <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>

            {/* 判断是否有推荐老师 */}
            {this.discountTeacher.discount == 1 && (
              <div class={styles.memberDiscount}>
                <Image
                  src={this.discountTeacher.avatar || iconTeacher}
                  class={styles.discountAvatar}
                />

                <span class={styles.discountName}>
                  {this.discountTeacher.username}老师的专属优惠～
                </span>

                <Image src={iconGift} class={styles.discountGift} />
              </div>
            )}

            <div class={styles['system-list']}>
              {this.memberList.map((item: any) => (
                <div
                  class={[styles['system-item'], item.status && styles.active]}
                  onClick={() => {
                    this.memberList.forEach((item: any) => {
                      item.status = false
                    })
                    item.status = true
                    this.selectMember = item
                  }}
                >
                  <div class={styles.discountItem}>
                    {item.discount == 1 && <img src={iconDiscount} />}
                  </div>
                  <p class={styles.title}>{item.title}</p>
                  <p class={styles.price}>
                    <span>￥</span>
                    {moneyFormat(this.calcSalePrice(item), '0,0[.]00')}
                  </p>
                  <del class={styles.originalPrice}>
                    ￥{moneyFormat(item.originalPrice, '0,0[.]00')}
                  </del>
                </div>
              ))}
            </div>
          </div>

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

          {this.functionList.length > 0 && (
            <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>
          )}

          {/* <ColProtocol
            v-model={this.agreeStatus}
            showHeader
            style={{ paddingLeft: 0, paddingRight: 0, marginBottom: '64px' }}
          /> */}
        </div>
        <div class={styles.btnGroup}>
          <div class={styles.priceSection}>
            支付金额：
            <div class={styles.price}>
              <span class={styles.priceUnit}>￥</span>
              <span class={styles.priceNum}>
                {(this as any).$filters.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}
          >
            立即支付
          </Button>
        </div>
      </div>
    )
  }
})
