<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "~icons/ep/refresh";
import Link from "~icons/ep/link";
import Remove from "~icons/ep/remove";
import Search from "~icons/ep/search";
import {
  syncErpGoods,
  getErpGoodsList,
  bindErpGoods,
  unbindErpGoods,
  autoBindErpGoods
} from "@/api/erpGoods";
import { getProductList } from "@/api/product";

defineOptions({
  name: "ErpGoodsList"
});

const loading = ref(false);
const syncing = ref(false);
const autoBinding = ref(false);

const form = reactive({
  keyword: ""
});

const dataList = ref<any[]>([]);
const total = ref(0);
const pagination = reactive({ currentPage: 1, pageSize: 10 });
const productOptions = ref<any[]>([]);
const bindDialogVisible = ref(false);
const currentErpGoods = ref<any>(null);
const selectedProductId = ref<number | null>(null);
const bindLoading = ref(false);

async function fetchList() {
  loading.value = true;
  try {
    const res = await getErpGoodsList({
      keyword: form.keyword || undefined,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    });
    if (res.code === 200) {
      dataList.value = res.data?.list || [];
      total.value = res.data?.total || 0;
      await fetchBoundStatus();
    }
  } finally {
    loading.value = false;
  }
}

function resetForm() {
  form.keyword = "";
  pagination.currentPage = 1;
  fetchList();
}

function handleSearch() {
  pagination.currentPage = 1;
  fetchList();
}

function handlePageChange(page: number) {
  pagination.currentPage = page;
  fetchList();
}

function handleSizeChange(size: number) {
  pagination.currentPage = 1;
  pagination.pageSize = size;
  fetchList();
}

async function fetchBoundStatus() {
  try {
    const res = await getProductList({ page: 1, pageSize: 1000 });
    if (res.code === 200) {
      const products = res.data?.list || [];
      dataList.value.forEach((erp: any) => {
        const bound = products.find((p: any) => p.erpGoodsId === erp.erpGoodsId);
        erp._boundProduct = bound || null;
      });
    }
  } catch {
    // ignore
  }
}

async function handleSync() {
  syncing.value = true;
  try {
    const res = await syncErpGoods();
    if (res.code === 200) {
      ElMessage.success(res.message || "同步任务已启动");
    } else {
      ElMessage.error(res.message || "同步失败");
    }
  } catch {
    ElMessage.error("同步请求失败，请稍后重试");
  } finally {
    syncing.value = false;
  }
}

async function handleAutoBind() {
  autoBinding.value = true;
  try {
    const res = await autoBindErpGoods();
    if (res.code === 200) {
      ElMessage.success(res.message || "自动关联完成");
      await fetchList();
    } else {
      ElMessage.error(res.message || "自动关联失败");
    }
  } catch {
    ElMessage.error("自动关联请求失败");
  } finally {
    autoBinding.value = false;
  }
}

async function loadProductOptions() {
  try {
    const res = await getProductList({ page: 1, pageSize: 1000 });
    if (res.code === 200) {
      productOptions.value = res.data?.list || [];
    }
  } catch {
    // ignore
  }
}

function openBindDialog(row: any) {
  currentErpGoods.value = row;
  selectedProductId.value = row._boundProduct?.id || null;
  bindDialogVisible.value = true;
  loadProductOptions();
}

async function handleBind() {
  if (!selectedProductId.value) {
    ElMessage.warning("请选择本地商品");
    return;
  }
  bindLoading.value = true;
  try {
    const res = await bindErpGoods(selectedProductId.value, currentErpGoods.value.erpGoodsId);
    if (res.code === 200) {
      ElMessage.success("关联成功");
      bindDialogVisible.value = false;
      await fetchList();
    } else {
      ElMessage.error(res.message || "关联失败");
    }
  } finally {
    bindLoading.value = false;
  }
}

async function handleUnbind(row: any) {
  if (!row._boundProduct) return;
  try {
    await ElMessageBox.confirm(
      `确认解除本地商品「${row._boundProduct.name}」与 ERP 商品「${row.goodsName}」的关联？`,
      "解除关联",
      { type: "warning" }
    );
    const res = await unbindErpGoods(row._boundProduct.id);
    if (res.code === 200) {
      ElMessage.success("解除关联成功");
      await fetchList();
    } else {
      ElMessage.error(res.message || "解除关联失败");
    }
  } catch {
    // 取消操作
  }
}

onMounted(() => {
  fetchList();
});
</script>

<template>
  <div class="main">
    <!-- 搜索表单区域 -->
    <el-form
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="商品名称：">
        <el-input
          v-model="form.keyword"
          placeholder="搜索商品名称或编码"
          clearable
          class="w-[240px]!"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 标题 + 操作按钮 + 表格 -->
    <div class="px-6 pt-4">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-semibold">ERP 商品关联</h2>
        <div class="flex items-center gap-2">
          <el-button
            type="primary"
            :icon="useRenderIcon(Refresh)"
            :loading="syncing"
            @click="handleSync"
          >
            从 ERP 同步
          </el-button>
          <el-button
            type="success"
            :loading="autoBinding"
            @click="handleAutoBind"
          >
            一键关联
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="dataList"
        border
        stripe
        style="width: 100%"
        empty-text="暂无数据，请先同步ERP商品"
        :row-style="{ height: '64px' }"
      >
        <el-table-column prop="erpGoodsId" label="ERP商品ID" width="150" align="center" />
        <el-table-column prop="goodsCode" label="商品编码" width="280" show-overflow-tooltip />
        <el-table-column prop="goodsName" label="商品名称" min-width="140" show-overflow-tooltip />
        <el-table-column label="图片" width="80" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.picPath"
              :src="row.picPath"
              :preview-src-list="[row.picPath]"
              fit="cover"
              preview-teleported
              style="width:48px;height:48px;border-radius:4px"
            />
            <div
              v-else
              style="width:48px;height:48px;border-radius:4px;background:#f3f4f6;display:flex;align-items:center;justify-content:center"
            >
              <span class="text-gray-400 text-xs">无</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="specs" label="规格名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="skUnit" label="单位" width="80" align="center" />
        <el-table-column prop="salePrice" label="售价" width="100" align="center" />
        <el-table-column label="关联本地商品" min-width="180">
          <template #default="{ row }">
            <el-popover
              v-if="row._boundProduct"
              trigger="hover"
              placement="right"
              :width="260"
            >
              <template #reference>
                <el-tag type="success" size="small" style="cursor:default">
                  {{ row._boundProduct.name }}
                </el-tag>
              </template>
              <div class="text-sm">
                <div class="font-medium text-base mb-3">{{ row._boundProduct.name }}</div>
                <div class="grid grid-cols-[70px_1fr] gap-y-2 gap-x-2 text-xs">
                  <span class="text-gray-400">商品编码</span>
                  <span>{{ row._boundProduct.code || '-' }}</span>
                  <span class="text-gray-400">条码</span>
                  <span>{{ row._boundProduct.barcode || '-' }}</span>
                  <span class="text-gray-400">零售价</span>
                  <span>¥{{ row._boundProduct.retailPrice || '-' }}</span>
                  <span class="text-gray-400">成本价</span>
                  <span>¥{{ row._boundProduct.costPrice || '-' }}</span>
                  <span class="text-gray-400">品类</span>
                  <span>{{ row._boundProduct.type || '-' }}</span>
                  <span class="text-gray-400">状态</span>
                  <span>{{ row._boundProduct.applyStatus || '-' }}</span>
                </div>
                <div v-if="row._boundProduct.pic" class="mt-3 bg-gray-100 rounded-md overflow-hidden">
                  <el-image
                    :src="row._boundProduct.pic"
                    fit="contain"
                    :preview-src-list="[row._boundProduct.pic]"
                    preview-teleported
                    style="width:100%;height:180px"
                  />
                </div>
              </div>
            </el-popover>
            <span v-else class="text-gray-400">未关联</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              v-if="!row._boundProduct"
              link
              type="primary"
              :icon="useRenderIcon(Link)"
              size="small"
              @click="openBindDialog(row)"
            >
              关联
            </el-button>
            <el-button
              v-else
              link
              type="danger"
              :icon="useRenderIcon(Remove)"
              size="small"
              @click="handleUnbind(row)"
            >
              解除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 关联对话框 -->
    <el-dialog
      v-model="bindDialogVisible"
      title="关联本地商品"
      width="680px"
      :close-on-click-modal="false"
    >
      <div class="flex items-center gap-4 mb-5 p-4 bg-gray-50 rounded-lg">
        <el-image
          v-if="currentErpGoods?.picPath"
          :src="currentErpGoods.picPath"
          :preview-src-list="[currentErpGoods.picPath]"
          fit="cover"
          preview-teleported
          style="width:72px;height:72px;border-radius:6px;flex-shrink:0"
        />
        <div
          v-else
          class="w-[72px] h-[72px] rounded-md flex items-center justify-center bg-gray-200 text-gray-400 text-xs flex-shrink-0"
        >
          无图
        </div>
        <div class="min-w-0">
          <div class="text-sm text-gray-500">{{ currentErpGoods?.goodsCode }}</div>
          <div class="text-base font-medium mt-1 truncate">{{ currentErpGoods?.goodsName }}</div>
          <div class="text-xs text-gray-400 mt-1">
            规格: {{ currentErpGoods?.specs || '-' }} &nbsp;|&nbsp; 售价: ¥{{ currentErpGoods?.salePrice || '-' }}
          </div>
        </div>
      </div>

      <el-form label-width="100px">
        <el-form-item label="选择本地商品">
          <el-select
            v-model="selectedProductId"
            placeholder="请搜索并选择要关联的本地商品"
            clearable
            filterable
            class="w-full!"
            popper-class="erp-bind-select-popper"
          >
            <el-option
              v-for="p in productOptions"
              :key="p.id"
              :label="`[${p.code || '无编码'}] ${p.name}`"
              :value="p.id"
            >
              <div class="flex items-center gap-3 py-0.5">
                <el-image
                  v-if="p.pic"
                  :src="p.pic"
                  fit="cover"
                  style="width:40px;height:40px;border-radius:4px;flex-shrink:0"
                />
                <div
                  v-else
                  class="w-[40px] h-[40px] rounded flex items-center justify-center bg-gray-100 text-gray-300 flex-shrink-0"
                >
                  <el-icon size="16"><component :is="useRenderIcon(Search)" /></el-icon>
                </div>
                <div class="min-w-0">
                  <div class="text-sm truncate">{{ p.name }}</div>
                  <div class="text-xs text-gray-400">{{ p.code || '无编码' }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="bindLoading" @click="handleBind">
          确认关联
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.erp-bind-select-popper {
  max-width: 600px !important;
}
</style>
