import ColProtocol from '@/components/col-protocol'
import { Button, Dialog, Icon, Popup, Sticky, Toast } from 'vant'
import ColPopup from '@/components/col-popup'
import { defineComponent } from 'vue'
import { postMessage } from '@/helpers/native-message'
import styles from './index.module.less'
import UserAuth from './userAuth'
import request from '@/helpers/request'

// 调用原生支付
// postMessage({ api: 'paymentOrder', content: { orderNo: 0 } })
// listenerMessage({ api: 'paymentResult', callback: (res: any) => {
//   status: 'success | fail'
// }})

import iconTips from '@common/images/icon_tips.png'
import Payment from './payment'
import ColHeader from '@/components/col-header'
import { state } from '@/state'
import { orderInfos, orderStatus } from './orderStatus'
import OrderVideo from './order-video'
import OrderLive from './order-live'
import OrderPractice from './order-practice'
import OrderVip from './order-vip'
import OrderMusic from './order-music'
import { moneyFormat } from '@/helpers/utils'
import OrderPinao from './order-pinao'
import { getMusicDetail } from '@/student/trade/tradeOrder'
import OrderActive from './order-active'

export default defineComponent({
  name: 'order-detail',
  data() {
    const query = this.$route.query
    return {
      loading: false, // 是否加载中，为了处理0元订单（）
      orderType: query.orderType,
      recomUserId: query.recomUserId, // 推荐人id
      activityId: query.activityId, // 活动编号
      id: query.id,
      agreeStatus: false,
      popupShow: false,
      paymentStatus: false,
      orderPrice: 0 // 支付金额
    }
  },
  unmounted() {
    // 销毁时解绑监听
    orderStatus.orderInfo = {
      orderNo: '',
      actualPrice: 0,
      payStatus: false
    }
  },
  computed: {
    orderList() {
      // 商品列表
      const orderObject = orderStatus.orderObject
      return orderObject.orderList || []
    }
    // orderInfos() {
    //   // 商品列表
    //   const orderList = orderStatus.orderObject.orderList || []
    //   return orderList.map((item: any) => {
    //     const params = {
    //       goodType: item.orderType,
    //       goodName: item.goodsName,
    //       recomUserId: item.recomUserId, // 推荐人id
    //       bizContent: {}
    //     }
    //     if (item.orderType === 'VIDEO') {
    //       params.bizContent = {
    //         videoLessonGroupId: item.courseGroupId,
    //         payMoney: item.coursePrice || 0
    //       }
    //     } else if (item.orderType === 'LIVE') {
    //       params.bizContent = {
    //         groupId: item.courseGroupId
    //       }
    //     } else if (item.orderType === 'PRACTICE') {
    //       const tempTime = item.classTime || []
    //       const classCourse: any = []
    //       tempTime.forEach((time: any) => {
    //         classCourse.push({
    //           classDate: time.classDate,
    //           startTime: time.startTime,
    //           endTime: time.endTime
    //         })
    //       })
    //       params.bizContent = {
    //         courseGroupName: item.courseGroupName,
    //         courseIntroduce: item.courseIntroduce,
    //         subjectId: item.subjectId,
    //         singleCourseMinutes: item.singleCourseMinutes,
    //         courseNum: item.courseNum,
    //         coursePrice: item.coursePrice,
    //         teacherId: item.teacherId,
    //         classTime: classCourse
    //       }
    //     } else if (item.orderType === 'VIP') {
    //       params.bizContent = item.id
    //     } else if (item.orderType === 'MUSIC') {
    //       params.bizContent = {
    //         musicSheetId: item.id,
    //         actualPrice: item.actualPrice || 0,
    //         clientType: state.platformType
    //       }
    //     } else if (item.orderType === 'PINAO_ROOM') {
    //       params.bizContent = item.id
    //     } else if (item.orderType === 'ACTI_REGIST') {
    //       params.bizContent = {
    //         activityId: item.activityId
    //       }
    //     }
    //     return params
    //   })
    // }
  },
  async mounted() {
    // 判断是否是曲目购买（只有智能陪练才会有入口），其它地方不会有入口
    if (this.orderType == 'MUSIC' && this.id) {
      try {
        const item = await getMusicDetail(this.id)
        orderStatus.orderObject.orderType = 'MUSIC'
        orderStatus.orderObject.orderName = item.musicSheetName
        orderStatus.orderObject.orderDesc = item.musicSheetName
        orderStatus.orderObject.actualPrice = item.musicPrice
        orderStatus.orderObject.recomUserId = this.recomUserId
        orderStatus.orderObject.activityId = this.activityId
        // 判断当前订单是否在支付中
        if (['WAIT_PAY', 'PAYING'].includes(item.orderStatus)) {
          orderStatus.orderObject.orderNo = item.orderNo
        } else if (['PAID', 'CLOSE', 'FAIL'].includes(item.orderStatus)) {
          // 判断订单是否是其它状态
          Toast('订单有误')
          postMessage({ api: 'back', content: {} })
        }
        orderStatus.orderObject.orderList = [
          {
            orderType: 'MUSIC',
            goodsName: item.musicSheetName,
            actualPrice: item.musicPrice,
            ...item
          }
        ]
      } catch {
        //
      }
    }
    this.orderPrice = orderStatus.orderObject.actualPrice || 0

    // 0元支付特别处理
    if (this.orderPrice === 0 && orderStatus.orderObject.orderType) {
      this.loading = true
      this.onSubmit()
    }
  },
  methods: {
    onAuthSuccess() {
      // console.log('auth success')
      this.popupShow = false
      this.onSubmit() // 实名成功后自动支付
    },
    async onSubmit() {
      // console.log(this.orderInfos)
      if (this.orderPrice > 0) {
        if (!this.agreeStatus) {
          Toast('请先阅读并同意《酷乐秀平台服务协议》')
          return
        }
        const users = state.user.data
        // 判断是否需要实名认证
        if (!users?.realName || !users?.idCardNo) {
          this.popupShow = true
          return
        }
      }

      // 判断是否有订单号
      if (orderStatus.orderObject.orderNo) {
        this.paymentStatus = true
        return
      }

      // 正常支付
      try {
        const orderObject = orderStatus.orderObject
        const url =
          state.platformType === 'TEACHER'
            ? '/api-teacher/userOrder/executeOrder'
            : '/api-student/userOrder/executeOrder'
        const res = await request.post(url, {
          data: {
            orderName: orderObject.orderName,
            orderDesc: orderObject.orderDesc,
            orderType: orderObject.orderType,
            actualPrice: orderObject.actualPrice || 0,
            recomUserId: orderObject.recomUserId,
            activityId: orderObject.activityId,
            orderInfos: [...orderInfos()]
          }
        })
        const result = res.data || {}
        // 支付成功
        if (result.status == 'PAID') {
          this.$router.replace({
            path: '/tradeDetail',
            query: {
              orderNo: result.orderNo
            }
          })
          return
        }

        // 拉起支付方式
        orderStatus.orderObject.orderNo = result.orderNo
        orderStatus.orderObject.actualPrice = result.actualPrice
        this.paymentStatus = true
      } catch {
        this.loading = false
        if (this.orderPrice === 0) {
          Dialog.alert({
            title: '提示',
            message: '支付失败，请稍后重试！',
            confirmButtonText: '确定',
            confirmButtonColor: '#2dc7aa'
          })
        }
      }
    },
    onBackOut() {
      // 关闭订单后需要重置数据
      orderStatus.orderObject = {
        orderNo: '',
        actualPrice: 0,
        orderName: '',
        orderDesc: '',
        orderType: '',
        recomUserId: null as any,
        orderList: []
      }
    }
  },
  render() {
    return (
      <div class={styles['order-detail']}>
        <ColHeader />

        {!this.loading && (
          <>
            {this.orderList.map((item: any) => {
              if (item.orderType === 'VIDEO') {
                return <OrderVideo item={item} />
              } else if (item.orderType === 'LIVE') {
                return <OrderLive item={item} />
              } else if (item.orderType === 'PRACTICE') {
                return <OrderPractice item={item} />
              } else if (item.orderType === 'VIP') {
                return <OrderVip item={item} />
              } else if (item.orderType === 'MUSIC') {
                return <OrderMusic item={item} />
              } else if (item.orderType === 'PINAO_ROOM') {
                return <OrderPinao item={item} />
              } else if (item.orderType === 'ACTI_REGIST') {
                return <OrderActive item={item} />
              }
            })}

            {/* <div class={styles.tips}>
          <h3>
            <Icon name={iconTips} size={15} />
            温馨提示
          </h3>
          
          {state.platformType === 'TEACHER' ? (
            <p>
              1、琴房时长为虚拟商品，一经购买不予退费； <br />
              2、琴房时长消耗以时长扣减逻辑为准。
            </p>
          ) : (
            <p>
              1、您支付的课程费用将由平台收取； <br />
              2、陪练课、直播课课程结束后，平台将单课时费用向老师结算；
              <br />
              3、除直播课未达到开课人数外，其他服务一经购买不予退费。
            </p>
          )}
        </div> */}

            <div class={styles.paymentInfo}>
              {this.orderPrice > 0 && (
                <div class={styles.protocol}>
                  <ColProtocol
                    v-model={this.agreeStatus}
                    showHeader
                    style={{ paddingLeft: 0, paddingRight: 0 }}
                  />
                </div>
              )}

              <div class={styles.btnGroup}>
                <div class={styles.priceSection}>
                  支付金额：
                  <div class={styles.price}>
                    <span class={styles.priceUnit}>￥</span>
                    <span class={styles.priceNum}>
                      {moneyFormat(this.orderPrice)}
                    </span>
                  </div>
                </div>
                <Button
                  type="primary"
                  round
                  class={styles.btn}
                  onClick={this.onSubmit}
                >
                  立即支付
                </Button>
              </div>
            </div>
          </>
        )}
        <ColPopup v-model={this.popupShow}>
          <UserAuth onSuccess={this.onAuthSuccess} />
        </ColPopup>

        <Popup
          show={this.paymentStatus}
          closeOnClickOverlay={false}
          position="bottom"
          round
          closeOnPopstate
          safeAreaInsetBottom
          style={{ minHeight: '30%' }}
        >
          <Payment
            v-model={this.paymentStatus}
            orderInfo={orderStatus.orderObject}
            onBackOut={this.onBackOut}
          />
        </Popup>
      </div>
    )
  }
})
