<template>
  <el-dialog
    :model-value="modelValue"
    title="添加商品"
    width="1200px"
    @update:model-value="handleDialogChange"
    @open="handleOpen"
    @close="handleClose"
  >
    <!-- 搜索条件 -->
    <el-form :model="queryParams" :inline="true" label-width="80px">
      <el-form-item label="商品编号">
        <el-input v-model="queryParams.productNo" placeholder="请输入商品编号" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="queryParams.itemName" placeholder="请输入商品名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="商品品牌">
        <el-select v-model="queryParams.brandId" placeholder="请选择品牌" clearable style="width: 200px">
          <el-option v-for="brand in brandOptions" :key="brand.id" :label="brand.brandName" :value="brand.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类">
        <el-tree-select
          v-model="queryParams.bottomCategoryId"
          :data="categoryList"
          :props="{ value: 'id', label: 'label', children: 'children' } as any"
          value-key="id"
          placeholder="请选择商品分类"
          clearable
          check-strictly
        />
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select v-model="queryParams.productStatus" placeholder="请选择" clearable style="width: 200px">
          <el-option label="上架" value="0" />
          <el-option label="下架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品列表 -->
    <el-table :data="productList" border style="width: 100%" max-height="400px" v-loading="loading">
      <el-table-column prop="productNo" label="商品编号" width="120" />
      <el-table-column label="商品图片" width="100">
        <template #default="scope">
          <el-image v-if="scope.row.productImage" :src="scope.row.productImage" style="width: 60px; height: 60px" fit="cover" />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="商品信息" min-width="200">
        <template #default="scope">
          <div>{{ scope.row.itemName }}</div>
          <div>品牌: {{ scope.row.brandName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="税率" width="100">
        <template #default="scope"> 增值税{{ formatTaxRate(scope.row.taxRate) }}% </template>
      </el-table-column>
      <el-table-column prop="unitName" label="单位" width="80" />
      <el-table-column prop="minSellingPrice" label="最低售价" width="100" />
      <el-table-column prop="minOrderQuantity" label="起订量" width="100" />
      <el-table-column prop="memberPrice" label="含税单价" width="100" />
      <el-table-column prop="productStatus" label="商品状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.productStatus === '0'" type="success">上架</el-tag>
          <el-tag v-else type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleAddProduct(scope.row)">加入</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="prev, next"
      @current-change="handleCurrentChange"
      class="mt-4"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { listBase, brandList, categoryTree } from '@/api/product/base';
import { BaseVO, BaseQuery } from '@/api/product/base/types';
import { BrandVO } from '@/api/product/brand/types';
import { categoryTreeVO } from '@/api/product/category/types';

interface Props {
  modelValue: boolean;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'confirm', product: BaseVO): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const loading = ref(false);
const productList = ref<BaseVO[]>([]);
const brandOptions = ref<BrandVO[]>([]);
const categoryList = ref<categoryTreeVO[]>([]);
const total = ref(0);

const queryParams = ref<BaseQuery>({
  pageNum: 1,
  pageSize: 10,
  productNo: undefined,
  itemName: undefined,
  brandId: undefined,
  topCategoryId: undefined
});

// 对话框状态变化
const handleDialogChange = (val: boolean) => {
  emit('update:modelValue', val);
};

// 格式化税率
const formatTaxRate = (taxRate: number | string | undefined): string => {
  if (taxRate === undefined || taxRate === null) {
    return '0';
  }
  return Number(taxRate).toFixed(0);
};

// 对话框打开时触发
const handleOpen = () => {
  loadProductList();
};

// 对话框关闭时触发
const handleClose = () => {
  // 可以在这里重置数据
};

// 加载商品列表
const loadProductList = async () => {
  if (loading.value) return;

  loading.value = true;
  try {
    const res = await listBase(queryParams.value);
    productList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('加载商品列表失败:', error);
    productList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载品牌列表
const loadBrandList = async () => {
  try {
    const res = await brandList();
    brandOptions.value = res.data || [];
  } catch (error) {
    console.error('加载品牌列表失败:', error);
    brandOptions.value = [];
  }
};

// 加载分类树
const loadCategoryTree = async () => {
  try {
    const res = await categoryTree();
    categoryList.value = res.data || [];
  } catch (error) {
    console.error('加载分类树失败:', error);
    categoryList.value = [];
  }
};

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  loadProductList();
};

// 分页大小变化
const handleSizeChange = () => {
  queryParams.value.pageNum = 1;
  loadProductList();
};

// 页码变化
const handleCurrentChange = () => {
  loadProductList();
};

// 添加商品
const handleAddProduct = (product: BaseVO) => {
  emit('confirm', product);
  // 关闭对话框
  emit('update:modelValue', false);
};

// 初始化
onMounted(() => {
  // loadBrandList(); // 暂时注释掉
  loadCategoryTree();
});
</script>

<style scoped lang="scss">
.mt-4 {
  margin-top: 16px;
}
</style>
