<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { Order, useOrderStore } from '@/pinia/stores/order'
import { useWxStore, useWxStoreOutside } from '@/pinia/stores/wx'
import { openCabinetApi } from '@/common/apis/shop'
import { showSuccessToast, showFailToast } from 'vant'
import { ref } from 'vue'
import { useAb98UserStore } from '@/pinia/stores/ab98-user'

const router = useRouter()
const route = useRoute()
const orderStore = useOrderStore()
const orderId = ref(Number(route.query.orderId))
const currentOrder = ref<Order>()
const isButtonDisabled = ref<Record<number, boolean>>({})

const wxStore = useWxStore();
const { openid, balance, corpidLogin, userid: qyUserid, name: qyName } = storeToRefs(wxStore);
const ab98UserStore = useAb98UserStore();
const { tel, userid: ab98Userid, name } = storeToRefs(ab98UserStore);

async function handleOpenCabinet(orderId: number, orderGoodsId: number) {
  isButtonDisabled.value[orderGoodsId] = true
  try {
    const isInternal = corpidLogin.value ? 2 : ab98Userid.value ? 1 : 0;
    const result = await openCabinetApi(orderId, orderGoodsId, {
      userid: isInternal === 2 ? qyUserid.value : ab98Userid.value,
      isInternal: isInternal,
      name: isInternal === 2 ? qyName.value : name.value,
      mobile: tel.value,
      operationType: 1
    });
    if (result.code !== 0) {
      showFailToast(result.msg || '开启失败，请稍后重试')
      return
    }
    showSuccessToast('柜口已成功开启')
  } catch (error) {
    showFailToast('开启失败，请稍后重试')
  } finally {
    setTimeout((currentId) => {
      delete isButtonDisabled.value[currentId]
    }, 10000, orderGoodsId)
  }
}

function backToHome() {
  router.push('/')
}

watch(() => orderId.value, async (newVal) => {
  await orderStore.getOrders(wxStore.corpid, wxStore.openid, wxStore.qyUserId, 0)
  currentOrder.value = orderStore.orders.find(o => o.orderId === newVal)
}, { immediate: true })
</script>

<template>
  <div class="success-container">
    <van-nav-bar title="支付成功" left-arrow @click-left="backToHome" />

    <div class="content-wrapper">
      <van-cell-group class="success-info">
        <van-cell title="订单号" :value="orderId" class="orderid-cell" />
      </van-cell-group>

      <van-cell-group v-if="currentOrder" class="goods-list">
        <van-cell
          v-for="(item, index) in currentOrder.goodsList"
          :key="index"
          class="goods-item"
        >
          <template #icon>
            <van-image 
              :src="item.goodsInfo.coverImg"
              width="80"
              height="80"
              class="product-image"
            />
          </template>
          <div class="product-info">
            <div class="product-name van-ellipsis">
              {{ item.goodsInfo.goodsName }}
            </div>
            <div class="product-price">
              ¥{{ item.goodsInfo.price.toFixed(2) }}
            </div>
            <div class="action-row">
              <van-button
                type="primary"
                size="small"
                class="open-btn add-cart-btn"
                @click.stop="handleOpenCabinet(currentOrder.orderId, item.orderGoods.orderGoodsId)"
                :disabled="isButtonDisabled[item.orderGoods.orderGoodsId]"
              >
                {{ isButtonDisabled[item.orderGoods.orderGoodsId] ? '处理中...' : '打开柜口' }}
              </van-button>
            </div>
          </div>
        </van-cell>
      </van-cell-group>

      <div class="action-buttons">
        <van-button 
          type="primary" 
          block
          @click="backToHome"
          class="home-button"
        >
          返回首页
        </van-button>
        <van-button 
          type="default" 
          block
          class="detail-button"
          @click="router.push('/order/' + orderId)"
        >
          查看订单详情
        </van-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.success-container {
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.content-wrapper {
  padding-top: 46px;
  flex: 1;
  overflow-y: auto;
}

.goods-list {
  margin: 20px 0;
  padding: 0 16px;
}

.goods-item {
  margin-bottom: 10px;
  padding: 10px 0;
  position: relative;
}

.product-image {
  margin-right: 12px;
  border-radius: 4px;
  overflow: hidden;
}

.product-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 80px;
}

.product-name {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.product-price {
  font-size: 16px;
  color: #e95d5d;
  font-weight: bold;
}

.action-row {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  margin-top: auto;
}

.open-btn {
  background-color: #e95d5d;
  border-color: #e95d5d;
  border-radius: 16px;
  padding: 0 24px;
}

.action-buttons {
  position: fixed;
  bottom: 30px;
  left: 16px;
  right: 16px;
}

.home-button {
  margin-bottom: 12px;
  background-color: #e95d5d;
  border: none;
}

.detail-button {
  border: 1px solid #e95d5d;
  color: #e95d5d;
}
</style>