<script setup>
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { getProductDetail, addOrder, createOrder } from '@/api/mall'
  import { reactive, ref } from 'vue'
  import { formatRMB } from '@/utils'
  import { getUserAddress } from '@/api'
  import { getUserPayPwd } from '@/api/my-index'
  import { navigateTo, navigateBack, redirectTo } from '@/utils/router'
  import { useUI } from '@/utils/use-ui'
  import { useUserStore } from '@/stores/user'

  const { showToast, showDialog } = useUI()
  const { refreshUserInfo } = useUserStore()

  const viewData = ref({})

  /** 分享二维码进入 拼团ID */
  const groupId = ref('')
  /** 单价 */
  const priceData = ref(0)
  const formData = reactive({
    /** 数量 */
    num: 1,
    /** 规格 */
    spec: 0,
    /** 默认支付方式 */
    payWay: 1,
    /** 合计 */
    total: 0,
    /** 默认地址 */
    address: '',
    /** 可选数量 */
    maxNum: 1,
    /** 是否发起拼团 */
    startGroup: true
  })
  /** 顶部地址信息 */
  const topRessData = reactive({
    name: '',
    houseNum: '',
    id: '',
    phone: '',
    state: false,
    loading: true
  })
  /** 地址选项弹出窗 */
  const isPopup = ref(null)
  /** 地址列表 */
  const ressDataList = ref([])
  const tixian = ref(null)
  const originalPrice = ref(0)

  /** 获取用户地址 */
  const userRess = async () => {
    topRessData.loading = true
    const res = await getUserAddress({ pageNum: 1, pageSize: 99 }, false)
    const data = res.rows.find(v => v.defaultAddress == 1)
    topRessData.state = !data?.id
    topRessData.name = data?.name || ''
    topRessData.houseNum = data?.houseNum || ''
    topRessData.id = data?.id || ''
    topRessData.phone = data?.phone || ''
    topRessData.loading = false
    ressDataList.value = res.rows
  }

  /** 选中地址 */
  const onAddress = data => {
    topRessData.state = !data?.id
    topRessData.name = data?.name || ''
    topRessData.houseNum = data?.houseNum || ''
    topRessData.id = data?.id || ''
    topRessData.phone = data?.phone || ''
    isPopup.value.close()
  }

  /** 点击顶部地址选项 */
  const onRess = () => {
    if (topRessData.name) {
      isPopup.value.open()
    } else {
      navigateTo('/pages/address/index')
    }
  }

  const getData = async productId => {
    const res = await getProductDetail(productId)
    viewData.value = res.data

    const {
      id,
      price,
      stockQuantity,
      originalPrice: nub
    } = res.data.skuList[0]
    originalPrice.value = nub
    formData.maxNum = stockQuantity
    formData.spec = id
    priceData.value = price
    formData.total = price
  }

  /** 数量切换 */
  const onChange = i => {
    formData.total = priceData.value * i
  }

  /** 规格选择 */
  const onSpecChange = item => {
    formData.spec = item.id
    formData.num = 1
    formData.total = item.price
    priceData.value = item.price
    formData.maxNum = item.stockQuantity
    originalPrice.value = item.originalPrice
  }

  // 提交订单
  const onConfirm = async () => {
    if (!topRessData.id) {
      showToast(`请选择地址`)
      return
    }
    const res = await getUserPayPwd()
    if (res?.data) {
      tixian.value.open()
    } else {
      const show = await showDialog('提示', '请先设置支付密码')
      if (show) {
        navigateTo('/pages/my-index/wallet/edit-password', { type: 0 })
      }
    }
  }

  const submit = async e => {
    const data = {
      groupId: groupId.value,
      payPassword: e.join(''),
      addressId: topRessData.id,
      productId: viewData.value.id,
      quantity: formData.num,
      skuId: formData.spec
    }
    tixian.value.close()
    if (formData.startGroup) {
      const res = await addOrder(data)
      await refreshUserInfo()
      await showToast('订单提交成功', 'success')
      navigateTo('/pages/shop-together/detail', { id: res.data.groupId })
    } else {
      const res = await createOrder(data)
      await refreshUserInfo()
      await showToast('订单提交成功', 'success')
      navigateBack()
    }
  }

  onShow(() => {
    userRess()
  })

  onLoad(async e => {
    groupId.value = e?.groupId || ''
    await getData(e.productId)
  })
</script>

<template>
  <view class="mall-confirm-order">
    <uu-pwdModal ref="tixian" @success="submit"></uu-pwdModal>

    <!-- 地址 -->
    <view class="address-box" @click="onRess">
      <text v-if="topRessData.state" class="wu-adres">
        暂无收货/默认地址(点击添加)
      </text>
      <view v-else class="left-name">
        <text class="adres">{{ topRessData.houseNum }}</text>
        <view class="bottom-name">
          <text>{{ topRessData.name }}</text>
          <text>{{ topRessData.phone }}</text>
        </view>
      </view>
      <image
        src="/static/images/public/right-arrow.png"
        mode="heightFix"
        class="right-box"
      ></image>
    </view>

    <!-- 商品展示 -->
    <view class="public-product_item">
      <image
        :src="viewData.mainImage"
        mode="scaleToFill"
        class="left-img"
      ></image>
      <view class="right-content">
        <text class="product-name">
          {{ viewData.productName }}
        </text>
        <view class="line-box">
          <view class="rmb-box">
            <text>¥{{ originalPrice }}</text>
            <text>¥{{ priceData }}</text>
          </view>
          <!-- 添加数量 -->
          <view class="add-num">
            <uni-number-box
              v-model="formData.num"
              :min="1"
              :max="formData.maxNum"
              @change="onChange"
            ></uni-number-box>
          </view>
        </view>
      </view>
    </view>

    <!-- 规格 -->
    <view class="spec-box">
      <text class="title">规格</text>
      <view class="spec-item">
        <text
          v-for="(item, index) in viewData.skuList"
          :key="index"
          :class="{
            'on-text': formData.spec === item.id,
            disabled: item.stockQuantity <= 0
          }"
          @click="item.stockQuantity > 0 && onSpecChange(item)"
        >
          {{ item.specText }}*{{ item.stockQuantity }}
        </text>
      </view>
    </view>

    <!-- 合计 -->
    <view class="total-box">
      <text class="name">合计：</text>
      <view class="num">
        <text>¥</text>
        <text>{{ formatRMB(formData.total) }}</text>
      </view>
    </view>

    <!-- 付款方式 -->
    <view class="pay-way">
      <view class="pay-way-item" @click="formData.payWay = 1">
        <view class="icon">
          <image
            src="/static/images/public/integral.png"
            mode="aspectFit"
            class="left-icon"
          ></image>
          <text>积分</text>
        </view>

        <view class="check">
          <image
            v-show="formData.payWay == 1"
            src="/static/images/public/check-to-confirm.png"
            mode="aspectFit"
            class="check-icon"
          ></image>
        </view>
      </view>

      <view
        class="pay-way-item"
        @click="formData.startGroup = !formData.startGroup"
      >
        <view class="icon">
          <image
            src="/static/images/public/pingtuan.png"
            mode="aspectFit"
            class="left-icon"
          ></image>
          <text>发起拼团</text>
        </view>

        <view class="check">
          <image
            v-show="formData.startGroup"
            src="/static/images/public/check-to-confirm.png"
            mode="aspectFit"
            class="check-icon"
          ></image>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <bottom-view>
      <cb-button @click="onConfirm">确认支付</cb-button>
    </bottom-view>

    <!-- 地址选项弹出窗 -->
    <uni-popup
      ref="isPopup"
      type="bottom"
      borderRadius="16rpx 16rpx 0 0"
      backgroundColor="#ffffff"
    >
      <view class="popup-box">
        <view class="top-name">
          <text class="title">地址选项</text>
          <uni-icons
            type="closeempty"
            size="44rpx"
            @click="isPopup.close()"
          ></uni-icons>
        </view>
        <!-- 选项卡片 -->
        <view class="card-list">
          <view
            v-for="(item, index) in ressDataList"
            :key="index"
            class="card-box"
            @click="onAddress(item)"
          >
            <view class="name-box">
              <text v-if="item.defaultAddress == 1" class="mode">
                默认
              </text>
              <text class="name">{{ item.houseNum }}</text>
            </view>
            <view class="right-box">
              <text class="p">{{ item.name }}</text>
              <uni-icons type="right" size="36rpx"></uni-icons>
            </view>
          </view>
        </view>
        <!-- 底部添加按钮 -->
        <view class="btn" @click="navigateTo('/pages/address/index')">
          添加新地址
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  page {
    background: #f9f9f9;
  }
  @import '@/styles/mall.scss';
  @import './styles/confirm-order.scss';
</style>
