<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 {
  syncErpShops,
  getErpShopList,
  bindErpShop,
  unbindErpShop
} from "@/api/erpShop";
import { getEnabledShops } from "@/api/shop";

defineOptions({
  name: "ErpShopList"
});

const loading = ref(false);
const syncing = ref(false);
const dataList = ref<any[]>([]);
const shopOptions = ref<any[]>([]);
const bindDialogVisible = ref(false);
const currentErpShop = ref<any>(null);
const selectedShopId = ref<number | null>(null);
const bindLoading = ref(false);

async function fetchList() {
  loading.value = true;
  try {
    const res = await getErpShopList();
    if (res.code === 200) {
      dataList.value = res.data || [];
      // 检查各 ERP 店铺的绑定状态
      await fetchBoundStatus();
    }
  } finally {
    loading.value = false;
  }
}

async function fetchBoundStatus() {
  // 获取门店列表来展示绑定关系
  try {
    const res = await getEnabledShops();
    if (res.code === 200) {
      const shops = res.data || [];
      dataList.value.forEach((erp: any) => {
        const bound = shops.find((s: any) => s.erpShopId === erp.erpShopId);
        erp._boundShop = bound || null;
      });
    }
  } catch (e) {
    // ignore
  }
}

async function handleSync() {
  syncing.value = true;
  try {
    const res = await syncErpShops();
    if (res.code === 200) {
      ElMessage.success("同步成功");
      await fetchList();
    } else {
      ElMessage.error(res.message || "同步失败");
    }
  } finally {
    syncing.value = false;
  }
}

function openBindDialog(row: any) {
  currentErpShop.value = row;
  selectedShopId.value = row._boundShop?.id || null;
  bindDialogVisible.value = true;
  // 加载门店下拉选项
  getEnabledShops().then(res => {
    if (res.code === 200) {
      shopOptions.value = res.data || [];
    }
  });
}

async function handleBind() {
  if (!selectedShopId.value) {
    ElMessage.warning("请选择门店");
    return;
  }
  bindLoading.value = true;
  try {
    const res = await bindErpShop(selectedShopId.value, currentErpShop.value.erpShopId);
    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._boundShop) return;
  try {
    await ElMessageBox.confirm(
      `确认解除门店「${row._boundShop.name}」与 ERP 店铺「${row.shopName}」的绑定？`,
      "解除绑定",
      { type: "warning" }
    );
    const res = await unbindErpShop(row._boundShop.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>
      <el-button
        type="primary"
        :icon="useRenderIcon(Refresh)"
        :loading="syncing"
        @click="handleSync"
      >
        从 ERP 同步
      </el-button>
    </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="erpShopId" label="ERP店铺ID" width="160" />
        <el-table-column prop="shopName" label="店铺名称" min-width="180" />
        <el-table-column prop="shopCode" label="店铺编码" width="180" />
        <el-table-column prop="nickName" label="卖家账号" width="140" />
        <el-table-column prop="shopPlatformCode" label="平台编码" width="100" />
        <el-table-column prop="authorizationFlag" label="授权状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.authorizationFlag === '1' ? 'success' : 'info'" size="small">
              {{ row.authorizationFlag === '1' ? '已授权' : '未授权' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="绑定门店" min-width="160">
          <template #default="{ row }">
            <el-tag v-if="row._boundShop" type="success" size="small">
              {{ row._boundShop.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._boundShop"
              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="500px"
      :close-on-click-modal="false"
    >
      <el-form label-width="100px">
        <el-form-item label="ERP 店铺">
          <el-input
            :model-value="currentErpShop?.shopName + ' (' + currentErpShop?.erpShopId + ')'"
            disabled
          />
        </el-form-item>
        <el-form-item label="选择门店">
          <el-select
            v-model="selectedShopId"
            placeholder="请选择要绑定的门店"
            clearable
            filterable
            class="w-full!"
          >
            <el-option
              v-for="s in shopOptions"
              :key="s.id"
              :label="s.name"
              :value="s.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>
