import OSticky from '@/components/o-sticky'
import {
  Button,
  Cell,
  CellGroup,
  Checkbox,
  CheckboxGroup,
  Icon,
  Image,
  showConfirmDialog,
  showToast,
  Tag
} from 'vant'
import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import styles from '../index.module.less'
import radioCheck from '@/common/images/icon-radio-check.png'
import radioDefault from '@/common/images/icon-radio-default.png'
import { useRoute, useRouter } from 'vue-router'
import request from '../../request-music'
import { moneyFormat } from '@/helpers/utils'
import { CountUp } from 'countup.js'

export default defineComponent({
  name: 'payment',
  emits: ['next'],
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      check: [] as any, // 选中的数据
      checkboxRefs: [] as any,
      details: [] as any, //
      goodsInfo: {} as any, // 商品
      textBookInfo: {} as any, // 教材
      repaireInfo: {} as any, // 乐器保养
      vipInfo: {} as any, // 团练宝
      paymentOrderDetails: [] as any, // 购买状态
      orderInfo: {
        needPrice: 0,
        originalPrice: 0
      }
    })

    // 查询未支付订单
    const paymentOrderUnpaid = async () => {
      try {
        const { data } = await request.get('/api-student/userPaymentOrder/unpaid')
        // 判断是否有待支付订单
        if (data.id) {
          showConfirmDialog({
            message: '您有待支付的订单,是否继续支付',
            cancelButtonText: '取消订单',
            confirmButtonText: '继续支付'
          })
            .then(() => {
              const paymentConfig = data.paymentConfig
              router.push({
                path: '/orderDetail',
                query: {
                  config: JSON.stringify(paymentConfig.paymentConfig),
                  orderNo: paymentConfig.orderNo
                }
              })
            })
            .catch(async () => {
              try {
                await request.post('/api-student/userPaymentOrder/cancelPayment/' + data.orderNo)
              } catch {
                //
              }
            })
        }
      } catch {
        //
      }
    }

    // 获取商品信息
    const registerGoods = async () => {
      try {
        const { data } = await request.get(
          '/api-student/orchestraRegister/registerGoods/' + route.query.id
        )

        // 获取已经购买商品信息
        const paymentOrderDetails = data.paymentOrderDetails || []
        paymentOrderDetails.forEach((item: any) => {
          state.paymentOrderDetails.push(item.goodsType)
        })

        // 初始化数据商品数据
        const details = data.details || []
        details.forEach((item: any) => {
          if (item.goodsType === 'INSTRUMENTS') {
            const img = item.goodsUrl ? item.goodsUrl.split(',')[0] : ''
            state.goodsInfo = { ...item, goodsUrl: img }
          } else if (item.goodsType === 'TEXTBOOK') {
            const img = item.goodsUrl ? item.goodsUrl.split(',')[0] : ''
            state.textBookInfo = { ...item, goodsUrl: img }
          } else if (item.goodsType === 'REPAIR') {
            state.repaireInfo = { ...item }
          } else if (item.goodsType === 'VIP') {
            state.vipInfo = { ...item }
          }
          state.details = details

          // 默认选中所有的
          if (!state.paymentOrderDetails.includes(item.goodsType)) {
            state.check.push(item.goodsId)
          }
        })

        calcPrice()
      } catch {
        //
      }
    }

    const onSelect = (type: string) => {
      console.log(type, 'type')
      console.log(state.goodsInfo, 'goodsInfo')

      state.checkboxRefs[type].toggle()

      calcPrice()
    }

    // 初始化金额

    const calcPrice = () => {
      const details = state.details
      const tempPrice = {
        needPrice: 0, //需要支付金额
        originalPrice: 0 // 原价
      }
      details.forEach((item: any) => {
        // 是否选中
        if (
          state.check.includes(item.goodsId) &&
          !state.paymentOrderDetails.includes(item.goodsType)
        ) {
          tempPrice.needPrice += parseFloat(item.currentPrice)
          tempPrice.originalPrice += parseFloat(item.originalPrice)
        }
      })

      state.orderInfo = tempPrice

      initNumCountUp()
    }
    const countUpRef = reactive({
      needPrice: null as any,
      originalPrice: null as any
    })
    const initNumCountUp = () => {
      nextTick(() => {
        // 在读学生
        if (countUpRef.needPrice) {
          countUpRef.needPrice.update(state.orderInfo.needPrice)
        } else {
          countUpRef.needPrice = new CountUp('needPrice', state.orderInfo.needPrice, {
            decimalPlaces: 2
          })
          if (!countUpRef.needPrice.error) {
            countUpRef.needPrice.start()
          } else {
            console.error(countUpRef.needPrice.error)
          }
        }
        if (countUpRef.originalPrice) {
          countUpRef.originalPrice.update(state.orderInfo.originalPrice)
        } else {
          countUpRef.originalPrice = new CountUp('originalPrice', state.orderInfo.originalPrice, {
            decimalPlaces: 2
          })
          if (!countUpRef.originalPrice.error) {
            countUpRef.originalPrice.start()
          } else {
            console.error(countUpRef.originalPrice.error)
          }
        }
      })
    }

    // 购买
    const onSubmit = async () => {
      try {
        // 判断订单号
        if (state.check.length <= 0) {
          showToast('请选择您要购买的商品')
          return
        }
        // 重新计算金额
        calcPrice()
        const params: any = [] // 支付参数
        const details = state.details
        details.forEach((item: any) => {
          // 是否选中
          if (
            state.check.includes(item.goodsId) &&
            !state.paymentOrderDetails.includes(item.goodsType)
          ) {
            params.push({
              goodsId: item.goodsId,
              goodsNum: 1,
              goodsType: item.goodsType,
              paymentCashAmount: item.currentPrice, // 现金支付金额
              paymentCouponAmount: 0 // 优惠券金额
            })
          }
        })
        console.log({
          bizId: route.query.id, // 乐团编号
          orderType: 'ORCHESTRA',
          paymentCashAmount: state.orderInfo.needPrice || 0,
          paymentCouponAmount: 0,
          goodsInfos: params
        })
        // 创建订单
        const { data } = await request.post('/api-student/userPaymentOrder/executeOrder', {
          data: {
            bizId: route.query.id, // 乐团编号
            orderType: 'ORCHESTRA',
            paymentCashAmount: state.orderInfo.needPrice || 0,
            paymentCouponAmount: 0,
            goodsInfos: params,
            orderName: '订单详情',
            orderDesc: '订单详情'
          }
        })

        console.log(data)
        router.push({
          path: '/orderDetail',
          query: {
            config: JSON.stringify(data.paymentConfig),
            orderNo: data.orderNo
          }
        })
      } catch (e: any) {
        //
        console.log(e)
      }
      // router.push('/orderDetail')
    }

    onMounted(() => {
      // 查询未支付订单
      paymentOrderUnpaid()
      registerGoods()
    })
    return () => (
      <>
        <div class={styles.applyTitle}>报名须知</div>
        <div class={[styles.paymentTips, styles.mlr13]}>
          <p>1、您注册时所选择的乐团声部，即为乐团录取最终确认的声部，请您务必仔细填写；</p>
          <p>
            2、所有参与乐团的学生免费赠送选报声部教材，教材随乐器一同发放，若您自备乐器，则需承担教材运费。
          </p>
        </div>

        <CheckboxGroup
          v-model={state.check}
          style={{ paddingBottom: '20px' }}
          onChange={() => {
            calcPrice()
          }}
        >
          {/* 判断是否已经购买乐器 */}
          {!state.paymentOrderDetails.includes('INSTRUMENTS') && (
            <>
              <div class={styles.applyTitle}>乐器</div>
              <CellGroup
                inset
                class={[styles.mlr13, styles.sectionCell]}
                onClick={() => onSelect(state.goodsInfo.goodsId)}
              >
                <Cell border={false}>
                  {{
                    icon: () => (
                      <Checkbox
                        name={state.goodsInfo.goodsId}
                        class={styles.checkbox}
                        ref={(el: any) => (state.checkboxRefs[state.goodsInfo.goodsId] = el)}
                        onClick={(e: Event) => {
                          e.stopPropagation()
                        }}
                        v-slots={{
                          icon: (props: any) => (
                            <Icon
                              class={styles.iconChecked}
                              name={props.checked ? radioCheck : radioDefault}
                            />
                          )
                        }}
                      />
                    ),
                    title: () => (
                      <div class={styles.section}>
                        <Image class={styles.img} src={state.goodsInfo.goodsUrl} />
                        <div class={styles.sectionContent}>
                          <h2>{state.goodsInfo.goodsName}</h2>
                          <Tag type="primary">{state.goodsInfo.brandName}</Tag>
                          <p class={styles.model}>{state.goodsInfo.desciption}</p>
                        </div>
                      </div>
                    )
                  }}
                </Cell>
                <Cell>
                  {{
                    title: () => (
                      <div class={styles.extra}>
                        <div class={styles.sectionPrice}>
                          <p class={styles.price}>
                            新团特惠：<span>¥{moneyFormat(state.goodsInfo.currentPrice)}</span>
                          </p>
                          <p class={styles.originPrice}>
                            原价：<del>¥{moneyFormat(state.goodsInfo.originalPrice)}</del>
                          </p>
                        </div>
                        <div class={styles.sectionTips}>
                          赠价值{state.repaireInfo.originalPrice}元乐器维保服务一年
                        </div>
                      </div>
                    )
                  }}
                </Cell>
              </CellGroup>
            </>
          )}

          {/* 判断是否已经购买教材 */}
          {!state.paymentOrderDetails.includes('TEXTBOOK') && (
            <>
              <div class={styles.applyTitle}>教材</div>
              <CellGroup
                inset
                class={[styles.mlr13, styles.sectionCell]}
                onClick={() => {
                  return
                  // onSelect(state.textBookInfo.goodsId)
                }}
              >
                <Cell border={false}>
                  {{
                    icon: () => (
                      <Checkbox
                        name={state.textBookInfo.goodsId}
                        disabled
                        class={styles.checkbox}
                        ref={(el: any) => (state.checkboxRefs[state.textBookInfo.goodsId] = el)}
                        onClick={(e: Event) => {
                          e.stopPropagation()
                        }}
                        v-slots={{
                          icon: (props: any) => (
                            <Icon
                              class={styles.iconChecked}
                              name={props.checked ? radioCheck : radioDefault}
                            />
                          )
                        }}
                      />
                    ),
                    title: () => (
                      <div class={styles.section}>
                        <Image class={styles.img} src={state.textBookInfo.goodsUrl} />
                        <div class={styles.sectionContent}>
                          <h2>{state.textBookInfo.goodsName}</h2>
                          <Tag type="primary">{state.textBookInfo.brandName}</Tag>
                          <p class={styles.model}>{state.textBookInfo.description}</p>
                        </div>
                      </div>
                    )
                  }}
                </Cell>
                <Cell>
                  {{
                    title: () => (
                      <div class={styles.extra}>
                        <div class={styles.sectionPrice}>
                          <p class={styles.price}>
                            新团特惠：
                            <span class={styles.free}>
                              {state.textBookInfo.currentPrice > 0
                                ? moneyFormat(state.textBookInfo.currentPrice)
                                : '免费赠送'}
                            </span>
                          </p>
                          <p class={styles.originPrice}>
                            原价：<del>¥{moneyFormat(state.textBookInfo.originalPrice)}</del>
                          </p>
                        </div>
                      </div>
                    )
                  }}
                </Cell>
              </CellGroup>
            </>
          )}

          {!state.paymentOrderDetails.includes('VIP') && (
            <>
              <div class={styles.applyTitle}>乐团学习系统</div>
              <CellGroup
                inset
                class={[styles.mlr13, styles.sectionCell]}
                onClick={() => onSelect(state.vipInfo.goodsId)}
              >
                <Cell border={false}>
                  {{
                    icon: () => (
                      <Checkbox
                        name={state.vipInfo.goodsId}
                        class={styles.checkbox}
                        ref={(el: any) => (state.checkboxRefs[state.vipInfo.goodsId] = el)}
                        onClick={(e: Event) => {
                          e.stopPropagation()
                        }}
                        v-slots={{
                          icon: (props: any) => (
                            <Icon
                              class={styles.iconChecked}
                              name={props.checked ? radioCheck : radioDefault}
                            />
                          )
                        }}
                      />
                    ),
                    title: () => (
                      <div class={styles.section}>
                        <Image class={styles.img} src={state.vipInfo.goodsUrl} />
                        <div class={styles.sectionContent}>
                          <h2>{state.vipInfo.goodsName}</h2>
                          <Tag type="primary">6个月</Tag>
                          <p class={styles.model}>{state.vipInfo.description}</p>
                        </div>
                      </div>
                    )
                  }}
                </Cell>
                <Cell>
                  {{
                    title: () => (
                      <div class={styles.extra}>
                        <div class={styles.sectionPrice}>
                          <p class={styles.price}>
                            新团特惠：<span>¥{moneyFormat(state.vipInfo.currentPrice)}</span>
                          </p>
                          <p class={styles.originPrice}>
                            原价：<del>¥{moneyFormat(state.vipInfo.originalPrice)}</del>
                          </p>
                        </div>
                      </div>
                    )
                  }}
                </Cell>
              </CellGroup>
            </>
          )}
        </CheckboxGroup>

        <OSticky position="bottom" background="white">
          <div class={styles.paymentContainer}>
            <div class={styles.payemntPrice}>
              <p class={styles.needPrice}>
                支付金额：
                <span>
                  ¥<i style="font-style: normal" id="needPrice"></i>
                </span>
              </p>
              <p class={styles.allPrice}>
                总原价：
                <del>
                  ¥<i style="font-style: normal" id="originalPrice"></i>
                </del>
              </p>
            </div>
            <div class={styles.paymentBtn}>
              <Button
                color="linear-gradient(135deg, #FF8C4A 0%, #FF531C 100%)"
                round
                onClick={onSubmit}
              >
                立即购买
              </Button>
            </div>
          </div>
        </OSticky>
      </>
    )
  }
})
