<template>
  <div class="p-2">
    <!-- 返回按钮 + 标题 -->
    <el-card shadow="never" class="mb-2">
      <div class="flex items-center">
        <el-button link @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-divider direction="vertical" />
        <span class="text-base font-medium">商品配置</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" label-width="70px">
            <el-form-item label="商品编号" prop="productNo">
              <el-input v-model="queryParams.productNo" placeholder="请输入商品编号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品名称" prop="itemName">
              <el-input v-model="queryParams.itemName" placeholder="请输入商品名称" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商品品牌" prop="brandId">
              <el-select v-model="queryParams.brandId" placeholder="请选择" clearable style="width: 120px">
                <el-option v-for="item in brandOptions" :key="item.id" :label="item.brandName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品类别" prop="categoryId">
              <el-select v-model="queryParams.topCategoryId" placeholder="请选择" clearable style="width: 100px" @change="handleTopCategoryChange">
                <el-option v-for="item in topCategoryOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
              </el-select>
              <el-select v-model="queryParams.mediumCategoryId" placeholder="请选择" clearable style="width: 100px; margin-left: 5px" @change="handleMediumCategoryChange">
                <el-option v-for="item in mediumCategoryOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
              </el-select>
              <el-select v-model="queryParams.bottomCategoryId" placeholder="请选择" clearable style="width: 100px; margin-left: 5px">
                <el-option v-for="item in bottomCategoryOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 表格区域 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-bold text-[#409EFF]">商品列表信息列表</span>
          <div class="flex gap-2">
            <el-button type="primary" icon="Plus" @click="handleAddProduct">添加商品</el-button>
            <el-button type="primary" icon="Upload" @click="handleImportProduct">导入商品</el-button>
            <el-button type="primary" icon="Download" @click="handleExportProduct">导出商品</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" border :data="productList">
        <el-table-column label="商品编号" align="center" prop="productNo" width="100" />
        <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="400">
          <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" prop="categoryName" width="120" />
        <el-table-column label="单位" align="center" width="100">
          <template #default="scope">
            <div 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="130">
          <template #default="scope">
            <div class="text-left" style="font-size: 12px;">
              <div>市场价：¥{{ scope.row.marketPrice || '0.00' }}</div>
              <div class="text-[#f56c6c]">平台售价：¥{{ scope.row.platformPrice || '0.00' }}</div>
              <div>最低售价：¥{{ scope.row.minPrice || '0.00' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="采购价" align="center" prop="purchasePrice" width="100" />
        <el-table-column label="协议价" align="center" prop="agreementPrice" width="100" />
        <el-table-column label="毛利率" align="center" width="130">
          <template #default="scope">
            {{ calcGrossMargin(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="商品状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.productStatus === '1'" type="success" size="small">上架</el-tag>
            <el-tag v-else type="info" size="small">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="scope">
            <div class="flex flex-col items-center gap-1">
              <el-link type="primary" :underline="false" @click="handlePriceEdit(scope.row)">价格修改</el-link>
              <el-link type="danger" :underline="false" @click="handleDelete(scope.row)">删 除</el-link>
            </div>
          </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 title="价格修改" v-model="priceDialog.visible" width="500px" append-to-body>
      <el-form ref="priceFormRef" :model="priceDialog.form" :rules="priceRules" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ priceDialog.row?.itemName }}</span>
        </el-form-item>
        <el-form-item label="协议价" prop="agreementPrice">
          <el-input-number v-model="priceDialog.form.agreementPrice" :precision="2" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="priceDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitPriceForm">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 导入商品弹窗 -->
    <el-dialog title="导入商品" v-model="importDialog.visible" width="500px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="导入模板">
          <el-button type="primary" link icon="Download" @click="handleDownloadTemplate">下载导入模板</el-button>
        </el-form-item>
        <el-form-item label="选择文件">
          <el-upload
            ref="importUploadRef"
            action="#"
            :auto-upload="false"
            :limit="1"
            accept=".xlsx,.xls"
            :on-change="handleImportFileChange"
            :on-remove="() => (importDialog.file = null)"
          >
            <el-button type="primary" icon="Upload">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">只支持 .xlsx / .xls 格式文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="importDialog.loading" @click="handleConfirmImport">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 添加商品弹窗 -->
    <el-dialog title="添加商品" v-model="addProductDialog.visible" width="1500px" 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: 180px" />
          </el-form-item>
          <el-form-item label="商品编号:">
            <el-input v-model="addProductQuery.productNo" placeholder="商品编号" clearable style="width: 180px" />
          </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" />
          <el-table-column label="商品编号" align="center" prop="productNo" width="100" />
          <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="400">
            <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" prop="categoryName" width="120" />
          <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="130">
            <template #default="scope">
              <div class="text-left" style="font-size: 12px;">
                <div>市场价：¥{{ scope.row.midRangePrice || '0.00' }}</div>
                <div class="text-[#f56c6c]">平台价：¥{{ scope.row.standardPrice || '0.00' }}</div>
                <div>最低价：¥{{ scope.row.certificatePrice || '0.00' }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库存情况" align="center" width="130">
            <template #default="scope">
              <div class="text-left" style="font-size: 12px;">
                <div class="text-[#f56c6c]">库存总数：{{ scope.row.stock || 0 }}</div>
                <div>现有库存：{{ scope.row.availableStock || 0 }}</div>
                <div>虚拟库存：{{ scope.row.virtualStock || 0 }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="采购价" align="center" prop="purchasingPrice" width="80" />
          <el-table-column label="商品状态" align="center" prop="productStatus" width="80" >
            <template #default="scope">
              <el-tag v-if="scope.row.productStatus === '1'" type="success" size="small">上架</el-tag>
              <el-tag v-else type="info" size="small">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="协议价" align="center" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.agreementPrice"
                :precision="2"
                :min="0"
                controls-position="right"
                style="width: 120px"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="handleAddSingleProduct(scope.row)">加入清单</el-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="addProductDialog.productList.length > 0"
          v-model:page="addProductQuery.pageNum"
          v-model:limit="addProductQuery.pageSize"
          :total="addProductDialog.total"
          @pagination="getProductList"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="ProductConfig" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { listBase } from '@/api/pmsProduct/base';
import { listProductCategory } from '@/api/customerOperation/customerBlacklist';
import { listBrand } from '@/api/product/brand';
import {
  addSiteProduct,
  getSiteProductPage,
  exportSiteProductData,
  importSiteProductData,
  getSiteProductImportTemplate,
  updateSiteProduct,
  delSiteProduct
} from '@/api/product/siteProduct/index';
import FileSaver from 'file-saver';

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

const productList = ref<any[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

// 从路由获取站点信息
const siteId = ref<string | number | undefined>(undefined);
const siteName = ref<string>('');

// 品牌选项
const brandOptions = ref<any[]>([]);

// 分类三级联动
const topCategoryOptions = ref<any[]>([]);
const mediumCategoryOptions = ref<any[]>([]);
const bottomCategoryOptions = ref<any[]>([]);
const allCategoryList = ref<any[]>([]);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  siteId: undefined as string | number | undefined,
  productNo: undefined as string | undefined,
  itemName: undefined as string | undefined,
  brandId: undefined as number | undefined,
  topCategoryId: undefined as number | undefined,
  mediumCategoryId: undefined as number | undefined,
  bottomCategoryId: undefined as number | undefined
});

// 价格修改弹窗
const priceDialog = reactive({
  visible: false,
  row: null as any,
  form: {
    id: undefined as number | undefined,
    agreementPrice: 0
  }
});
const priceFormRef = ref<FormInstance>();
const priceRules = {
  agreementPrice: [{ required: true, message: '请输入协议价', trigger: 'blur' }]
};

// 添加商品弹窗
const addProductDialog = reactive({
  visible: false,
  loading: false,
  productList: [] as any[],
  total: 0
});
const addProductQuery = ref({
  pageNum: 1,
  pageSize: 10,
  isSelf: 1,
  productNo: undefined as string | undefined,
  itemName: undefined as string | undefined
});
const selectedProducts = ref<any[]>([]);
const addProductTableRef = ref<any>();

// 导入商品弹窗
const importDialog = reactive({
  visible: false,
  loading: false,
  file: null as File | null
});
const importUploadRef = ref<any>();

/** 初始化 */
const initData = () => {
  siteId.value = route.query.siteId as string;
  siteName.value = route.query.siteName as string || '';
  queryParams.value.siteId = siteId.value;
  getList();
};

/** 查询商品列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await getSiteProductPage({
      ...queryParams.value,
      bottomCategoryId: queryParams.value.bottomCategoryId || queryParams.value.mediumCategoryId || queryParams.value.topCategoryId
    });
    productList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取商品列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 加载品牌列表 */
const loadBrandOptions = async () => {
  try {
    const res = await listBrand({ pageNum: 1, pageSize: 1000 });
    brandOptions.value = res.rows || [];
  } catch (error) {
    console.error('获取品牌列表失败:', error);
  }
};

/** 加载商品分类 */
const loadCategoryOptions = async () => {
  try {
    const res = await listProductCategory({ pageNum: 1, pageSize: 1000, dataSource: 'A10' });
    allCategoryList.value = res.rows || [];
    topCategoryOptions.value = allCategoryList.value.filter((item: any) => !item.parentId || item.parentId === 0);
  } catch (error) {
    console.error('加载分类失败:', error);
  }
};

/** 顶级分类变化 */
const handleTopCategoryChange = (val: number | undefined) => {
  queryParams.value.mediumCategoryId = undefined;
  queryParams.value.bottomCategoryId = undefined;
  bottomCategoryOptions.value = [];
  if (val) {
    mediumCategoryOptions.value = allCategoryList.value.filter((item: any) => item.parentId === val);
  } else {
    mediumCategoryOptions.value = [];
  }
};

/** 中级分类变化 */
const handleMediumCategoryChange = (val: number | undefined) => {
  queryParams.value.bottomCategoryId = undefined;
  if (val) {
    bottomCategoryOptions.value = allCategoryList.value.filter((item: any) => item.parentId === val);
  } else {
    bottomCategoryOptions.value = [];
  }
};

/** 计算毛利率：(协议价 - 采购价) ÷ 采购价 × 100% */
const calcGrossMargin = (row: any): string => {
  const agreement = parseFloat(row.agreementPrice);
  const purchase = parseFloat(row.purchasePrice || row.purchasingPrice);
  if (!purchase || purchase === 0 || isNaN(agreement) || isNaN(purchase)) return '-';
  const margin = ((agreement - purchase) / purchase) * 100;
  return `${margin.toFixed(2)}%`;
};

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

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    siteId: siteId.value,
    productNo: undefined,
    itemName: undefined,
    brandId: undefined,
    topCategoryId: undefined,
    mediumCategoryId: undefined,
    bottomCategoryId: undefined
  };
  mediumCategoryOptions.value = [];
  bottomCategoryOptions.value = [];
  handleQuery();
};

/** 返回 */
const handleBack = () => {
  router.push('/customerOperation/vipSite');
};

/** 价格修改 */
const handlePriceEdit = (row: any) => {
  priceDialog.row = row;
  priceDialog.form = {
    id: row.id,
    agreementPrice: row.agreementPrice || 0
  };
  priceDialog.visible = true;
};

/** 提交价格修改 */
const submitPriceForm = async () => {
  await priceFormRef.value?.validate();
  await updateSiteProduct({
    id: priceDialog.form.id,
    agreementPrice: String(priceDialog.form.agreementPrice)
  });
  proxy?.$modal.msgSuccess('价格修改成功');
  priceDialog.visible = false;
  await getList();
};

/** 删除商品 */
const handleDelete = async (row: any) => {
  await proxy?.$modal.confirm(`确认要删除商品"${row.itemName}"吗？`);
  await delSiteProduct(row.id);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 添加商品 */
const handleAddProduct = () => {
  addProductDialog.visible = true;
  addProductQuery.value = {
    pageNum: 1,
    pageSize: 10,
    isSelf: 1,
    productNo: undefined,
    itemName: undefined
  };
  selectedProducts.value = [];
  getProductList();
};

/** 获取可添加的商品列表 */
const getProductList = async () => {
  addProductDialog.loading = true;
  try {
    const res = await listBase(addProductQuery.value);
    addProductDialog.productList = res.rows || [];
    addProductDialog.total = res.total || 0;
  } catch (error) {
    console.error('获取商品列表失败:', error);
    addProductDialog.productList = [];
    addProductDialog.total = 0;
  } finally {
    addProductDialog.loading = false;
  }
};

/** 搜索商品 */
const handleSearchProducts = () => {
  addProductQuery.value.pageNum = 1;
  getProductList();
};

/** 选择变化 */
const handleSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection;
};

/** 批量加入清单 */
const handleBatchAdd = async () => {
  if (selectedProducts.value.length === 0) {
    proxy?.$modal.msgWarning('请先选择要添加的商品');
    return;
  }
  // 校验是否填写协议价
  const noPrice = (selectedProducts.value as any[]).filter((item: any) => !item.agreementPrice || Number(item.agreementPrice) <= 0);
  if (noPrice.length > 0) {
    proxy?.$modal.msgWarning(`有 ${noPrice.length} 个商品未填写协议价，请填写后再加入清单`);
    return;
  }
  try {
    await Promise.all(
      (selectedProducts.value as any[]).map((item: any) =>
        addSiteProduct({
          siteId: siteId.value,
          productId: item.id,
          productNo: item.productNo,
          agreementPrice: String(item.agreementPrice)
        })
      )
    );
    proxy?.$modal.msgSuccess(`成功添加 ${selectedProducts.value.length} 个商品`);
    addProductDialog.visible = false;
    selectedProducts.value = [];
    if (addProductTableRef.value) {
      addProductTableRef.value.clearSelection();
    }
    await getList();
  } catch (error) {
    console.error('添加商品失败:', error);
  }
};

/** 添加单个商品 */
const handleAddSingleProduct = async (row: any) => {
  if (!row.agreementPrice || Number(row.agreementPrice) <= 0) {
    proxy?.$modal.msgWarning('请先填写协议价');
    return;
  }
  try {
    await addSiteProduct({
      siteId: siteId.value,
      productId: row.id,
      productNo: row.productNo,
      agreementPrice: String(row.agreementPrice)
    });
    proxy?.$modal.msgSuccess('添加成功');
    await getList();
  } catch (error) {
    console.error('添加商品失败:', error);
  }
};

/** 下载导入模板 */
const handleDownloadTemplate = async () => {
  try {
    const res = await getSiteProductImportTemplate();
    const blob = new Blob([res as any], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    FileSaver.saveAs(blob, '站点商品导入模板.xlsx');
  } catch (error) {
    console.error('下载模板失败:', error);
  }
};

/** 导入文件选择 */
const handleImportFileChange = (file: any) => {
  importDialog.file = file.raw;
};

/** 确认导入 */
const handleConfirmImport = async () => {
  if (!importDialog.file) {
    proxy?.$modal.msgWarning('请先选择要导入的文件');
    return;
  }
  importDialog.loading = true;
  try {
    await importSiteProductData(importDialog.file);
    proxy?.$modal.msgSuccess('导入成功');
    importDialog.visible = false;
    importDialog.file = null;
    if (importUploadRef.value) importUploadRef.value.clearFiles();
    await getList();
  } catch (error) {
    console.error('导入失败:', error);
  } finally {
    importDialog.loading = false;
  }
};

/** 导入商品 */
const handleImportProduct = () => {
  importDialog.visible = true;
  importDialog.file = null;
  if (importUploadRef.value) importUploadRef.value.clearFiles();
};

/** 导出商品 */
const handleExportProduct = async () => {
  try {
    const res = await exportSiteProductData({ siteId: siteId.value });
    const blob = new Blob([res as any], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    FileSaver.saveAs(blob, `站点商品数据_${new Date().getTime()}.xlsx`);
  } catch (error) {
    console.error('导出失败:', error);
  }
};

onMounted(() => {
  initData();
  loadBrandOptions();
  loadCategoryOptions();
});
</script>

<style scoped lang="scss">
.add-product-dialog {
  :deep(.el-form--inline .el-form-item) {
    margin-right: 10px;
  }
}
</style>
