import {
  computed,
  ref,
  defineComponent,
  onMounted,
  reactive,
  onUnmounted,
  watch
} from 'vue'
import { Card, Cell, CellGroup, Popup, SubmitBar, Toast } from 'vant'
import { addressType, cartConfirm, formateAttr } from '../cart'
import styles from '../index.module.less'
import Address from '../components/address'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import ColProtocol from '@/components/col-protocol'
import Payment from '@/views/order-detail/payment'
import { state } from '@/state'
import ColPopup from '@/components/col-popup'
import UserAuth from '@/views/order-detail/userAuth'
import ColResult from '@/components/col-result'
import { moneyFormat } from '@/helpers/utils'
import {
  listenerMessage,
  postMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import UseCoupons, { couponEnum } from '@/views/order-detail/use-coupons'
import ColHeader from '@/components/col-header'
export default defineComponent({
  name: 'cartConfirm',
  setup() {
    const loading = ref(true)
    const route = useRoute()
    const address = ref<addressType>()
    onMounted(async () => {
      loading.value = true
      if (route.query.cartIds) {
        try {
          const { code, data } = await request.post(
            '/api-mall-portal/order/generateConfirmOrder',
            {
              params: {
                cartIds: route.query.cartIds
              }
            }
          )
          if (code === 200) {
            cartConfirm.calcAmount = data.calcAmount
            cartConfirm.cartPromotionItemList = data.cartPromotionItemList
            cartConfirm.memberReceiveAddressList = data.memberReceiveAddressList
          }
        } catch (error) {}
      }
      loading.value = false
      if (cartConfirm.memberReceiveAddressList.length) {
        const a =
          cartConfirm.memberReceiveAddressList.find(
            (n: any) => n.defaultStatus
          ) || cartConfirm.memberReceiveAddressList[0]
        if (a) address.value = a
      }
    })

    const setAddress = (result: addressType) => {
      address.value = result
    }
    onMounted(() => {
      listenerMessage('getAddress', result => {
        setAddress(result?.content || {})
      })
    })
    onUnmounted(() => {
      removeListenerMessage('getAddress', () => {})
    })

    const agreeStatus = ref(false)
    const paymentPopup = ref(false)
    const authPopup = ref(false)
    const orderInfo = reactive({
      orderNo: '',
      actualPrice: 0,
      couponId: ''
    })
    //修复实名认证头部问题
    watch(authPopup, (value, oldValue) => {
      if (authPopup.value) {
        // 设置是否显示导航栏 0 显示 1 不显示
        postMessage({ api: 'setBarStatus', content: { status: 0 } })
      } else {
        postMessage({ api: 'setBarStatus', content: { status: 1 } })
      }
    })
    // 提交
    const onSubmit = () => {
      if (!address.value?.id) {
        Toast('请选择收货地址')
        return
      }
      if (!agreeStatus.value) {
        Toast('请先阅读并同意《酷乐秀平台服务协议》')
        return
      }
      const users = state.user.data
      // 判断是否需要实名认证
      if (!users?.realName || !users?.idCardNo) {
        authPopup.value = true
        return
      }

      // 判断是否有订单号
      if (orderInfo.orderNo) {
        paymentPopup.value = true
        return
      }
      createOrder()
    }
    const router = useRouter()
    //创建订单
    const createOrder = async () => {
      const ids = cartConfirm.cartPromotionItemList.reduce(
        (arr, value: any) => {
          arr.push(value.id)
          return arr
        },
        []
      )
      const payAmount =
        cartConfirm.calcAmount.payAmount -
        cartConfirm.calcAmount.promotionAmount
      const body = {
        cartIds: ids,
        memberReceiveAddressId: address.value?.id,
        platformType: state.platformType,
        orderAmount: Number((payAmount >= 0 ? payAmount : 0).toFixed(2)),
        couponId: orderInfo.couponId
      }
      try {
        const { code, data } = await request.post(
          '/api-mall-portal/order/generateOrder',
          { data: body }
        )
        if (code === 200) {
          if (data.order.status === 1) {
            router.replace({
              path: `/shopTrade`,
              query: {
                orderNo: data?.order.orderSn,
                id: data?.order.id
              }
            })
            return
          }
          paymentPopup.value = true
          orderInfo.orderNo = data?.order.orderSn || ''
          orderInfo.actualPrice = data?.order.payAmount || 0
        }
      } catch (error) {}
    }

    //认证成功
    const onAuthSuccess = () => {
      authPopup.value = false
      onSubmit() // 实名成功后自动支付
    }
    return () => (
      <>
        <ColHeader />
        {loading.value ? null : (
          <div>
            {cartConfirm.cartPromotionItemList.length ? (
              <div class={styles.cartConfirm}>
                <div class={styles.cartConfirmBox}>
                  <Address item={address.value} setAddress={setAddress} />
                </div>
                <div
                  style={{ marginTop: '20px' }}
                  class={[styles.cartBox, styles.cartConfirmBox]}
                >
                  <div class={styles.shopBox}>
                    {cartConfirm.cartPromotionItemList.map((item: any) => (
                      <div
                        class={[styles.cartItem]}
                        style={{ marginBottom: '10px' }}
                      >
                        <Card
                          price={moneyFormat(item.price)}
                          desc={formateAttr(item.productAttr)}
                          title={item.productName}
                          thumb={item.productPic}
                          num={item.quantity}
                        ></Card>
                      </div>
                    ))}
                  </div>
                  <CellGroup border={false}>
                    {/* <Cell
                    border={false}
                    title="运费"
                    value={moneyFormat(cartConfirm.calcAmount.freightAmount)}
                  ></Cell>

                    {/* <Cell border={false} title="优惠卷" value="暂无可用优惠卷"></Cell>
              <Cell border={false} title="乐乐币抵扣" value={"-¥" + cartConfirm.calcAmount.promotionAmount}></Cell> */}
                    <UseCoupons
                      orderType="GOODS"
                      orderAmount={cartConfirm.calcAmount.totalAmount}
                      onCouponSelect={coupon => {
                        const discountPrice = coupon
                          .map(n => n.discountPrice)
                          .reduce((total, n) => {
                            return total + n
                          }, 0)
                        const couponId = coupon
                          .map(n => n.couponIssueId)
                          .join(',')
                        cartConfirm.calcAmount.promotionAmount = discountPrice
                        orderInfo.couponId = couponId
                      }}
                    />
                    {/* <Cell
                      border={false}
                      title="优惠"
                      value={
                        '-¥ ' +
                        moneyFormat(cartConfirm.calcAmount.promotionAmount)
                      }
                    ></Cell> */}

                    <Cell
                      border={false}
                      title="总额"
                      value={
                        '¥ ' + moneyFormat(cartConfirm.calcAmount.totalAmount)
                      }
                    ></Cell>
                  </CellGroup>
                </div>

                <div class={styles.payProtocol}>
                  <ColProtocol v-model={agreeStatus.value}></ColProtocol>
                  <SubmitBar
                    buttonText={`结算(${cartConfirm.cartPromotionItemList.length})`}
                    buttonColor="var(--van-primary)"
                    disabled={cartConfirm.cartPromotionItemList.length === 0}
                    onSubmit={() => onSubmit()}
                  >
                    <div class={styles.confirmBottom}>
                      合计{' '}
                      <span class={styles['price-des']}>
                        ¥
                        {moneyFormat(
                          cartConfirm.calcAmount.payAmount -
                            cartConfirm.calcAmount.promotionAmount >=
                            0
                            ? cartConfirm.calcAmount.payAmount -
                                cartConfirm.calcAmount.promotionAmount
                            : 0
                        )}
                      </span>
                    </div>
                  </SubmitBar>
                </div>

                <div style={{ height: 'var(--van-submit-bar-height)' }}></div>
                <ColPopup v-model={authPopup.value}>
                  <UserAuth onSuccess={onAuthSuccess} />
                </ColPopup>
                <Popup
                  show={paymentPopup.value}
                  closeOnClickOverlay={false}
                  position="bottom"
                  round
                  closeOnPopstate
                  safeAreaInsetBottom
                  style={{ minHeight: '30%' }}
                >
                  <Payment
                    v-model={paymentPopup.value}
                    orderInfo={orderInfo}
                    paymentType="goodsPay"
                    onBackOut={() => (paymentPopup.value = false)}
                  />
                </Popup>
              </div>
            ) : (
              <ColResult
                buttonText="去购物车"
                onClick={() => {
                  router.push({ path: '/cart' })
                }}
              ></ColResult>
            )}
          </div>
        )}
      </>
    )
  }
})
