import {
  computed,
  ref,
  defineComponent,
  onMounted,
  reactive,
  watch,
  onBeforeMount
} 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 { 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 UseCoupons from '@/views/order-detail/use-coupons'
import ColHeader from '@/components/col-header'
export default defineComponent({
  name: 'cartConfirmAgin',
  setup() {
    // console.log(cartConfirm)
    const list = cartConfirm.orderInfo?.orderItemList || []
    const calcAmount = {
      totalAmount: cartConfirm.orderInfo?.totalAmount || 0,
      payAmount: cartConfirm.orderInfo?.payAmount || 0,
      freightAmount: cartConfirm.orderInfo?.freightAmount || 0,
      couponAmount: cartConfirm.orderInfo?.couponAmount
    }
    const payType = ref(0) // 0->未支付；1->支付宝；2->微信
    const address: addressType = {
      city: cartConfirm.orderInfo?.receiverCity,
      detailAddress: cartConfirm.orderInfo?.receiverDetailAddress,
      name: cartConfirm.orderInfo?.receiverName,
      phoneNumber: cartConfirm.orderInfo?.receiverPhone,
      postCode: cartConfirm.orderInfo?.receiverPostCode,
      province: cartConfirm.orderInfo?.receiverProvince,
      region: cartConfirm.orderInfo?.receiverRegion
    }
    const agreeStatus = ref(false)
    const paymentPopup = ref(false)
    const authPopup = ref(false)
    const orderInfo = ref<any>()
    //修复实名认证头部问题
    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 (!agreeStatus.value) {
        Toast('请先阅读并同意《产品及服务协议》')
        return
      }
      // const users = state.user.data
      // 判断是否需要实名认证
      // if (!users?.student.realName || !users?.student.idCardNo) {
      //   authPopup.value = true
      //   return
      // }
      // 判断是否有订单号
      createOrder()
    }
    const router = useRouter()

    const createOrder = async () => {
      console.log(cartConfirm)
      const body = {
        orderNo: cartConfirm.orderInfo.orderSn
      }
      try {
        const { code, data } = await request.post(
          '/api-mall-portal/order/generateOrder',
          { data: body }
        )
        if (code === 200) {
          paymentPopup.value = true
          orderInfo.value = data
        }
      } catch (error) {}
    }
    return () => (
      <>
        <ColHeader />
        {list.length ? (
          <div class={styles.cartConfirm}>
            <div class={styles.cartConfirmBox}>
              <Address item={address as any} isLink={false} />
            </div>
            <div
              style={{ marginTop: '20px' }}
              class={[styles.cartBox, styles.cartConfirmBox]}
            >
              <div class={styles.shopBox}>
                {list.map((item: any) => (
                  <div
                    class={[styles.cartItem]}
                    style={{ marginBottom: '10px' }}
                  >
                    <Card
                      price={moneyFormat(item.productPrice)}
                      desc={formateAttr(item.productAttr)}
                      title={item.productName}
                      thumb={item.productPic}
                      num={item.productQuantity}
                    ></Card>
                  </div>
                ))}
              </div>
              <CellGroup border={true}>
                <Cell
                  border={false}
                  title="优惠券"
                  v-slots={{
                    value: () => (
                      <span
                        style={{
                          fontSize: '0.42667rem',
                          color: '#ff3535',
                          fontWeight: 'bold'
                        }}
                      >
                        {'-¥ ' + calcAmount.couponAmount}
                      </span>
                    )
                  }}
                ></Cell>
                <Cell
                  border={false}
                  title="总额"
                  value={'¥ ' + calcAmount.totalAmount}
                ></Cell>
                {/* <Cell
                  border={false}
                  title="运费"
                  value={calcAmount.freightAmount}
                ></Cell>
                 */}
                {/* <Cell border={false} title="优惠卷" value="暂无可用优惠卷"></Cell>
            <Cell border={false} title="乐乐币抵扣" value={"-¥" + calcAmount.promotionAmount}></Cell> */}
              </CellGroup>
            </div>

            <div class={styles.payProtocol}>
              <ColProtocol v-model={agreeStatus.value}></ColProtocol>
              <SubmitBar
                buttonText={`结算(${list.length})`}
                buttonColor="var(--van-primary)"
                disabled={list.length === 0}
                onSubmit={() => onSubmit()}
              >
                <div class={styles.confirmBottom}>
                  合计{' '}
                  <span class={styles['price-des']}>
                    ¥{moneyFormat(calcAmount.payAmount)}
                  </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.value}
                paymentType="goodsPay"
                onBackOut={() => (paymentPopup.value = false)}
              />
            </Popup>
          </div>
        ) : (
          <ColResult
            buttonText="去购物车"
            onClick={() => {
              router.push({ path: '/cart' })
            }}
          ></ColResult>
        )}
      </>
    )
  }
})
