<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>

    <!-- 分页 -->
    <pagination
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      v-model:way="queryParams.way"
      :cursor-mode="true"
      :has-more="hasMore"
      :total="total"
      @pagination="getList"
    />
  </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<any>({
  pageNum: 1,
  pageSize: 10,
  productNo: undefined,
  itemName: undefined,
  brandName: undefined,
  brandId: undefined,
  productTag: undefined,
  purchaseNature: undefined,
  supplierType: undefined,
  supplierNature: undefined,
  projectOrg: undefined,
  topCategoryId: undefined,
  mediumCategoryId: undefined,
  bottomCategoryId: undefined,
  isSelf: undefined,
  productReviewStatus: undefined,
  productStatus: undefined,
  lastSeenId: undefined,
  firstSeenId: undefined,
  way: undefined,
  params: {}
});

const hasMore = ref(true); // 是否还有更多数据
// 页面历史记录，存储每页的第一个id和最后一个id，用于支持双向翻页
const pageHistory = ref([]);

// 对话框状态变化
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 = () => {
  // 重置查询参数到第一页
  queryParams.value.pageNum = 1;
  queryParams.value.lastSeenId = undefined;
  queryParams.value.firstSeenId = undefined;
  queryParams.value.way = undefined;
  pageHistory.value = [];
  loadProductList();
};

// 对话框关闭时触发
const handleClose = () => {
  // 重置查询参数
  queryParams.value.pageNum = 1;
  queryParams.value.productNo = undefined;
  queryParams.value.itemName = undefined;
  queryParams.value.brandId = undefined;
  queryParams.value.bottomCategoryId = undefined;
  queryParams.value.productStatus = undefined;
  productList.value = [];
  pageHistory.value = [];
};

// // 加载商品列表
// 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 loadProductList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    const currentPageNum = queryParams.value.pageNum;

    // 第一页不需要游标参数
    if (currentPageNum === 1) {
      delete params.lastSeenId;
      delete params.way;
    } else {
      // way参数：0=上一页，1=下一页
      if (queryParams.value.way === 0) {
        // 上一页：使用目标页（即当前显示页）的firstId
        const nextPageHistory = pageHistory.value[currentPageNum];
        if (nextPageHistory) {
          params.firstSeenId = nextPageHistory.firstId;
          params.way = 0;
        }
      } else {
        // 下一页：使用前一页的lastId作为lastSeenId
        const prevPageHistory = pageHistory.value[currentPageNum - 1];
        if (prevPageHistory) {
          params.lastSeenId = prevPageHistory.lastId;
          params.way = 1;
        }
      }
    }

    const res = await listBase(params);
    productList.value = res.rows || [];

    // 判断是否还有更多数据
    hasMore.value = productList.value.length === queryParams.value.pageSize;

    // 记录当前页的第一个id和最后一个id
    if (productList.value.length > 0) {
      const firstItem = productList.value[0];
      const lastItem = productList.value[productList.value.length - 1];
      //如果长度小于currentPageNum则创建

      if (pageHistory.value.length <= currentPageNum) {
        pageHistory.value[currentPageNum] = {
          firstId: firstItem.id,
          lastId: lastItem.id
        };
      }
    }

    total.value = res.total || 0;
  } catch (error) {
    console.error('获取列表失败:', error);
  } 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);
};

// 分页查询
const getList = () => {
  loadProductList();
};

// 初始化
onMounted(() => {
  // loadBrandList();
  loadCategoryTree();
});
</script>

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