<script setup lang="ts">
import { ref, 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
} from "@/api/erpGoods";
import { getProductList } from "@/api/product";

defineOptions({
  name: "ErpGoodsList"
});

const loading = ref(false);
const syncing = ref(false);
const keyword = ref("");
const dataList = ref<any[]>([]);
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.value || undefined);
    if (res.code === 200) {
      dataList.value = res.data || [];
      // 检查各 ERP 商品的关联状态
      await fetchBoundStatus();
    }
  } finally {
    loading.value = false;
  }
}

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 (e) {
    // 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 (e) {
    ElMessage.error("同步请求失败，请稍后重试");
  } finally {
    syncing.value = false;
  }
}

async function loadProductOptions() {
  try {
    const res = await getProductList({ page: 1, pageSize: 1000 });
    if (res.code === 200) {
      productOptions.value = res.data?.list || [];
    }
  } catch (e) {
    // 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 (e) {
    // 取消操作
  }
}

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

<template>
  <div class="main">
    <div class="px-6 pt-4 flex items-center justify-between">
      <h2 class="text-lg font-semibold">ERP 商品关联</h2>
      <div class="flex items-center gap-3">
        <el-input
          v-model="keyword"
          placeholder="搜索商品名称或编码"
          clearable
          class="w-[240px]!"
          @keyup.enter="fetchList"
        >
          <template #prefix>
            <el-icon><component :is="useRenderIcon(Search)" /></el-icon>
          </template>
        </el-input>
        <el-button @click="fetchList">搜索</el-button>
        <el-button
          type="primary"
          :icon="useRenderIcon(Refresh)"
          :loading="syncing"
          @click="handleSync"
        >
          从 ERP 同步
        </el-button>
      </div>
    </div>

    <div class="px-6 pt-4">
      <el-table
        v-loading="loading"
        :data="dataList"
        border
        stripe
        style="width: 100%"
        empty-text="暂无数据，请先同步ERP商品"
      >
        <el-table-column prop="erpGoodsId" label="ERP商品ID" width="150" />
        <el-table-column prop="goodsCode" label="商品编码" width="140" />
        <el-table-column prop="goodsName" label="商品名称" min-width="180" show-overflow-tooltip />
        <el-table-column label="图片" width="80">
          <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"
            />
            <span v-else class="text-gray-400 text-xs">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="specs" label="规格" width="120" show-overflow-tooltip />
        <el-table-column prop="skUnit" label="单位" width="80" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="salePrice" label="售价" width="100" />
        <el-table-column label="关联本地商品" min-width="160">
          <template #default="{ row }">
            <el-tag v-if="row._boundProduct" type="success" size="small">
              {{ row._boundProduct.name }}
            </el-tag>
            <span v-else class="text-gray-400">未关联</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <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>

    <!-- 关联对话框 -->
    <el-dialog
      v-model="bindDialogVisible"
      title="关联本地商品"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-form-item label="ERP 商品">
          <el-input
            :model-value="
              currentErpGoods?.goodsCode +
              ' - ' +
              currentErpGoods?.goodsName
            "
            disabled
          />
        </el-form-item>
        <el-form-item label="选择本地商品">
          <el-select
            v-model="selectedProductId"
            placeholder="请选择要关联的本地商品"
            clearable
            filterable
            class="w-full!"
          >
            <el-option
              v-for="p in productOptions"
              :key="p.id"
              :label="`[${p.code || '无编码'}] ${p.name}`"
              :value="p.id"
            />
          </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>
