<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加商品报价"
    width="90%"
    :close-on-click-modal="false"
    @close="handleClose"
    class="product-dialog"
    :modal-append-to-body="false"
    :append-to-body="true"
  >
    <div class="dialog-content">
      <!-- 搜索表单区域 - 固定 -->
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" label-width="80px">
          <el-row :gutter="16" class="first-row">
            <el-col :span="6"> <!-- 调整为6列，均分24列，避免宽度不足 -->
              <el-form-item label="产品编号：" prop="productNo">
                <el-input v-model="queryParams.productNo" placeholder="请输入产品编号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品名称：" prop="itemName">
                <el-input v-model="queryParams.itemName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="品牌名称：" prop="brandName">
                <el-input v-model="queryParams.brandName" placeholder="请选择" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上架状态：" prop="productStatus">
                <el-select v-model="queryParams.productStatus" placeholder="请选择" clearable style="width: 100%">
                  <el-option label="已上架" :value="1" />
                  <el-option label="下架" :value="0" />
                  <el-option label="上架中" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16" class="second-row">
            <el-col :span="24" style="text-align: left;">
              <el-button type="primary" icon="Plus" @click="handleBatchAddToList">批量加入清单</el-button>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 表格区域 - 可滚动 -->
      <div class="table-wrapper">
        <el-table 
          v-loading="loading" 
          border 
          :data="baseList" 
          @selection-change="handleSelectionChange"
          max-height="calc(70vh - 200px)"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="产品编号" align="center" prop="productNo" width="110" />
          <el-table-column label="产品图片" align="center" prop="productImage" width="90">
            <template #default="scope">
              <image-preview :src="scope.row.productImage" :width="60" :height="60" />
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="itemName" width="180" show-overflow-tooltip />
          <el-table-column label="产品类型" align="center" prop="categoryName" width="110" />
          <el-table-column label="品牌" align="center" prop="brandName" width="100" />
          <el-table-column label="单位" align="center" prop="unitName" width="70" />
          <el-table-column label="市场价" align="center" width="90">
            <template #default="scope">
              <span>¥{{ scope.row.marketPrice || '0.00' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="平台售价" align="center" width="90">
            <template #default="scope">
              <span>¥{{ scope.row.memberPrice || '0.00' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="起订量" align="center" prop="minOrderQuantity" width="70" />
          <el-table-column label="上架状态" align="center" prop="productStatus" width="90">
            <template #default="scope">
              <el-tag v-if="scope.row.productStatus === 1" type="success">已上架</el-tag>
              <el-tag v-else-if="scope.row.productStatus === 0" type="warning">下架</el-tag>
              <el-tag v-else-if="scope.row.productStatus === 2" type="info">上架中</el-tag>
              <el-tag v-else type="info">未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" fixed="right"> <!-- 固定右侧，避免空白 -->
            <template #default="scope">
              <el-button link type="primary" @click="handleAddToList(scope.row)">加入清单</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <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"
          />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup name="Base" lang="ts">
// 补充必要的导入
import { getCurrentInstance, ComponentInternalInstance, computed, ref, reactive, onMounted } from 'vue';
import type { ElFormInstance } from 'element-plus';

// Props 定义
interface Props {
  visible: boolean;
  modelValue: any[];
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  modelValue: () => []
});

// Emits 定义
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'update:modelValue': [value: any[]];
  'confirm': [selectedProducts: any[]];
}>();

// 控制 dialog 显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false);
};

// 模拟接口（如果实际项目有，可替换）
import { listBase, categoryTree } from '@/api/product/base';
import { BaseVO, BaseQuery, BaseForm } from '@/api/product/base/types';
import { categoryTreeVO } from '@/api/product/category/types';
import Pagination from '@/components/Pagination/index.vue';

// 类型补充
interface PageData<F, Q> {
  form: F;
  queryParams: Q;
  rules: Record<string, any>;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const baseList = ref<BaseVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const categoryOptions = ref<categoryTreeVO[]>([]);
const hasMore = ref(true);
const pageHistory = ref([]);

const queryFormRef = ref<ElFormInstance>();

const initFormData: BaseForm = {
  id: undefined,
  productNo: undefined,
  itemName: undefined,
  brandId: undefined,
  topCategoryId: undefined,
  mediumCategoryId: undefined,
  bottomCategoryId: undefined,
  unitId: undefined,
  productImage: undefined,
  isSelf: undefined,
  productReviewStatus: undefined,
  homeRecommended: undefined,
  categoryRecommendation: undefined,
  cartRecommendation: undefined,
  recommendedProductOrder: undefined,
  isPopular: undefined,
  isNew: undefined,
  productStatus: undefined,
  remark: undefined
};

const data = reactive<PageData<BaseForm, BaseQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productNo: undefined,
    itemName: undefined,
    brandName: 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,
    way: undefined,
    params: {}
  },
  rules: {
    productNo: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
    itemName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    brandId: [{ required: true, message: '品牌id不能为空', trigger: 'blur' }],
    topCategoryId: [{ required: true, message: '顶级分类id不能为空', trigger: 'blur' }],
    mediumCategoryId: [{ required: true, message: '中级分类id不能为空', trigger: 'blur' }],
    bottomCategoryId: [{ required: true, message: '底层分类id不能为空', trigger: 'blur' }],
    unitId: [{ required: true, message: '单位id不能为空', trigger: 'blur' }],
    productImage: [{ required: true, message: '产品图片URL不能为空', trigger: 'blur' }],
    productReviewStatus: [{ required: true, message: '产品审核状态不能为空', trigger: 'change' }],
    homeRecommended: [{ required: true, message: '首页推荐不能为空', trigger: 'blur' }],
    categoryRecommendation: [{ required: true, message: '分类推荐不能为空', trigger: 'blur' }],
    cartRecommendation: [{ required: true, message: '购物车推荐不能为空', trigger: 'blur' }],
    recommendedProductOrder: [{ required: true, message: '推荐产品顺序不能为空', trigger: 'blur' }],
    isPopular: [{ required: true, message: '是否热门不能为空', trigger: 'blur' }],
    isNew: [{ required: true, message: '是否新品不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams } = toRefs(data);

/** 查询产品基础信息列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    const currentPageNum = queryParams.value.pageNum;

    if (currentPageNum === 1) {
      delete params.lastSeenId;
      delete params.way;
    } else {
      if (queryParams.value.way === 0) {
        const nextPageHistory = pageHistory.value[currentPageNum];
        if (nextPageHistory) {
          params.firstSeenId = nextPageHistory.firstId;
          params.way = 0;
        }
      } else {
        const prevPageHistory = pageHistory.value[currentPageNum - 1];
        if (prevPageHistory) {
          params.lastSeenId = prevPageHistory.lastId;
          params.way = 1;
        }
      }
    }

    const res = await listBase(params);
    baseList.value = res.rows || [];
    hasMore.value = baseList.value.length === queryParams.value.pageSize;

    if (baseList.value.length > 0) {
      const firstItem = baseList.value[0];
      const lastItem = baseList.value[baseList.value.length - 1];
      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 handleQuery = () => {
  queryParams.value = {
    ...queryParams.value,
    pageNum: 1,
    productNo: queryParams.value.productNo,
    itemName: queryParams.value.itemName,
    brandName: queryParams.value.brandName,
    bottomCategoryId: queryParams.value.bottomCategoryId,
    isSelf: queryParams.value.isSelf,
    productReviewStatus: queryParams.value.productReviewStatus,
    productStatus: queryParams.value.productStatus,
    lastSeenId: undefined
  };
  pageHistory.value = [];
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.lastSeenId = undefined;
  pageHistory.value = [];
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BaseVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 加入清单 */
const handleAddToList = (row: BaseVO) => {
  const existsInModelValue = props.modelValue.some(item => item.productId === row.id);
  if (existsInModelValue) {
    proxy?.$modal.msgWarning('该商品已在清单中');
    return;
  }
  
  const newProduct = {
    productId: row.id,
    productCode: row.productNo,
    productImage: row.productImage,
    productName: row.itemName,
    productType: row.categoryName,
    brand: row.brandName,
    unit: row.unitName,
    basePrice: row.purchasingPrice || 0,
    marketPrice: row.marketPrice || 0,
    platformPrice: row.memberPrice || 0,
    offerPrice: '',
    supplyCycle: '',
    upPrice: Number(row.productStatus) === 1 ? '上架' : '下架'
  };
  
  emit('update:modelValue', [...props.modelValue, newProduct]);
  proxy?.$modal.msgSuccess('添加成功');
  emit('update:visible', false);
};

/** 批量加入清单 */
const handleBatchAddToList = () => {
  const selectedProducts = baseList.value.filter(item => ids.value.includes(item.id));
  
  if (selectedProducts.length === 0) {
    proxy?.$modal.msgWarning('请选择要添加的商品');
    return;
  }
  
  const newProducts: any[] = [];
  
  selectedProducts.forEach(row => {
    const exists = props.modelValue.some(item => item.productId === row.id);
    if (!exists) {
      newProducts.push({
        productId: row.id,
        productCode: row.productNo,
        productImage: row.productImage,
        productName: row.itemName,
        productType: row.categoryName,
        brand: row.brandName,
        unit: row.unitName,
        basePrice: row.purchasingPrice || 0,
        marketPrice: row.marketPrice || 0,
        platformPrice: row.memberPrice || 0,
        offerPrice: '',
        supplyCycle: '',
        upPrice: Number(row.productStatus) === 1 ? '上架' : '下架'
      });
    }
  });
  
  if (newProducts.length === 0) {
    proxy?.$modal.msgWarning('所选商品已在清单中');
    return;
  }
  
  emit('update:modelValue', [...props.modelValue, ...newProducts]);
  proxy?.$modal.msgSuccess(`成功添加${newProducts.length}个商品`);
  emit('update:visible', false);
};

/** 查询分类树 */
const getCategoryTree = async () => {
  const res = await categoryTree();
  categoryOptions.value = res.data || [];
};

onMounted(() => {
  getList();
  getCategoryTree();
});
</script>

<style scoped>
/* 核心：禁止外层滚动，仅表格内部滚动 */
.product-dialog {
  overflow: hidden !important;
}

.product-dialog :deep(.el-dialog__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden !important; /* 禁止对话框主体滚动 */
  height: calc(90vh); /* 限制对话框主体高度，避免超出视口 */
}

.dialog-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden !important; /* 禁止内容容器滚动 */
}

.search-container {
  flex-shrink: 0;
  padding: 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  box-sizing: border-box; /* 内边距不影响宽度 */
  width: 100%;
}

.search-container :deep(.el-form) {
  margin-bottom: 0;
  width: 100%;
}

.search-container :deep(.el-row) {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-container .first-row {
  margin-bottom: 16px;
}

.search-container :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-container :deep(.el-form-item__label) {
  font-weight: normal;
  white-space: nowrap;
}

.search-container :deep(.el-input),
.search-container :deep(.el-select) {
  width: 100%;
}

/* 表格容器：仅让表格内部滚动，外层不滚动 */
.table-wrapper {
  flex: 1; /* 占满剩余高度 */
  padding: 16px;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden !important; /* 禁止表格容器滚动 */
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  flex-shrink: 0; /* 分页栏不压缩 */
}

/* 修复固定列样式 */
.product-dialog :deep(.el-table__fixed-right) {
  height: calc(100% - 17px) !important; /* 匹配表格高度 */
}
</style>