import { computed, defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import ColHeader from '@/components/col-header'
import { useEventListener } from '@vant/use'
import iconStudent from '@common/images/icon_student.png'
import { Button, Image, Popup } from 'vant'
import { state as baseState, setLogin } from '@/state'

import iconMemo from './images/memo.png'
import iconTip from './images/tip.png'
import iconTitle1 from './images/title1.png'
import TheSticky from '@/components/the-sticky'
import request from '@/helpers/request'
import { tradeOrder } from '../trade/tradeOrder'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { orderStatus } from '@/views/order-detail/orderStatus'

export default defineComponent({
  name: 'discount-card',
  setup() {
    const router = useRouter()
    const state = reactive({
      discountDetail: {} as any,
      titleOpacity: 0,
      orderVisible: false,
      orderDetail: {} as any
    })
    const userInfo = computed(() => {
      const users = baseState.user.data
      console.log(users, 'users')
      return {
        username: users?.username,
        phone: users?.phone,
        avatar: users?.heardUrl,
        id: users?.userId,
        discountCardFlag: users?.discountCardFlag,
        discountEndTime: users?.discountEndTime,
        userVip: users?.userVip
      }
    })

    useEventListener('scroll', () => {
      const height =
        window.scrollY ||
        window.pageYOffset ||
        document.documentElement.scrollTop
      state.titleOpacity = height > 30 ? 1 : 0
    })

     // 取消支付
     const onCancelOrder = async () => {
      try {
        await request.post(`${baseState.platformApi}/userOrder/orderCancel`, {
          data: { orderNo: state.orderDetail.orderNo }
        })
        state.orderVisible = false
      } catch {
        //
      }
    }

    // 继续支付
    const onContinueOrder = async () => {
      const orderDetail = state.orderDetail || {}
      tradeOrder(orderDetail, () => {
        router.push({
          path: '/orderDetail',
          query: {
            orderType: orderDetail.orderType
          }
        })
      })
    }

    const onSubmit = async () => {
      try {

        // 判断是否有待支付订单
        const resPadding = await request.post(
          `${baseState.platformApi}/userOrder/getPendingOrder`,
          {
            data: { goodType: 'DISCOUNT' }
          }
        )
        console.log(resPadding, 'resPadding')
        if (resPadding?.data?.id) {
          state.orderVisible = true
          state.orderDetail = resPadding.data || {}
          return
        }

        let startTime = new Date()
        if(userInfo.value.discountCardFlag) {
          startTime = dayjs(userInfo.value.discountEndTime || new Date()).toDate()
        }
        let endTime = new Date()
        if (state.discountDetail.period === 'MONTH') {
          endTime = dayjs(startTime).add(1, 'month').toDate()
        } else if (state.discountDetail.period === 'QUARTERLY') {
          endTime = dayjs(startTime).add(3, 'month').toDate()
        } else if (state.discountDetail.period === 'YEAR_HALF') {
          endTime = dayjs(startTime).add(6, 'month').toDate()
        } else if (state.discountDetail.period === 'YEAR') {
          endTime = dayjs(startTime).add(1, 'year').toDate()
        }
        orderStatus.orderObject.orderType = 'DISCOUNT'
        orderStatus.orderObject.orderName = `畅学卡`
        orderStatus.orderObject.orderDesc = `畅学卡`
        orderStatus.orderObject.actualPrice = state.discountDetail.salePrice || 0
        orderStatus.orderObject.recomUserId = null
        orderStatus.orderObject.activityId = null
        orderStatus.orderObject.orderNo = ''

        orderStatus.orderObject.orderList = [
          {
            orderType: 'DISCOUNT',
            goodsName: `畅学卡`,
            id: state.discountDetail.id,
            title: '畅学卡',
            num: 1, // 购买个数
            salePrice: state.discountDetail.salePrice,
            period: state.discountDetail.period,
            price: state.discountDetail.salePrice,
            startTime: dayjs(startTime).format('YYYY-MM-DD'),
            endTime: dayjs(endTime).format('YYYY-MM-DD')
          }
        ]
        router.push({
          path: '/orderDetail',
          query: {
            orderType: 'DISCOUNT'
          }
        })
      } catch {
        //
      }
    }

    onMounted(async () => {
      try {
        const userInfo = await request.get(
          baseState.platformType === 'TEACHER'
            ? '/api-teacher/teacher/queryUserInfo'
            : '/api-student/student/queryUserInfo'
        )
        setLogin(userInfo.data)

        const { data } = await request.get(
          `${baseState.platformApi}/memberPriceSettings/getDiscount`
        )
        state.discountDetail = data
      } catch {
        //
      }
      
    })
    return () => (
      <div class={styles.discountCardContainer}>
        <ColHeader
          background={`rgba(255,255,255, ${state.titleOpacity})`}
          backIconColor="black"
          hideHeader={false}
          border={false}
        />
        <div class={styles.cardContainer}>
          <div class={styles.userSection}>
            <div
              class={[
                styles.userImgSection,
                (userInfo.value.userVip.vipType === 'SVIP' ||
                  userInfo.value.userVip.vipType === 'PERMANENT_SVIP') &&
                  styles.userSVip,
                userInfo.value.userVip.vipType === 'VIP' && styles.userVip,
                userInfo.value.userVip.svipEndDays > 0 ||
                userInfo.value.userVip.vipEndDays > 0
                  ? styles.isVip
                  : ''
              ]}
            >
              <Image
                class={styles.userImg}
                src={userInfo.value.avatar || iconStudent}
                fit="cover"
              />
              <i class={styles.showMemeber}></i>
            </div>
            <div class={styles.userInfo}>
              <div class={styles.userName}>
                <span class={styles.name}>{userInfo.value.username}</span>
                {userInfo.value.phone && (
                  <span class={styles.phone}>({userInfo.value.phone})</span>
                )}
              </div>
              <div class={styles.member_time}>
                {userInfo.value.discountCardFlag ? <>有效期至<span>{dayjs(userInfo.value.discountEndTime).format('YYYY-MM-DD')}</span></> : '您当前尚未开通畅学卡'}
              </div>
            </div>
          </div>

          <div class={styles.cardSection}>
            <div class={styles.top}>
              <img src={iconTitle1} class={styles.iconTitle1} />
              <div class={styles.priceSection}>
                <div class={styles.currentPrice}>
                  <div class={styles.l}>¥</div>
                  <div class={styles.c}>{state.discountDetail.salePrice || 0}</div>
                  <div class={styles.r}>/年</div>
                </div>
                <del class={styles.originPrice}>原价¥{state.discountDetail.originalPrice}/年</del>
              </div>
            </div>

            <div class={styles.chapter}>
              <div class={styles.chapterTop}>课程全部</div>
              <div class={styles.chapterBottom}>
                {(state.discountDetail.discountRate || 0) * 100}<i>折</i>
              </div>
            </div>
          </div>

          <div class={styles.imgSection}>
            <img src={iconMemo} class={styles.iconMemo} />
            <img src={iconTip} class={styles.iconTip} />
          </div>
        </div>

        <TheSticky position="bottom">
          <div class={styles.btnGroup}>
            <div class={styles.submitBtn} onClick={onSubmit}>
              {userInfo.value.discountCardFlag ? '立即续费' : <><i>¥</i>{state.discountDetail.salePrice||0}元立即开通</>}
            </div>
          </div>
        </TheSticky>


        <Popup
          v-model:show={state.orderVisible}
          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>
    )
  }
})
