<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getGoodsListApi, type GoodsDTO } from "@/api/shop/goods";
import { configureGoodsCellsStock } from "@/api/cabinet/cabinet-cell";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { ElMessage, ElMessageBox } from "element-plus";
import { useWxStore } from "@/store/modules/wx";

const props = defineProps({
  cellId: {
    type: Number,
    required: true
  },
  belongType: {
    type: Number,
    required: false
  }
});

const emit = defineEmits(['refresh', 'update:modelValue']);
const closeModal = () => {
  emit('update:modelValue', false);
};

const wxStore = useWxStore();

const searchFormParams = ref({
  corpid: wxStore.corpid,
  goodsName: "",
  status: null,
  belongType: props.belongType
});

const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

const loading = ref(false);
const dataList = ref<GoodsDTO[]>([]);

const getList = async () => {
  try {
    loading.value = true;
    searchFormParams.value.corpid = wxStore.corpid;
    searchFormParams.value.belongType = props.belongType;
    const { data } = await getGoodsListApi({
      ...searchFormParams.value,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

const handleConfigure = async (row: GoodsDTO) => {
  try {
    const { value } = await ElMessageBox.prompt(
      '请输入商品库存数量',
      '配置库存',
      {
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '请输入有效的正整数库存'
      }
    );

    if (!value) {
      ElMessage.warning('请输入库存数量');
      return;
    }
    if (Number(value) > row.stock - row.totalStock) {
      ElMessage.warning('分配数量不能超过剩余库存');
      return;
    }
    await configureGoodsCellsStock(props.cellId, row.goodsId!, Number(value));
    ElMessage.success('配置成功');
    emit('refresh');
    closeModal();
  } catch (error) {
    console.error('配置取消或失败', error);
  }
};

watch(
  () => props.cellId,
  () => {
    getList();
  }
);

onMounted(() => {
  getList();
})

defineExpose({ getList });
</script>

<template>
  <div class="config-modal">
    <el-form :inline="true" :model="searchFormParams" class="search-form">
      <el-form-item>
        <el-input @keydown.enter.prevent="getList" v-model="searchFormParams.goodsName" placeholder="请输入商品名称"
          clearable />
      </el-form-item>
      <!-- <el-form-item label="状态：">
        <el-select v-model="searchFormParams.status" placeholder="请选择状态" clearable>
          <el-option label="已上架" :value="1" />
          <el-option label="已下架" :value="2" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item prop="belongType">
        <el-select v-model="searchFormParams.belongType" placeholder="请选择商品所属" clearable @change="getList"
          class="!w-[180px]">
          <el-option label="智柜宝" :value="0" />
          <el-option label="固资通" :value="1" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="getList">
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" border>
      <el-table-column label="商品图片" width="120">
        <template #default="{ row }">
          <el-image :src="row.coverImg" fit="cover" class="rounded" width="60" height="60" />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="goodsName" />
      <el-table-column label="价格" prop="price" width="120" />
      <el-table-column label="库存" prop="stock" width="120" />
      <el-table-column label="已分配库存" prop="totalStock" width="120" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '已上架' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleConfigure(row)">
            配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" :total="pagination.total"
      @size-change="getList" @current-change="getList" class="pagination" />
  </div>
</template>

<style scoped lang="scss">
.config-modal {
  padding: 20px;
}

.search-form {
  margin-bottom: 8px;
}

.el-form-item {
  margin-bottom: 8px;
}

.pagination {
  margin-top: 10px;
}
</style>