import OHeader from '@/components/o-header'
import { computed, defineComponent, onMounted, reactive, ref } from 'vue'
import styles from './order-detail.module.less'
import Addres from './component/addres'
import OSticky from '@/components/o-sticky'
import { Button, Cell, CellGroup, Image, Popup, showConfirmDialog, showToast, Tag } from 'vant'
import Payment from '@/views/adapay/payment'
import { useRoute, useRouter } from 'vue-router'
import OQrcode from '@/components/o-qrcode'
import request from '@/helpers/request'
import { state as baseState } from '@/state'
import { browser, moneyFormat } from '@/helpers/utils'
import OProtocol from '@/components/o-protocol'
import OPopup from '@/components/o-popup'
import UserAuth from './component/user-auth'
import qs from 'query-string'

export default defineComponent({
  name: 'order-detail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      orderTimer: null as any,
      paymentStatus: false,
      showQrcode: false,
      qrCodeUrl: '',
      pay_channel: '',
      orderNo: route.query.orderNo,
      orderInfo: {} as any, // 订单信息
      goodsInfos: [] as any, // 订单信息列表
      config: route.query.config ? JSON.parse(route.query.config as any) : {},
      hasFreight: route.query.hf ? false : true, // 是否显示
      freight: '', // 运费
      agreeStatus: true, //是否勾选协议
      showHeader: false,
      authShow: false // 是否进行实名认证
    })

    const orderType = computed(() => {
      return state.orderInfo.orderType
    })

    const addressDetails = ref<any>({})

    const getOrderDetails = async () => {
      try {
        const { data } = await request.get('/api-student/userPaymentOrder/detail/' + state.orderNo)
        const goodsInfos = data.goodsInfos || []
        state.orderInfo = data
        let hasInstrument = false // 是否有乐器
        let hasTextbook = false // 是否购买教材
        goodsInfos.forEach((item: any) => {
          const img = item.goodsUrl ? item.goodsUrl.split(',')[0] : ''
          item.goodsUrl = img

          if (item.goodsType === 'INSTRUMENTS') {
            hasInstrument = true
          } else if (item.goodsType === 'TEXTBOOK') {
            hasTextbook = true
          }
        })
        state.goodsInfos = goodsInfos

        if (!addressDetails.value.id) {
          addressDetails.value = data.addresses || {}
        }

        // 判断运费状态
        // 如果没有购买商品，有购买教材则『到付』 其它则免运费
        console.log(hasInstrument, hasTextbook)
        if (!hasInstrument && hasTextbook) {
          state.freight = '到付'
        } else {
          state.freight = '免运费'
        }

        // 判断订单状态，如果不是待支付则返回
        // WAIT_PAY: '待支付',
        // PAYING: '支付中',
        // PAID: '已付款',
        // TIMEOUT: '订单超时',
        // FAIL: '支付失败',
        // CLOSED: '订单关闭',
        // REFUNDING: '退款中',
        // REFUNDED: '已退款'
        if (data.status !== 'WAIT_PAY' && data.status !== 'PAYING') {
          // status
          showConfirmDialog({
            message: '订单处理中，请稍等',
            showCancelButton: false
          }).then(() => {
            router.replace({
              path: '/payment-result',
              query: {
                orderNo: state.orderNo
              }
            })
          })
        }
      } catch {
        //
      }
    }

    const onConfirm = (val: any) => {
      const config: any = state.config
      state.pay_channel = val.pay_channel
      if (val.payCode === 'payResult') {
        // router.push({
        //   path: '/payResult',
        //   query: {
        //     pay_channel: val.pay_channel,
        //     wxAppId: config.wxAppId,
        //     body: config.body,
        //     price: config.price,
        //     orderNo: config.merOrderNo,
        //     userId: config.userId
        //   }
        // })

        window.location.href =
          window.location.origin +
          '/orchestra-student/#/payResult?' +
          qs.stringify({
            pay_channel: val.pay_channel,
            wxAppId: config.wxAppId,
            body: config.body,
            price: config.price,
            orderNo: config.merOrderNo,
            userId: config.userId
          })
      } else {
        state.qrCodeUrl =
          window.location.origin +
          '/orchestra-student/#/payDefine?pay_channel=' +
          val.pay_channel +
          '&wxAppId=' +
          config.wxAppId +
          '&body=' +
          config.body +
          '&price=' +
          config.price +
          '&orderNo=' +
          config.merOrderNo +
          '&userId=' +
          config.userId
        console.log(state.qrCodeUrl, 'qrCodeUrl')
        state.showQrcode = true
        state.paymentStatus = false

        setTimeout(() => {
          getPaymentOrderStatus()
        }, 300)
      }
    }

    // 轮询查询订单状态
    const getPaymentOrderStatus = async () => {
      // 循环查询订单
      // const orderNo = state.orderNo
      const orderTimer = setInterval(async () => {
        // 判断是否在当前路由，如果不是则清除定时器
        if (route.name != 'orderDetail') {
          clearInterval(orderTimer)
          return
        }
        state.orderTimer = orderTimer
        try {
          const { data } = await request.post(
            '/api-student/open/userOrder/paymentStatus/' + state.orderNo,
            {
              hideLoading: true
            }
          )
          // console.log(data)
          if (data.status !== 'WAIT_PAY' && data.status !== 'PAYING') {
            clearInterval(orderTimer)
            window.location.replace(
              window.location.origin +
                '/orchestra-student/#/payment-result?orderNo=' +
                state.orderNo
            )
          }
        } catch {
          //
          clearInterval(orderTimer)
        }
      }, 5000)
    }

    // const locationReplace = (url: any) => {
    //   // 只允许同域名
    //   console.log(history.replaceState, 'window.history.replaceState', url)
    //   if (history.replaceState) {
    //     history.replaceState(null, document.title, url)
    //     history.go(0)
    //   } else {
    //     location.replace(url)
    //   }
    // }

    const beforeSubmit = () => {
      const pt = state.pay_channel
      let payCode = 'qrCode'
      // 判断当前浏览器
      if (browser().weixin) {
        // 微信浏览器
        if (pt == 'alipay_qr' || pt == 'alipay_wap') {
          payCode = 'qrCode'
        } else if (pt == 'wx_pub') {
          payCode = 'pay'
        }
      } else if (browser().alipay) {
        // 支付宝浏览器
        if (pt == 'alipay_wap') {
          // 支付宝 H5 支付
          payCode = 'pay'
        } else {
          payCode = 'qrCode'
        }
      } else {
        payCode = 'qrCode'
      }

      onConfirm({
        payCode: payCode == 'qrCode' ? 'payDefine' : 'payResult',
        pay_channel: pt
      })
    }

    const onSubmit = async () => {
      clearInterval(state.orderTimer)

      if (orderType.value === 'VIP') {
        // onCallback()
        buyVip(onCallback)
      } else {
        buyOrchestra(onCallback)
      }
    }
    const onCallback = () => {
      const pt = state.pay_channel
      // 判断是否有支付方式
      if (pt) {
        beforeSubmit()
      } else {
        state.paymentStatus = true
      }
    }

    const buyVip = async (callback?: any) => {
      try {
        const { data } = await request.get('/api-student/userPaymentOrder/detail/' + state.orderNo)
        console.log(data)
        state.pay_channel = data.paymentChannel
        if (data.status === 'PAID') {
          showConfirmDialog({
            message: '该订单已支付成功',
            showCancelButton: false
          }).then(() => {
            router.replace({
              path: '/payment-result',
              query: {
                orderNo: state.orderNo
              }
            })
          })
        } else {
          callback && callback()
        }
      } catch {
        //
      }
    }

    const buyOrchestra = async (callback: any) => {
      // 请选择收货地址
      if (!addressDetails.value.id) {
        showToast('请选择收货地址')
        return
      }

      if (!state.agreeStatus) {
        showToast('请先阅读并同意《管乐团平台服务协议》')
        return
      }
      const users = baseState.user.data

      // 判断是否需要实名认证, 姓名，卡号
      if (!users?.account.realName || !users?.account.idCardNo) {
        state.authShow = true
        return
      }

      try {
        const { data } = await request.post('/api-student/userPaymentOrder/updateReceiveAddress', {
          data: {
            orderNo: state.orderNo,
            orderType: 'ORCHESTRA',
            receiveAddress: addressDetails.value.id
          }
        })
        console.log(data)
        state.pay_channel = data.paymentChannel
        if (data.status === 'PAID') {
          showConfirmDialog({
            message: '该订单已支付成功',
            showCancelButton: false
          }).then(() => {
            router.replace({
              path: '/payment-result',
              query: {
                orderNo: state.orderNo
              }
            })
          })
        } else {
          callback && callback()
        }
      } catch {
        //
      }
    }

    // 放弃支付时，则取消订单
    const onBackOut = async () => {
      try {
        await request.post('/api-student/userPaymentOrder/cancelPayment/' + state.orderNo)
        router.back()
      } catch {
        //
      }
    }

    // 实名认证成功
    const onAuthSuccess = () => {
      //
      state.authShow = false
      onSubmit() // 实名成功后自动支付
    }

    onMounted(() => {
      if (browser().isApp) {
        state.showHeader = true
      } else {
        state.showHeader = false
      }

      // 获取收货地址
      let details = sessionStorage.getItem('addressDetails')
      details = details ? JSON.parse(details) : {}
      addressDetails.value = details
      sessionStorage.removeItem('addressDetails')

      getOrderDetails()
    })
    return () => (
      <>
        {browser().isApp && <OHeader border={false} />}
        <div class={styles.cartConfirm}>
          {/* 只有乐团购买的时候显示收货地址 */}
          {orderType.value === 'ORCHESTRA' && (
            <div class={styles.cartConfirmBox}>
              <Addres item={addressDetails.value} />
            </div>
          )}

          <CellGroup style={{ margin: 0 }}>
            {state.goodsInfos &&
              state.goodsInfos.map((goods: any) => (
                <Cell class={styles.cellItem} center>
                  {{
                    icon: () => <Image class={styles.img} src={goods.goodsUrl} />,
                    title: () => (
                      <div class={styles.goodsContent}>
                        <h2>{goods.goodsName}</h2>
                        <Tag type="primary">{goods.brandName}</Tag>
                        <p class={styles.goodsNum}>{goods.goodsType === 'VIP' ? '6个月' : 'x 1'}</p>
                      </div>
                    ),
                    value: () => (
                      <span class={styles.cellPrice}>
                        {goods.currentPrice > 0 ? '￥' + moneyFormat(goods.currentPrice) : '赠送'}
                      </span>
                    )
                  }}
                </Cell>
              ))}
          </CellGroup>

          {orderType.value === 'ORCHESTRA' && (
            <Cell class={styles.freight} title="运费" value={state.freight}></Cell>
          )}

          <div class={styles.protocol}>
            <OProtocol
              v-model:modelValue={state.agreeStatus}
              showHeader={state.showHeader}
              style={{ paddingLeft: 0, paddingRight: 0 }}
            />
          </div>
        </div>

        <OSticky position="bottom" background="white">
          <div class={styles.paymentContainer}>
            <div class={styles.payemntPrice}>
              <p class={styles.needPrice}>
                共需支付：<span>¥{moneyFormat(state.orderInfo.currentPrice)}</span>
              </p>
            </div>
            <div class={styles.paymentBtn}>
              <Button
                color="linear-gradient(135deg, #FF8C4A 0%, #FF531C 100%)"
                round
                onClick={onSubmit}
              >
                立即购买
              </Button>
            </div>
          </div>
        </OSticky>

        <Popup
          show={state.paymentStatus}
          closeOnClickOverlay={false}
          position="bottom"
          round
          closeOnPopstate
          safeAreaInsetBottom
          style={{ minHeight: '30%' }}
        >
          <Payment
            paymentConfig={state.orderInfo}
            onClose={() => (state.paymentStatus = false)}
            onBackOut={onBackOut}
            onConfirm={(val: any) => onConfirm(val)}
          />
        </Popup>

        <Popup
          v-model:show={state.showQrcode}
          style={{ background: 'transparent', overflow: 'initial' }}
          safeAreaInsetBottom={true}
          class={styles.popupCode}
          closeable
          onClose={() => {
            // 二维码关闭时清除订单器
            clearInterval(state.orderTimer)
          }}
        >
          <div class={styles.codeContainer}>
            {/* <i class={styles.codeClose} onClick={() => (state.showQrcode = false)}></i> */}
            <div class={styles.codeImg}>
              <div class={styles.codeContent}>
                <h2 class={styles.codeTitle}>
                  {orderType.value === 'VIP' ? '开通会员' : '乐团报名'}
                </h2>
                <div class={styles.codeName}>
                  请截图下方二维码 登录{state.pay_channel === 'wx_pub' ? '微信' : '支付宝'}
                  扫码支付
                </div>

                <div class={styles.codeQr}>
                  <OQrcode text={state.qrCodeUrl} size={'400'} />
                </div>
                <div style={{ textAlign: 'center' }}>
                  <span class={styles.codeBtnText}>请在30分钟内扫码支付</span>
                </div>
                <div class={styles.codeTips}>
                  <div class={styles.tipsTitle}>使用说明：</div>
                  <div class={styles.tipsContent}>
                    1.长按二维码保存图片到相册（或截屏保存到相册）
                    <br />
                    2.打开{state.pay_channel === 'wx_pub' ? '微信' : '支付宝'}扫一扫
                    <br />
                    3.选择相册中的二维码
                    <br />
                    4.请在30分钟内扫码支付
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Popup>

        <OPopup v-model:modelValue={state.authShow}>
          <UserAuth onSuccess={onAuthSuccess} hideHeader={!browser().isApp} />
        </OPopup>
      </>
    )
  }
})
