<template>
  <div class="bind-goods-container">
    <div class="header">
      <van-nav-bar title="选择商品" left-text="取消" @click-left="onCancel" />
    </div>
    <div class="search-container">
      <div v-if="currentGoodsName" class="current-goods-info">
        <div class="goods-name">当前绑定: {{ currentGoodsName }}</div>
        <div class="stock-controls">
          <van-field 
            v-model="newStock" 
            type="number" 
            label="库存" 
            placeholder="输入库存数量"
            :min="0"
          />
          <van-button size="small" type="primary" @click="handleUpdateStock">修改库存</van-button>
          <van-button size="small" type="danger" @click="handleUnbind">解绑</van-button>
        </div>
      </div>
      <van-search v-model="searchQuery" placeholder="搜索商品名称" shape="round" />
    </div>
    <div class="goods-list" ref="scrollContainer">
      <van-cell v-for="goods in filteredGoods" :key="goods.goodsId" class="goods-item">
        <template #icon>
          <van-image 
            :src="goods.coverImg || `${publicPath}img/product-image.svg`"
            width="80" 
            height="80"
            fit="cover"
            radius="4"
            class="goods-image"
            :style="{ filter: goods.stock === 0 ? 'grayscale(100%)' : 'none' }"
          >
          </van-image>
        </template>
        <div class="goods-info">
          <div class="name-price-container">
            <div class="goods-name van-ellipsis">{{ goods.goodsName }}</div>
            <div class="goods-price">¥{{ (goods.price || 0).toFixed(2) }}</div>
          </div>
          <div class="stock-info">
            <span>总库存: {{ goods.stock || 0 }}</span>
            <span>已分配: {{ goods.totalStock || 0 }}</span>
            <span>剩余: {{ (goods.stock || 0) - (goods.totalStock || 0) }}</span>
          </div>
          <div class="action-row">
            <van-stepper
              v-model="allocatedStocks[goods.goodsId]"
              :min="1"
              :max="(goods.stock || 0) - (goods.totalStock || 0)"
              :disabled="goods.stock === 0 || loading"
              size="small"
              class="stock-stepper"
            />
            <van-button 
              size="small" 
              type="primary" 
              class="bind-btn"
              :disabled="(goods.stock || 0) - (goods.totalStock || 0) <= 0 || loading || !allocatedStocks[goods.goodsId]"
              :loading="loading && currentBindGoodsId === goods.goodsId"
              @click="handleBindGoods(goods)"
            >
              绑定
            </van-button>
          </div>
        </div>
      </van-cell>
      <div v-if="goodsList.length === 0 && !loading" class="empty-state">
        <van-empty description="暂无商品数据" />
      </div>
      <div v-if="loading" class="loading-state">
        <van-loading type="spinner" color="#e95d5d" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, defineProps, defineEmits } from 'vue';
import { getShopGoodsApi, getShopGoodsListApi } from '@/common/apis/shop';
import { ShopGoodsEntity, SearchGoodsDO } from '@/common/apis/shop/type';
import { publicPath } from '@/common/utils/path';
import { useWxStore } from '@/pinia/stores/wx';
import { showToast } from 'vant';
import { configureGoodsCellsStock, changeGoodsCellsStock, clearGoodsCells } from '@/common/apis/cabinet';

const props = defineProps<{
  shopId: number;
  lockerId: number;
  visible: boolean;
  currentStock?: number;
  currentGoodsName?: string;
  mode?: number;
}>();

const emits = defineEmits<{
  (e: 'cancel'): void;
  (e: 'success', goods: ShopGoodsEntity): void;
  (e: 'unbind'): void;
  (e: 'update:currentStock', stock: number): void;
}>();

const wxStore = useWxStore();
const searchQuery = ref('');
const newStock = ref<number>(props.currentStock || 0);
const goodsList = ref<SearchGoodsDO[]>([]);
const loading = ref(false);
const currentBindGoodsId = ref<number | null>(null);
const scrollContainer = ref<HTMLElement>();
const allocatedStocks = ref<Record<number, number>>({});

// 过滤商品列表
const filteredGoods = computed(() => {
  if (!searchQuery.value) return goodsList.value;
  return goodsList.value.filter(goods => 
    goods.goodsName.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
  /* return goodsList.value.filter(goods => {
    const matchesSearch = !searchQuery.value || goods.goodsName.toLowerCase().includes(searchQuery.value.toLowerCase());
    const remainingStock = (goods.stock || 0) - (goods.totalStock || 0);
    return matchesSearch && remainingStock > 0;
  }); */
});

// 获取商品列表
const loadGoodsList = async () => {
  if (!props.shopId) return;
  loading.value = true;
  try {
    const belongType = props.mode === 4 ? 1 : 0;
    const response = await getShopGoodsListApi(wxStore.corpid, belongType); // 根据mode动态设置belongType参数
    if (response?.code === 0 && response.data) {
      goodsList.value = response.data;
      // 初始化分配库存
      goodsList.value.forEach(goods => {
        allocatedStocks.value[goods.goodsId] = 1;
      });
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    showToast('获取商品列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 绑定商品
const handleBindGoods = async (goods: SearchGoodsDO) => {
  const remaining = (goods.stock || 0) - (goods.totalStock || 0);
  if (goods.stock === 0 || remaining <= 0) {
    showToast('商品剩余库存不足，无法绑定');
    return;
  }
  if (allocatedStocks.value[goods.goodsId] > remaining) {
    showToast(`入库数量不能超过剩余数量${remaining}`);
    return;
  }

  currentBindGoodsId.value = goods.goodsId;
  try {
    await configureGoodsCellsStock(props.lockerId, goods.goodsId, allocatedStocks.value[goods.goodsId]);
    emits('success', goods);
    showToast('商品绑定成功');
  } catch (error) {
    console.error('绑定商品失败:', error);
    showToast('绑定商品失败，请重试');
  } finally {
    currentBindGoodsId.value = null;
  }
};

const handleUpdateStock = async () => {
  if (newStock.value < 0) {
    showToast('库存不能为负数');
    return;
  }
  try {
    await changeGoodsCellsStock(props.lockerId, newStock.value);
    showToast('库存修改成功');
    emits('update:currentStock', newStock.value);
  } catch (error) {
    console.error('修改库存失败:', error);
    showToast('修改库存失败，请重试');
  }
};

const handleUnbind = async () => {
  try {
    await clearGoodsCells(props.lockerId);
    showToast('商品解绑成功');
    emits('unbind');
    emits('cancel');
  } catch (error) {
    console.error('解绑商品失败:', error);
    showToast('解绑商品失败，请重试');
  }
};

// 取消绑定
const onCancel = () => {
  emits('cancel');
};

// 监听visible变化，当弹窗显示时加载商品列表
watch(() => props.visible, (newVal) => {
  if (newVal) {
    newStock.value = props.currentStock || 0;
    loadGoodsList();
  }
}, { immediate: true });

onMounted(() => {
  // 初始加载商品列表
  if (props.visible) {
    loadGoodsList();
  }
});
</script>

<style scoped lang="scss">
.bind-goods-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  border-bottom: 1px solid #eee;
}

.search-container {
  padding: 10px;
  background-color: #f7f8fa;
}

.current-goods-info {
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.goods-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.stock-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stock-controls .van-field {
  flex: 1;
}

.stock-controls .van-button {
  white-space: nowrap;
}

.goods-list {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 10px;
}

.goods-item {
  margin-bottom: 10px;
  padding: 10px 12px;
  border-bottom: 1px solid #f5f5f5;
}

.goods-image {
  margin-right: 12px;
}

.goods-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 90px; // 调整高度以适应新布局
}

.name-price-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

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

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

.action-row {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.stock-stepper {
  margin-right: 10px;
  width: 120px;
}

.bind-btn {
  background-color: #e95d5d;
  border: none;
}

.stock-info {
  font-size: 12px;
  color: #666;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 4px;
}

.stock-info span {
  flex: 1;
  text-align: center;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.loading-state {
  padding: 40px 0;
  text-align: center;
}
</style>