<template>
  <div class="p-2">
    <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-row :gutter="20">
              <el-col :span="6">
                <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-row>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="success" :disabled="multiple" @click="handleBatchPush">批量推送</el-button>
              <el-button type="info" icon="Upload" @click="handleImport">导入</el-button>
              <el-button type="warning" icon="Download" @click="handleImportTemplate">下载模板</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table ref="productTableRef" v-loading="loading" border :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="图片" align="center" prop="productImage" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.productImage"
              :src="scope.row.productImage"
              :preview-src-list="[scope.row.productImage]"
              fit="cover"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column label="产品编号" align="center" prop="productNo" width="150" />
        <el-table-column label="产品名称" align="center" prop="itemName" width="200" show-overflow-tooltip />
        <el-table-column label="我方分类" align="center" prop="categoryName" width="120" show-overflow-tooltip />
        <el-table-column label="第三方分类" align="center" width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.standardCatalogName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" prop="brandName" width="120" />
        <el-table-column label="单位" align="center" prop="unitName" width="80" />
        <el-table-column label="市场价" align="center" prop="marketPrice" width="100" />
        <el-table-column label="官网价" align="center" prop="memberPrice" width="100" />
        <el-table-column label="最低售价" align="center" prop="minSellingPrice" width="100" />
        <el-table-column label="协议价" align="center" prop="externalPrice" width="100" />
        <el-table-column label="总库存" align="center" prop="totalInventory" width="100" />

        <el-table-column label="上架状态" align="center" prop="productStatus" width="100">
          <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="danger">已下架</el-tag>
            <el-tag v-else type="info">上架中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="推送状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.pushStatus == '1'" type="success">已推送</el-tag>
            <el-tag v-else type="danger">未推送</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >编辑</el-button>
            </el-tooltip>
            <el-tooltip content="编辑库存" placement="top">
              <el-button link type="success" icon="Edit" @click="handleEditInventory(scope.row)">库存</el-button>
            </el-tooltip>
            <el-tooltip content="上下架" placement="top">
              <el-button link type="primary" @click="handleToggleStatus(scope.row)">{{ scope.row.productStatus == '1' ? '下架' : '上架' }}</el-button>
            </el-tooltip>
            <el-tooltip content="推送" placement="top">
              <el-button link type="primary" :disabled="scope.row.productStatus != '1'" @click="handlePush(scope.row)">推送</el-button>
            </el-tooltip>
            <el-tooltip content="查看日志" placement="top">
              <el-button link type="primary" @click="handleViewLog(scope.row)">查看日志</el-button>
            </el-tooltip>
          </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-drawer v-model="logDrawer.visible" title="推送日志" size="1000px" append-to-body>
      <div v-loading="logDrawer.loading">
        <el-table v-if="logDrawer.data.length > 0" :data="logDrawer.data" border stripe>
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="推送状态" align="center" width="90">
            <template #default="scope">
              <el-tag v-if="scope.row.pushStatus == '0'" type="success">成功</el-tag>
              <el-tag v-else-if="scope.row.pushStatus == '1'" type="danger">失败</el-tag>
              <el-tag v-else type="info">-</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="失败原因" align="center" prop="reason" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.reason || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        </el-table>
        <el-empty v-else description="暂无日志数据" />
      </div>
    </el-drawer>

    <!-- 添加或修改对外部推送商品对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="productFormRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="第三方产品分类:" prop="externalCategoryId">
          <el-cascader
            v-model="form.externalCategoryId"
            :options="externalCategoryList"
            :props="cascaderProps"
            placeholder="请选择第三方产品分类"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="第三方平台售价:" prop="externalPrice">
          <el-input-number
            v-model="form.externalPrice"
            :precision="2"
            :min="0"
            :controls="false"
            placeholder="请输入第三方平台售价"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="总库存:" prop="totalInventory">
          <el-input-number
            v-model="form.totalInventory"
            :precision="0"
            :min="0"
            :controls="false"
            placeholder="请输入总库存"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="warning" @click="cancel">取 消</el-button>
          <el-button type="primary" :loading="buttonLoading" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importDialog.visible" :title="importDialog.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        drag
        :limit="1"
        :accept="importDialog.fileType"
        :before-upload="handleBeforeUpload"
        :on-exceed="handleExceed"
        :http-request="handleFileUpload"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅支持 {{ importDialog.fileType }} 格式文件</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="warning" @click="importDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="confirmImport">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 库存编辑对话框 -->
    <el-dialog v-model="inventoryDialog.visible" :title="inventoryDialog.title" width="500px" append-to-body>
      <el-form ref="inventoryFormRef" :model="inventoryForm" :rules="inventoryRules" label-width="100px">
        <el-form-item label="商品编号:">
          <el-input v-model="inventoryForm.productNo" disabled />
        </el-form-item>
        <el-form-item label="商品名称:">
          <el-input v-model="inventoryForm.itemName" disabled />
        </el-form-item>
        <el-form-item label="当前库存:" prop="currentInventory">
          <el-input-number
            v-model="inventoryForm.currentInventory"
            :precision="0"
            :min="0"
            :controls="true"
            placeholder="请输入当前库存"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="inventoryForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="warning" @click="inventoryDialog.visible = false">取 消</el-button>
          <el-button type="primary" :loading="inventoryLoading" @click="submitInventoryForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product" lang="ts">
import { getThirdProductPage, getProduct, updateProduct, shelfReview, batchPushProduct, importData, importTemplate } from '@/api/external/product';
import { ThirdProductVO, ProductQuery, ProductVO, ProductForm } from '@/api/external/product/types';
import { getProductCategoryTree } from '@/api/external/productCategory';
import { ProductCategoryVO } from '@/api/external/productCategory/types';
import { listPushPoolLog } from '@/api/external/pushPoolLog';
import { PushPoolLogVO } from '@/api/external/pushPoolLog/types';
import cache from '@/plugins/cache';
import { UploadFilled } from '@element-plus/icons-vue';
import type { UploadInstance, UploadRawFile } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productList = ref<ThirdProductVO[]>([]);
const buttonLoading = ref(false);
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 onShelfCount = ref(0);

const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();
const productTableRef = ref();
const uploadRef = ref<UploadInstance>();
const inventoryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 日志侧边栏数据
const logDrawer = reactive({
  visible: false,
  loading: false,
  data: [] as PushPoolLogVO[]
});

// 导入对话框数据
const importDialog = reactive({
  visible: false,
  title: '导入商品数据',
  fileType: '.xlsx, .xls',
  selectedFile: null as File | null
});

// 库存编辑对话框数据
const inventoryDialog = reactive({
  visible: false,
  title: '编辑库存'
});

// 编辑模式标识
const isEditMode = ref(false);

const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: {
    id: undefined,
    productId: undefined,
    itemId: undefined,
    categoryId: undefined,
    externalCategoryId: undefined,
    externalPrice: 0,
    pushStatus: 0,
    remark: undefined,
    totalInventory: 0
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productNo: undefined,
    itemName: undefined,
    itemId: undefined,
    params: {},
    externalPrice: 0
  },
  rules: {
    externalCategoryId: [{ required: true, message: '请选择第三方产品分类', trigger: 'change' }],
    externalPrice: [{ required: true, message: '请输入第三方价格', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 外部分类列表（懒加载模式只需要初始化为空数组）
const externalCategoryList = ref<ProductCategoryVO[]>([]);

// 级联选择器配置（使用分类树接口全量加载）
const cascaderProps = {
  value: 'id',
  label: 'label',  // 后端返回的是label字段，不是categoryName
  children: 'children',
  checkStrictly: true,
  emitPath: false
};

/** 初始化第三方分类数据 */
const initCategoryData = async () => {
  try {
    const itemId = queryParams.value.itemId;
    if (!itemId) {
      externalCategoryList.value = [];
      return;
    }
    const res = await getProductCategoryTree({ itemId });
    externalCategoryList.value = res.data || [];
  } catch (error) {
    console.error('加载分类树失败:', error);
    proxy?.$modal.msgError('加载分类数据失败');
  }
};


/** 查询第三方商品列表 */
const getList = async () => {
  loading.value = true;
  const params = {
    ...queryParams.value
  };
  const res = await getThirdProductPage(params);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 初始化项目ID（从缓存获取） */
const initProjectId = () => {
  const currentProject = cache.local.getJSON('currentProject');
  if (currentProject && currentProject.id) {
    queryParams.value.itemId = currentProject.id;
  }
}

const handleBatchPush = async () => {
  if (multiple.value) return;
  // 检查是否有已上架商品
  if (onShelfCount.value === 0) {
    proxy?.$modal.msgWarning('请选择已上架的商品进行推送');
    return;
  }
  try {
    await proxy?.$modal.confirm(`确认推送选中的 ${onShelfCount.value} 个已上架商品吗?`);
    // 只推送已上架商品的ID
    const selection = productTableRef.value?.getSelectionRows() || [];
    const onShelfIds = selection.filter((item: ThirdProductVO) => item.productStatus == '1').map((item: ThirdProductVO) => item.id);
    await batchPushProduct(onShelfIds);
    proxy?.$modal.msgSuccess('推送成功');
    productTableRef.value?.clearSelection?.();
    ids.value = [];
    multiple.value = true;
    single.value = true;
    onShelfCount.value = 0;
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量推送失败:', error);
      proxy?.$modal.msgError('推送失败');
    }
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    productId: undefined,
    itemId: undefined,
    categoryId: undefined,
    externalCategoryId: undefined,
    externalPrice: 0,
    pushStatus: 0,
    remark: undefined,
    totalInventory: 0
  };
  productFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ThirdProductVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // 统计已上架商品数量
  onShelfCount.value = selection.filter(item => item.productStatus == '1').length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  proxy?.$modal.msgWarning("暂不支持新增");
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ThirdProductVO) => {
  reset();
  isEditMode.value = true;
  dialog.title = '编辑对接信息';

  try {
    // 确保分类数据已加载
    if (externalCategoryList.value.length === 0) {
      await initCategoryData();
    }

    // 通过商品ID获取对接信息
    const res = await getProduct(row!.id);
    const productInfo = res.data;

    form.value = {
      id: productInfo.id,
      productId: productInfo.productId,
      itemId: productInfo.itemId,
      categoryId: productInfo.categoryId,
      externalCategoryId: productInfo.externalCategoryId,
      externalPrice: productInfo.externalPrice,
      pushStatus: productInfo.pushStatus,
      remark: productInfo.remark,
      totalInventory: productInfo.totalInventory || 0
    };

    dialog.visible = true;
  } catch (error) {
    console.error('获取对接信息失败:', error);
    proxy?.$modal.msgError('获取对接信息失败');
  }
}

/** 提交按钮 */
const submitForm = async () => {
  if (!productFormRef.value) return;

  await productFormRef.value.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (isEditMode.value) {
          // 编辑模式
          await updateProduct(form.value);
          proxy?.$modal.msgSuccess('编辑成功');
        } else {
          // 新增模式（如果需要）
          proxy?.$modal.msgWarning('暂不支持新增');
          return;
        }

        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('操作失败:', error);
        proxy?.$modal.msgError(isEditMode.value ? '编辑失败' : '新增失败');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ThirdProductVO) => {
  proxy?.$modal.msgWarning("暂不支持删除");
}

/** 上下架操作 */
const handleToggleStatus = async (row: ThirdProductVO) => {
  const action = row.productStatus == '1' ? '下架' : '上架';
  const newStatus = row.productStatus == '1' ? '0' : '1';

  try {
    await proxy?.$modal.confirm(`确认${action}该商品吗？`);

    // 调用上下架接口
    await shelfReview({
      id: row.id,
      productStatus: newStatus
    });

    proxy?.$modal.msgSuccess(`${action}成功`);

    // 刷新列表
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('上下架操作失败:', error);
      proxy?.$modal.msgError(`${action}失败`);
    }
  }
}

/** 推送操作 */
const handlePush = async (row: ThirdProductVO) => {
  // 检查是否已上架
  if (row.productStatus != '1') {
    proxy?.$modal.msgWarning('只有已上架的商品才能推送');
    return;
  }
  try {
    await proxy?.$modal.confirm('确认推送该商品吗?');

    // 调用批量推送接口,传入单个商品ID
    await batchPushProduct(row.id);

    proxy?.$modal.msgSuccess('推送成功');

    // 刷新列表
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('推送操作失败:', error);
      proxy?.$modal.msgError('推送失败');
    }
  }
}

/** 查看日志操作 */
const handleViewLog = async (row: ThirdProductVO) => {
  logDrawer.visible = true;
  logDrawer.loading = true;
  logDrawer.data = [];

  try {
    // 获取项目ID
    const itemId = queryParams.value.itemId;
    if (!itemId) {
      proxy?.$modal.msgWarning('请先选择项目');
      logDrawer.visible = false;
      return;
    }

    // 调用列表接口，传入项目id和商品池id
    const res = await listPushPoolLog({ itemId, productId: row.productId, pageNum: 1, pageSize: 100 });
    logDrawer.data = res.rows || [];
  } catch (error) {
    console.error('获取推送日志失败:', error);
    proxy?.$modal.msgError('获取推送日志失败');
  } finally {
    logDrawer.loading = false;
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('external/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
const handleImport = () => {
  importDialog.visible = true;
  importDialog.selectedFile = null;
  uploadRef.value?.clearFiles();
}

/** 下载导入模板 */
const handleImportTemplate = async () => {
  try {
    const response = await importTemplate();
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `对外部推送商品模板_${new Date().getTime()}.xlsx`;
    link.click();
    window.URL.revokeObjectURL(url);
    proxy?.$modal.msgSuccess('模板下载成功');
  } catch (error) {
    console.error('下载模板失败:', error);
    proxy?.$modal.msgError('下载模板失败');
  }
}

/** 文件上传前校验 */
const handleBeforeUpload = (file: UploadRawFile) => {
  const isExcel = file.type === 'application/vnd.ms-excel' ||
                  file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    proxy?.$modal.msgError('只能上传 Excel 文件格式!');
    return false;
  }
  importDialog.selectedFile = file;
  return false; // 阻止自动上传
}

/** 文件超出数量限制 */
const handleExceed = () => {
  proxy?.$modal.msgWarning('只能上传一个文件');
}

/** 自定义文件上传处理 */
const handleFileUpload = async () => {
  if (!importDialog.selectedFile) {
    proxy?.$modal.msgWarning('请选择要导入的文件');
    return;
  }

  try {
    const res = await importData(importDialog.selectedFile);
    proxy?.$modal.msgSuccess(res.msg || '导入成功');
    importDialog.visible = false;
    uploadRef.value?.clearFiles();
    importDialog.selectedFile = null;
    await getList();
  } catch (error) {
    console.error('导入失败:', error);
    proxy?.$modal.msgError('导入失败');
  }
}

/** 确认导入 */
const confirmImport = () => {
  if (!importDialog.selectedFile) {
    proxy?.$modal.msgWarning('请先选择要导入的文件');
    return;
  }
  handleFileUpload();
}

/** 编辑库存操作 */
const handleEditInventory = async (row: ThirdProductVO) => {
  // 重置表单
  inventoryForm.id = row.id;
  inventoryForm.productNo = row.productNo;
  inventoryForm.itemName = row.itemName;
  inventoryForm.currentInventory = row.availableStock || 0;
  inventoryForm.remark = undefined;

  inventoryDialog.title = '编辑库存';
  inventoryDialog.visible = true;
}

/** 提交库存表单 */
const submitInventoryForm = async () => {
  if (!inventoryFormRef.value) return;

  await inventoryFormRef.value.validate(async (valid) => {
    if (valid) {
      inventoryLoading.value = true;
      try {
        // 调用编辑接口，更新库存
        const updateData = {
          id: inventoryForm.id,
          totalInventory: inventoryForm.currentInventory,
          remark: inventoryForm.remark
        };

        await updateProduct(updateData);
        proxy?.$modal.msgSuccess('库存修改成功');
        inventoryDialog.visible = false;
        await getList();
      } catch (error) {
        console.error('修改库存失败:', error);
        proxy?.$modal.msgError('修改库存失败');
      } finally {
        inventoryLoading.value = false;
      }
    }
  });
}

// 库存编辑表单数据
interface InventoryForm {
  id?: string | number;
  productNo?: string;
  itemName?: string;
  currentInventory?: number;
  remark?: string;
}

const inventoryForm = reactive<InventoryForm>({
  id: undefined,
  productNo: undefined,
  itemName: undefined,
  currentInventory: 0,
  remark: undefined
});

const inventoryRules = reactive({
  currentInventory: [
    { required: true, message: '请输入当前库存', trigger: 'blur' }
  ]
});

// 库存编辑加载状态
const inventoryLoading = ref(false);

onMounted(() => {
  // 从缓存获取项目ID并初始化
  initProjectId();
  if (queryParams.value.itemId) {
    getList();
    initCategoryData();
  }
});
</script>
