import { defineComponent, onMounted, reactive, computed } from 'vue'
import styles from './index.module.less'
import ColHeader from '@/components/col-header'
import { postMessage } from '@/helpers/native-message'
import request from '@/helpers/request'
import { useEventListener } from '@vant/use'
import tip1Img from './imgs/tip1Img.png'
import tip2Img from './imgs/tip2Img.png'
import shadowImg from './imgs/shadow.png'
import svipCon1 from './imgs/svipCon1.png'
import svipCon2 from './imgs/svipCon2.png'
import dayjs from 'dayjs'
import { state as baseState } from '@/state'
import { Toast, Popup, Button } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { tradeOrder } from '@/student/trade/tradeOrder'
import { orderStatus } from '@/views/order-detail/orderStatus'
import { memberType, studyCardType } from '@/constant'

export default defineComponent({
  name: 'double12Active',
  setup(props, { emit }) {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      titleOpacity: 0,
      navBarHeight: 0,
      orderVisiable: false,
      orderDetail: {} as any,
      activityId: route.query.activityId
    })
    const activitData = reactive({
      activityStart: '2024-12-12 00:00:00',
      activityEnd: '2024-12-12 23:59:59',
      registrationPrice: 0,
      buyCount: 0, //  buyCount 小于1的时候 代表能无限购买
      buyNum: 0,
      vipCardId: 0,
      activityList: []
    })
    const subBtnState = computed(() => {
      if (Date.now() < new Date(activitData.activityStart).getTime()) {
        return {
          disable: true,
          text: '活动未开始'
        }
      } else if (Date.now() > new Date(activitData.activityEnd).getTime()) {
        return {
          disable: true,
          text: '活动已结束'
        }
      } else if (activitData.buyCount <= activitData.buyNum) {
        return {
          disable: true,
          text: '您已参与活动'
        }
      }
      return {
        disable: false,
        text: '立即购买'
      }
    })
    const userInfo = computed(() => {
      return baseState.user.data
    })
    // 是否为永久会员
    const isPermanent = computed(() => {
      return userInfo.value.userVip?.vipType === 'PERMANENT_SVIP' ? true : false
    })
    initActivit()
    function initActivit() {
      if (!state.activityId) return
      request
        .get(
          `/api-student/memberPriceSettings/getDoubleTwelve/${state.activityId}`
        )
        .then(res => {
          if (res.code === 200 && res.data) {
            const {
              activityStart,
              activityEnd,
              registrationPrice,
              buyCount,
              buyNum,
              vipCardId,
              activityRewardList
            } = res.data || {}
            activitData.activityStart = activityStart
            activitData.activityEnd = activityEnd
            activitData.registrationPrice = registrationPrice
            activitData.buyCount = buyCount < 1 ? 99999 : buyCount //buyCount 小于1的时候 代表能无限购买
            activitData.buyNum = buyNum
            activitData.vipCardId = vipCardId
            activitData.activityList = (activityRewardList || []).map(item => {
              const { rewardType, vipCardId, unit } = item.activityReward
              if (rewardType === 'DISCOUNT') {
                return {
                  goodType: rewardType,
                  goodName: `畅学卡 ${studyCardType[unit]}`,
                  goodNum: 1,
                  bizContent: vipCardId,
                  giftFlag: true,
                  vipEndDays: null,
                  goodsNum: 1,
                  unit
                }
              }
              return {
                goodType: rewardType,
                goodName: `小酷Ai ${rewardType} ${memberType[unit]}`,
                goodNum: 1,
                bizContent: vipCardId,
                giftFlag: true,
                vipEndDays: null,
                goodsNum: 1,
                unit
              }
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
    async function handleSubmit() {
      try {
        // 永久会员
        if (isPermanent.value) {
          Toast('您已是永久SVIP会员')
          return
        }
        const vipType = 'SVIP'
        // 判断是否有待支付订单
        const resPadding = await request.post(
          `/api-student/userOrder/getPendingOrder`,
          {
            data: { goodType: vipType }
          }
        )
        console.log(resPadding, 'resPadding')
        if (resPadding?.data?.id) {
          state.orderVisiable = true
          state.orderDetail = resPadding.data || {}
          return
        }
        // 组合订单参数
        const { data } = await request.post(
          `/api-student/memberPriceSettings/list`,
          {
            data: {
              status: 1
            }
          }
        )

        const member: any = (data?.list || []).find(item => {
          return item.id === activitData.vipCardId
        })
        if (!member) {
          Toast('未匹配上活动')
        }
        member.title = memberType[member.period]
        const startTime = dayjs(
          userInfo.value.userVip.svipEndDate || new Date()
        ).toDate()
        const endTime = dayjs(startTime).add(1, 'year').toDate()

        orderStatus.orderObject.orderType = vipType
        orderStatus.orderObject.orderName = `小酷Ai ${vipType} ${member.title}`
        orderStatus.orderObject.orderDesc = `小酷Ai ${vipType} ${member.title}`
        orderStatus.orderObject.actualPrice = activitData.registrationPrice
        orderStatus.orderObject.recomUserId = ''
        orderStatus.orderObject.activityId = state.activityId
        orderStatus.orderObject.orderNo = ''
        const orderData = {
          orderType: vipType,
          goodsName: `小酷Ai ${vipType} ${member.title}`,
          id: member.id,
          title: member.title,
          num: 1, // 购买个数
          salePrice: member.salePrice,
          period: member.period,
          vipEndDays: userInfo.value.userVip?.vipEndDays || 0, // 会员剩余天数
          svipEndDays: userInfo.value.userVip?.svipEndDays || 0,
          discount: member.discount, // 是否有折扣
          discountPrice: member.discountPrice, // 折扣金额
          price: activitData.registrationPrice,
          startTime: dayjs(startTime).format('YYYY-MM-DD'),
          endTime: dayjs(endTime).format('YYYY-MM-DD'),
          recomUserId: '',
          activityBuyCount: 0, // 活动购买限制次数
          activityList: [], // 活动赠送的东西
          discountEndTime: userInfo.value.discountEndTime, // 畅学卡结束时间
          discountStartTime: userInfo.value.discountStartTime // 畅学卡开始时间
        }
        const canBuyNum = activitData.buyCount - activitData.buyNum
        if (canBuyNum > 0) {
          orderData.activityBuyCount = canBuyNum
          orderData.activityList = activitData.activityList
        }
        orderStatus.orderObject.orderList = [orderData]
        router.push({
          path: '/orderDetail',
          query: {
            orderType: vipType
          }
        })
      } catch {
        //
      }
    }
    // 取消支付
    const onCancelOrder = async () => {
      try {
        await request.post(`/api-student/userOrder/orderCancel`, {
          data: { orderNo: state.orderDetail.orderNo }
        })
        state.orderVisiable = false
      } catch {
        //
      }
    }
    // 继续支付
    const onContinueOrder = async () => {
      const orderDetail = state.orderDetail || {}
      tradeOrder(orderDetail, () => {
        router.push({
          path: '/orderDetail',
          query: {
            orderType: orderDetail.orderType
          }
        })
      })
    }
    onMounted(() => {
      postMessage({ api: 'getNavHeight' }, res => {
        const { content } = res as any
        const dpi = content.dpi || 2
        if (content.navHeight) {
          const navHeight = content.navHeight / dpi
          state.navBarHeight = navHeight
        }
      })
    })
    useEventListener('scroll', () => {
      const height =
        window.scrollY ||
        window.pageYOffset ||
        document.documentElement.scrollTop
      state.titleOpacity = height > 30 ? 1 : 0
    })
    return () => (
      <div
        class={styles.double12Active}
        style={{
          '--navBarHeight': `${state.navBarHeight}px`
        }}
      >
        <ColHeader
          background={`rgba(255,255,255, ${state.titleOpacity})`}
          color={`rgba(0,0,0, ${state.titleOpacity})`}
          backIconColor="black"
          hideHeader={false}
          border={false}
        />
        <div class={styles.headImg}></div>
        <div class={styles.activeArea1}>
          <img class={styles.tip1} src={tip1Img} />
          <img class={styles.shadowImg} src={shadowImg} />
          <div class={styles.activeCon}>
            <div class={styles.activeBox}>活动时间</div>
            <div class={styles.activeTimes}>
              {`${dayjs(activitData.activityStart).format(
                'YYYY年MM月DD日HH:MM'
              )}-${dayjs(activitData.activityEnd).format(
                'YYYY年MM月DD日HH:MM'
              )}`}
            </div>
          </div>
          <div class={styles.activeCon}>
            <div class={styles.activeBox}>活动内容</div>
            <div class={styles.activeListCon}>
              <div class={styles.activeList}>
                SVIP年度会员限时特惠至
                <span class={styles.number}>
                  {' '}
                  {activitData.registrationPrice}{' '}
                </span>
                <span>元</span>
              </div>
              <div class={styles.activeList}>
                活动期间<span>买一年送一年</span>
              </div>
              <div class={styles.activeList}>
                同时额外<span>获赠一年畅学卡</span>，享受约课75折！
              </div>
            </div>
          </div>
          <div class={styles.activeContent}>
            <div class={[styles.vipNumber, styles.vipBuy1]}>
              <div>SVIP年度会员</div>
              <div>价值1280元</div>
            </div>{' '}
            <div class={[styles.vipNumber, styles.vipBuy2]}>
              <div>SVIP年度会员</div>
              <div>价值1280元</div>
            </div>{' '}
            <div class={[styles.vipNumber, styles.vipBuy3]}>
              <div>畅学卡一年期</div>
              <div>价值129元</div>
            </div>
            <div class={styles.svipDetails}>
              <span>¥</span>
              <span>{activitData.registrationPrice}</span>
              <span>(SVIP会员买1年赠1年，还送1年畅学)</span>
            </div>
          </div>
        </div>
        <img class={styles.activeArea2} src={svipCon1} />
        <div class={styles.activeArea3}>
          <img class={styles.tip1} src={tip2Img} />
          <img class={styles.shadowImg} src={shadowImg} />
          <div class={styles.titCon}>
            专为音乐学习者设计的全方位学习通行证，畅学卡生效期间，购买任何VIP定制课、趣纠课、直播课、视频课
            <span>享受75折</span>优惠，助您在音乐道路上更进一步。
          </div>
          <div class={styles.classCon}>
            <div class={styles.classBox}>
              课程全部<span>75</span>
              <span>折</span>
            </div>
          </div>
        </div>
        <img class={styles.activeArea4} src={svipCon2} />
        <div class={styles.subBtnCon}>
          <div
            class={[styles.subBtn, subBtnState.value.disable && styles.disable]}
            onClick={() => {
              !subBtnState.value.disable && handleSubmit()
            }}
          >
            {subBtnState.value.text}
          </div>
        </div>
        <Popup
          v-model:show={state.orderVisiable}
          style={{ background: 'transparent' }}
          closeOnClickOverlay={false}
        >
          <div class={styles.dialogContainer}>
            <div class={styles.dialogTitle}>提示</div>
            <div class={styles.dialogContent}>
              您有待支付的订单,是否继续支付
            </div>

            <div class={[styles.dialogBtnGroup, styles.orderGroup]}>
              <Button round type="default" plain block onClick={onCancelOrder}>
                取消订单
              </Button>
              <Button
                round
                type="primary"
                block
                class={styles.dialogBtn}
                onClick={onContinueOrder}
              >
                继续支付
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    )
  }
})
