<template>
  <div class="p-2">
    <!-- 头部信息 -->
    <el-card shadow="hover" class="mb-[10px]">
      <div class="flex items-center">
        <el-button link type="primary" @click="handleBack">
          <el-icon class="mr-1"><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-divider direction="vertical" />
        <span class="mr-4">客户编号: {{ protocolInfo.customerNo }}</span>
        <span class="mr-4">客户名称: {{ protocolInfo.customerName }}</span>
        <span>截止日期: {{ protocolInfo.endTime }}</span>
      </div>
    </el-card>

    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="产品编号" prop="productNo">
              <el-input v-model="queryParams.productNo" placeholder="请输入产品编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品品牌" prop="brandName">
              <el-select v-model="queryParams.brandName" placeholder="请选择" clearable style="width: 200px">
                <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.brandName" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品状态" prop="productStatus">
              <el-select v-model="queryParams.productStatus" placeholder="请选择" clearable style="width: 200px">
                <el-option label="上架" value="1" />
                <el-option label="下架" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择" clearable style="width: 200px">
                <el-option label="待审核" :value="1" />
                <el-option label="审核通过" :value="2" />
                <el-option label="审核驳回" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button type="primary" icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表区域 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8" justify="space-between">
          <el-col :span="1.5">
            <span class="table-title">协议商品详细信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="Check"
              :disabled="selectedProducts.length > 0"
              @click="handleBatchAudit"
            >批量审核</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="productsList" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="checkSelectableForAudit" />
        <el-table-column label="产品编号" align="center" prop="productNo" width="120" />
        <el-table-column label="商品图片" align="center" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.productImage" :width="60" :height="60"/>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" min-width="180">
          <template #default="scope">
            <div>
              <div class="text-primary">{{ scope.row.itemName }}</div>
              <div class="text-gray-400 text-sm">{{ scope.row.brandName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品类别" align="center" prop="categoryName" width="100" />
        <el-table-column label="单位" align="center" prop="unitName" width="80" />
        <el-table-column label="Sku价格" align="center" width="140">
          <template #default="scope">
            <div class="text-left">
              <div>市场价: ¥{{ scope.row.marketPrice || 0 }}</div>
              <div class="text-red-500">官网价: ¥{{ scope.row.memberPrice || 0 }}</div>
              <div>标准成本: ¥{{ scope.row.purchasingPrice || 0 }}</div>
              <div>最低售价: ¥{{ scope.row.minSellingPrice || 0 }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产品来源" align="center" prop="dataSource" width="100" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <span :class="scope.row.productStatus === '1' ? 'text-green-500' : 'text-red-500'">
              {{ scope.row.productStatus === '1' ? '上架' : '下架' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.auditStatus === 1" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 2" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.auditStatus === 3" type="danger">审核驳回</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核意见" align="center" width="150" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.auditReason || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="协议供货价" align="center" width="140">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.agreementPrice"
              :min="0"
              :precision="2"
              size="small"
              controls-position="right"
              @change="handlePriceChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="供货价毛利率" align="center" width="120">
          <template #default="scope">
            {{ calculateMargin(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="80">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 批量审核对话框 -->
    <el-dialog v-model="auditDialog.visible" title="批量审核" width="600px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :value="2">审核通过</el-radio>
            <el-radio :value="3">审核驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditReason">
          <el-input v-model="auditForm.auditReason" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加商品对话框 -->
    <el-dialog title="添加商品" v-model="addProductDialog.visible" width="1400px" append-to-body top="5vh">
      <div class="add-product-dialog">
        <!-- 搜索区域 -->
        <el-form :model="addProductQuery" :inline="true" class="mb-4">
          <el-form-item>
            <el-button type="primary" icon="Plus" @click="handleBatchAdd">加入清单</el-button>
          </el-form-item>
          <el-form-item label="商品名称:">
            <el-input v-model="addProductQuery.itemName" placeholder="商品名称" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="商品编号:">
            <el-input v-model="addProductQuery.productNo" placeholder="商品编号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearchProducts">搜索</el-button>
          </el-form-item>
        </el-form>

        <!-- 商品列表 -->
        <el-table
          ref="addProductTableRef"
          v-loading="addProductDialog.loading"
          :data="addProductDialog.productList"
          border
          @selection-change="handleSelectionChange"
          max-height="500"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
          <el-table-column label="商品编号" align="center" prop="productNo" width="120" />
          <el-table-column label="商品图片" align="center" prop="productImageUrl" width="100">
            <template #default="scope">
              <image-preview :src="scope.row.productImage " :width="60" :height="60"/>
            </template>
          </el-table-column>
          <el-table-column label="商品信息" align="center" min-width="200">
            <template #default="scope">
              <div class="text-left" style="font-size: 12px;">
                <div>{{ scope.row.itemName }}</div>
                <div class="text-gray-500">品牌：{{ scope.row.brandName || '-' }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品分类" align="center" width="150">
            <template #default="scope">
              <div class="text-left" style="font-size: 12px;">
                <div>{{ scope.row.categoryName || '-' }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" width="100">
            <template #default="scope">
              <div class="text-left" style="font-size: 12px;">
                <div>单位：{{ scope.row.unitName || '-' }}</div>
                <div>起订量：{{ scope.row.minOrderQuantity || 1 }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="SKU价格" align="center" width="150">
            <template #default="scope">
              <div class="text-left" style="font-size: 12px;">
                <div>
                  <span class="text-gray-500">市场价:</span>
                  <span>¥{{ scope.row.midRangePrice || scope.row.marketPrice || '0.00' }}</span>
                </div>
                <div>
                  <span class="text-gray-500">官网价:</span>
                  <span class="text-red-500">¥{{ scope.row.standardPrice || scope.row.memberPrice || '0.00' }}</span>
                </div>
                <div>
                  <span class="text-gray-500">最低价:</span>
                  <span>¥{{ scope.row.certificatePrice || scope.row.minSellingPrice || '0.00' }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="isProductAdded(scope.row.id)" type="info">已添加</el-tag>
              <el-tag v-else-if="scope.row.productStatus === '1'" type="success">上架</el-tag>
              <el-tag v-else type="warning">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template #default="scope">
              <el-link
                v-if="!isProductAdded(scope.row.id)"
                type="primary"
                :underline="false"
                @click="handleAddSingleProduct(scope.row)"
              >加入清单</el-link>
              <span v-else class="text-gray-400">已添加</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="addProductDialog.productList.length > 0"
          v-model:page="addProductQuery.pageNum"
          v-model:limit="addProductQuery.pageSize"
          v-model:way="addProductQuery.way"
          :cursor-mode="true"
          :has-more="addProductHasMore"
          @pagination="getProductListForAdd"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="ProductManage" lang="ts">
import { listProducts, delProducts, updateProducts, addProducts, getProtocolProductIds, updateProductsPrice, updateProductsAudit } from '@/api/product/products';
import { ProductsQuery, ProductsForm } from '@/api/product/products/types';
import { getInfo } from '@/api/product/protocolInfo';
import { listBrand } from '@/api/product/brand';
import { BrandVO } from '@/api/product/brand/types';
import { BaseVO, BaseQuery } from '@/api/product/base/types';
import { listBase } from '@/api/product/base';
import { ArrowLeft } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();

// 协议ID
const protocolId = ref<string | number>('');
// 协议编号
const protocolNo = ref<string>('');
// 协议信息
const protocolInfo = ref<any>({
  customerNo: '',
  customerName: '',
  endTime: ''
});

const productsList = ref<BaseVO[]>([]);
const brandList = ref<BrandVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<ProductsQuery>({
  pageNum: 1,
  pageSize: 10,
  protocolId: route.query.protocolId as string | number,
  protocolNo: undefined,
  productNo: undefined,
  productName: undefined,
  brandName: undefined,
  productStatus: undefined
});

// 已关联的产品ID列表
const addedProductIds = ref<Set<string | number>>(new Set());

// 添加商品对话框
const addProductDialog = reactive({
  visible: false,
  loading: false,
  productList: [] as BaseVO[],
  total: 0
});

// 游标分页相关变量
const addProductHasMore = ref(true);
const addProductPageHistory = ref<Array<{ firstId: string | number; lastId: string | number }>>([]);

// 添加商品查询参数
const addProductQuery = ref<BaseQuery>({
  pageNum: 1,
  pageSize: 10,
  way: undefined,
  productNo: undefined,
  itemName: undefined,
  lastSeenId: undefined
});

// 选中的商品（添加商品弹窗用）
const selectedProducts = ref<BaseVO[]>([]);
const addProductTableRef = ref<any>();

// 列表选中的商品（批量审核用）
const tableSelectedProducts = ref<BaseVO[]>([]);

// 审核对话框
const auditDialog = reactive({
  visible: false
});

// 审核表单
const auditFormRef = ref<ElFormInstance>();
const auditForm = ref({
  auditStatus: 2,
  auditReason: '',
  protocolId: route.query.protocolId as string | number
});

// 审核表单验证规则
const auditRules = ref({
  auditStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  auditReason: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
});

/** 查询协议商品列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listProducts(queryParams.value);
    productsList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

/** 加载协议信息 */
const loadProtocolInfo = async () => {
  if (!protocolId.value) return;
  const res = await getInfo(protocolId.value);
  if (res.data) {
    protocolInfo.value = {
      customerNo: res.data.customerNo || '',
      customerName: res.data.customerName || '',
      endTime: res.data.endTime ? parseTime(res.data.endTime, '{y}/{m}/{d} {h}:{i}:{s}') : ''
    };
    // 设置协议编号用于查询
    protocolNo.value = res.data.protocolNo || '';
    queryParams.value.protocolNo = res.data.protocolNo;
  }
};

/** 加载品牌列表 */
const loadBrandList = async () => {
  const res = await listBrand({ pageNum: 1, pageSize: 1000 });
  brandList.value = res.rows || [];
};

/** 加载已关联的产品ID列表 */
const loadAddedProductIds = async () => {
  const protocolId = route.query.protocolId as string | number;
  try {
    const res = await getProtocolProductIds(protocolId);
    addedProductIds.value = new Set(res.data || []);
  } catch (error) {
    console.error('获取已关联产品ID失败:', error);
    addedProductIds.value = new Set();
  }
};

/** 判断商品是否已添加 */
const isProductAdded = (productId: string | number): boolean => {
  return addedProductIds.value.has(String(productId)) || addedProductIds.value.has(Number(productId));
};

/** 检查行是否可选择 */
const checkSelectable = (row: BaseVO): boolean => {
  return !isProductAdded(row.id);
};

/** 格式化时间 */
const parseTime = (time: any, pattern?: string) => {
  if (!time) return '';
  const date = new Date(time);
  const fmt = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  const o: Record<string, number> = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds()
  };
  return fmt.replace(/{([ymdhis])+}/g, (match, key) => {
    const val = o[key];
    return val.toString().padStart(2, '0');
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 保留协议编号
  const pNo = queryParams.value.protocolNo;
  const protocolId = queryParams.value.protocolId
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    protocolNo: pNo,
    protocolId: protocolId || undefined,
    productNo: undefined,
    productName: undefined,
    brandName: undefined,
    productStatus: undefined
  };
  handleQuery();
};

/** 返回按钮 */
const handleBack = () => {
  router.back();
};

/** 添加商品按钮 */
const handleAdd = async () => {
  addProductDialog.visible = true;
  // 重置查询条件
  addProductQuery.value = {
    pageNum: 1,
    pageSize: 10,
    way: undefined,
    productNo: undefined,
    itemName: undefined,
    lastSeenId: undefined
  };
  // 重置游标分页状态
  addProductPageHistory.value = [];
  addProductHasMore.value = true;
  selectedProducts.value = [];
  // 先加载已关联的产品ID
  await loadAddedProductIds();
  // 再加载商品列表
  getProductListForAdd();
};

/** 获取商品列表用于添加 */
const getProductListForAdd = async () => {
  addProductDialog.loading = true;
  try {
    const params = { ...addProductQuery.value };
    const currentPageNum = addProductQuery.value.pageNum;

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

    const res = await listBase(params);
    // 兼容两种返回结构
    if (res.rows) {
      addProductDialog.productList = res.rows;
      addProductDialog.total = res.total || 0;
    } else if (res.data) {
      addProductDialog.productList = Array.isArray(res.data) ? res.data : [];
      addProductDialog.total = addProductDialog.productList.length;
    } else {
      addProductDialog.productList = [];
      addProductDialog.total = 0;
    }

    // 判断是否还有更多数据
    addProductHasMore.value = addProductDialog.productList.length === addProductQuery.value.pageSize;

    // 记录当前页的第一个id和最后一个id
    if (addProductDialog.productList.length > 0) {
      const firstItem = addProductDialog.productList[0];
      const lastItem = addProductDialog.productList[addProductDialog.productList.length - 1];
      // 如果长度小于currentPageNum则创建
      if (addProductPageHistory.value.length <= currentPageNum) {
        addProductPageHistory.value[currentPageNum] = {
          firstId: firstItem.id,
          lastId: lastItem.id
        };
      }
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    addProductDialog.productList = [];
    addProductDialog.total = 0;
  } finally {
    addProductDialog.loading = false;
  }
};

/** 搜索商品 */
const handleSearchProducts = () => {
  addProductQuery.value.pageNum = 1;
  addProductQuery.value.lastSeenId = undefined;
  addProductPageHistory.value = []; // 重置页面历史
  addProductHasMore.value = true;
  getProductListForAdd();
};

/** 选择变化（添加商品弹窗用） */
const handleSelectionChange = (selection: BaseVO[]) => {
  selectedProducts.value = selection;
};

/** 表格选择变化（批量审核用） */
const handleTableSelectionChange = (selection: BaseVO[]) => {
  tableSelectedProducts.value = selection;
};

/** 检查行是否可选择（批量审核用，只有待审核状态才能选择） */
const checkSelectableForAudit = (row: BaseVO): boolean => {
  return row.auditStatus === 1;
};

/** 批量审核按钮 */
const handleBatchAudit = () => {
  if (tableSelectedProducts.value.length === 0) {
    proxy?.$modal.msgWarning('请先选择要审核的商品');
    return;
  }
  auditDialog.visible = true;
  auditForm.value = {
    protocolId: route.query.protocolId as string | number,
    auditStatus: 2,
    auditReason: ''
  };
};

/** 提交批量审核 */
const submitBatchAudit = async () => {
  await auditFormRef.value?.validate();
  try {
    const data = tableSelectedProducts.value.map(item => ({
      id: item.id,
      productId: item.id,
      protocolId: auditForm.value.protocolId,
      auditStatus: auditForm.value.auditStatus,
      auditReason: auditForm.value.auditReason
    }));
    await updateProductsAudit(data);
    proxy?.$modal.msgSuccess(auditForm.value.auditStatus === 2 ? '审核通过' : '审核驳回');
    auditDialog.visible = false;
    await getList();
  } catch (error) {
    console.error('批量审核失败:', error);
    proxy?.$modal.msgError('审核失败');
  }
};

/** 批量加入清单 */
const handleBatchAdd = async () => {
  if (selectedProducts.value.length === 0) {
    proxy?.$modal.msgWarning('请先选择要添加的商品');
    return;
  }

  try {
    // 逐个添加商品
    for (const product of selectedProducts.value) {
      const data: ProductsForm = {
        protocolNo: protocolNo.value,
        protocolId: route.query.protocolId as string | number,
        productNo: product.productNo,
        productId: product.id,
        agreementPrice: product.standardPrice || product.midRangePrice || product.memberPrice || 0,
        customerId: protocolInfo.value.customerId,
        dataSource: product.dataSource
      };
      await addProducts(data);
    }

    proxy?.$modal.msgSuccess(`成功添加 ${selectedProducts.value.length} 个商品`);
    addProductDialog.visible = false;
    // 清空选中项
    selectedProducts.value = [];
    if (addProductTableRef.value) {
      addProductTableRef.value.clearSelection();
    }
    // 刷新列表
    await loadAddedProductIds();
    await getList();
  } catch (error) {
    console.error('添加商品失败:', error);
    proxy?.$modal.msgError('添加商品失败');
  }
};

/** 添加单个商品 */
const handleAddSingleProduct = async (row: BaseVO) => {
  try {
    const data: ProductsForm = {
      protocolNo: protocolNo.value,
      protocolId: route.query.protocolId as string | number,
      productNo: row.productNo,
      productId: row.id,
      agreementPrice: row.standardPrice || row.midRangePrice || row.memberPrice || 0,
      customerId: protocolInfo.value.customerId,
      dataSource: row.dataSource
    };
    await addProducts(data);

    proxy?.$modal.msgSuccess('添加成功');
    // 更新已添加的产品ID列表
    addedProductIds.value.add(row.id);
    // 刷新主列表
    await getList();
  } catch (error) {
    console.error('添加商品失败:', error);
    proxy?.$modal.msgError('添加商品失败');
  }
};

/** 导入商品按钮 */
const handleImport = () => {
  proxy?.$modal.msgWarning('导入商品功能待实现');
};

/** 导出商品按钮 */
const handleExport = () => {
  proxy?.download('product/products/export', {
    ...queryParams.value
  }, `products_${new Date().getTime()}.xlsx`);
};

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  await proxy?.$modal.confirm('是否确认删除该商品？');
  await delProducts(row.id);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 协议供货价变更 */
const handlePriceChange = async (row: any) => {
  try {
    await updateProductsPrice({
      agreementPrice: row.agreementPrice,
      productId: row.id,
      protocolId: route.query.protocolId as string | number
    });
    proxy?.$modal.msgSuccess('价格更新成功');
  } catch (error) {
    proxy?.$modal.msgError('价格更新失败');
  }
};

/** 计算供货价毛利率 */
const calculateMargin = (row: any) => {
  if (!row.agreementPrice || !row.purchasingPrice || row.purchasingPrice === 0) {
    return '-';
  }
  const margin = ((row.agreementPrice - row.purchasingPrice) / row.agreementPrice * 100).toFixed(2)+'%';
  return margin;
};

onMounted(() => {
  // 从路由参数获取协议ID
  protocolId.value = route.query.protocolId as string || route.params.id as string || '';
  if (protocolId.value) {
    loadProtocolInfo();
    loadBrandList();
    getList();
  } else {
    proxy?.$modal.msgError('缺少协议ID参数');
    router.back();
  }
});
</script>

<style scoped>
.text-primary {
  color: #409eff;
}
.text-gray-400 {
  color: #909399;
}
.text-gray-500 {
  color: #909399;
}
.text-red-500 {
  color: #f56c6c;
}
.text-green-500 {
  color: #67c23a;
}
.text-sm {
  font-size: 12px;
}
.add-product-dialog {
  :deep(.el-form--inline .el-form-item) {
    margin-right: 10px;
  }
}
</style>
