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 { 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() {
    return {
      agreeStatus: false,
      functionList: [],
      memberList: [],
      selectMember: {} as any,
      params: {
        page: 1,
        rows: 20
      }
    }
  },
  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(
        '/api-student/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(
        '/api-student/memberPriceSettings/list',
        {
          data: {}
        }
      )
      const settingResult = setting.data || []
      const settingList: any = []
      settingResult.forEach((item: any) => {
        const tempItem = {
          title: '',
          salePrice: item.salePrice,
          originalPrice: item.originalPrice,
          period: item.period,
          id: item.id,
          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]
      }
      this.memberList = settingList
    } catch {}
  },
  methods: {
    onSubmit() {
      const member: any = this.selectMember
      // 判断是否有会员
      let 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 = member.salePrice
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'VIP',
          goodsName: '小酷Ai' + member.title,
          id: member.id,
          title: member.title,
          price: member.salePrice,
          startTime: dayjs(startTime).format('YYYY-MM-DD'),
          endTime: dayjs(endTime).format('YYYY-MM-DD')
        }
      ]
      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>

            <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
                  }}
                >
                  <p class={styles.title}>{item.title}</p>
                  <p class={styles.price}>
                    <span>￥</span>
                    {moneyFormat(item.salePrice, '0,0[.]00')}
                  </p>
                  <del class={styles.originalPrice}>
                    ￥{moneyFormat(item.originalPrice, '0,0[.]00')}
                  </del>
                </div>
              ))}
              {/* <div class={[styles['system-item'], styles.active]}>
                <p class={styles.title}>月度会员</p>
                <p class={styles.price}>
                  <span>￥</span>199
                </p>
                <del class={styles.originalPrice}>￥199</del>
              </div>

              <div class={styles['system-item']}>
                <p class={styles.title}>月度会员</p>
                <p class={styles.price}>
                  <span>￥</span>199
                </p>
                <del class={styles.originalPrice}>￥199</del>
              </div>

              <div class={styles['system-item']}>
                <p class={styles.title}>月度会员</p>
                <p class={styles.price}>
                  <span>￥</span>199
                </p>
                <del class={styles.originalPrice}>￥199</del>
              </div>

              <div class={styles['system-item']}>
                <p class={styles.title}>月度会员</p>
                <p class={styles.price}>
                  <span>￥</span>199
                </p>
                <del class={styles.originalPrice}>￥199</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.selectMember?.salePrice || 0
                )}
              </span>
            </div>
          </div>
          <Button
            color="linear-gradient(220deg, #DFA164 0%, #FAC87E 100%)"
            round
            class={styles.btn}
            onClick={this.onSubmit}
          >
            立即支付
          </Button>
        </div>
      </div>
    )
  }
})
