<!-- ERP 测试页面 -->
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { testErpConnection, erpHealth, getCustomerList, getSalesAreas, getBrands, type CustomerVO } from '@/api/erp';
import { ElMessage } from 'element-plus';

// 连接测试
const connectionStatus = ref<string>('');
const connectionData = ref<any>(null);
const healthStatus = ref<string>('');
const loading = ref(false);

async function checkConnection() {
  loading.value = true;
  try {
    const res = await testErpConnection();
    connectionStatus.value = res.status;
    connectionData.value = res.data;
    if (res.status === 'connected') {
      ElMessage.success('SQL Server 连接成功');
    } else {
      ElMessage.error(`连接失败: ${res.data?.error}`);
    }
  } catch (error: any) {
    connectionStatus.value = 'error';
    connectionData.value = { error: error?.message || '未知错误' };
    ElMessage.error('请求失败');
  } finally {
    loading.value = false;
  }
}

async function checkHealth() {
  try {
    const res = await erpHealth();
    healthStatus.value = res.msg || '正常';
    ElMessage.success('ERP 服务运行正常');
  } catch (error: any) {
    healthStatus.value = `异常: ${error?.message || '服务不可用'}`;
    ElMessage.error('ERP 服务不可用');
  }
}

// 客户档案
const customerList = ref<CustomerVO[]>([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const keyword = ref('');
const customerLoading = ref(false);
const salesAreas = ref<CustomerVO[]>([]);
const selectedSalesArea = ref('');
const brands = ref<CustomerVO[]>([]);
const selectedBrand = ref('');

async function loadCustomerList() {
  customerLoading.value = true;
  try {
    const res = await getCustomerList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      keyword: keyword.value || undefined,
      salesAreaCode: selectedSalesArea.value || undefined,
      brand: selectedBrand.value || undefined,
    });
    customerList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error: any) {
    ElMessage.error(error?.message || '加载客户列表失败');
  } finally {
    customerLoading.value = false;
  }
}

async function loadSalesAreas() {
  try {
    const res = await getSalesAreas();
    salesAreas.value = res || [];
  } catch {
    // ignore
  }
}

async function loadBrands() {
  try {
    const res = await getBrands();
    brands.value = res || [];
  } catch {
    // ignore
  }
}

function handleSearch() {
  pageNum.value = 1;
  loadCustomerList();
}

function handlePageChange(page: number) {
  pageNum.value = page;
  loadCustomerList();
}

onMounted(() => {
  loadCustomerList();
  loadSalesAreas();
  loadBrands();
});
</script>

<template>
  <div class="erp-test-page">
    <h2>ERP 服务</h2>

    <!-- 连接测试 -->
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>SQL Server 连接测试</span>
          <el-button type="primary" :loading="loading" @click="checkConnection">
            测试连接
          </el-button>
        </div>
      </template>
      <div v-if="connectionStatus" class="result">
        <el-alert
          :title="connectionStatus === 'connected' ? '连接成功' : '连接失败'"
          :type="connectionStatus === 'connected' ? 'success' : 'error'"
          :closable="false"
          show-icon
        />
        <pre v-if="connectionData" class="result-data">{{ JSON.stringify(connectionData, null, 2) }}</pre>
      </div>
    </el-card>

    <!-- 健康检查 -->
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>ERP 服务健康检查</span>
          <el-button type="success" @click="checkHealth">
            检查健康
          </el-button>
        </div>
      </template>
      <div v-if="healthStatus" class="result">
        <p>{{ healthStatus }}</p>
      </div>
    </el-card>

    <!-- 客户档案 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户档案（SCLTGENERAL）</span>
          <el-button type="primary" @click="loadCustomerList">
            刷新
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="keyword"
          placeholder="搜索客户编号/名称/联系人/销区/业务员"
          clearable
          style="width: 280px"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        />
        <el-select
          v-model="selectedSalesArea"
          placeholder="选择销区"
          clearable
          style="width: 140px"
          @change="handleSearch"
        >
          <el-option
            v-for="area in salesAreas"
            :key="area.salesAreaCode"
            :label="area.salesAreaName"
            :value="area.salesAreaCode"
          />
        </el-select>
        <el-select
          v-model="selectedBrand"
          placeholder="选择品牌"
          clearable
          filterable
          style="width: 150px"
          @change="handleSearch"
        >
          <el-option
            v-for="item in brands"
            :key="item.brand"
            :label="item.brandName"
            :value="item.brand"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <span class="total-info" v-if="total > 0">共 {{ total }} 条</span>
      </div>

      <!-- 客户列表表格 -->
      <el-table
        v-loading="customerLoading"
        :data="customerList"
        border
        stripe
        style="width: 100%; margin-top: 12px"
      >
        <el-table-column prop="customerCode" label="客户编号" width="120" fixed />
        <el-table-column prop="customerName" label="客户名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="brandName" label="品牌" width="100" />
        <el-table-column prop="salesAreaName" label="销区" width="100" />
        <el-table-column prop="sdOrgName" label="经销组织" min-width="150" show-overflow-tooltip />
        <el-table-column prop="saleDocName" label="销售负责人" width="100" />
        <el-table-column prop="pricePlanName" label="价格方案" min-width="120" show-overflow-tooltip />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="province" label="省份" width="80" />
        <el-table-column prop="city" label="城市" width="100" />
      </el-table>

      <el-pagination
        v-if="total > 0"
        v-model:current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        style="margin-top: 16px; justify-content: flex-end"
        @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.erp-test-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .test-card {
    margin-bottom: 16px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .result {
      padding: 12px 0;

      .result-data {
        margin-top: 12px;
        padding: 12px;
        background: #f5f7fa;
        border-radius: 4px;
        font-size: 13px;
        line-height: 1.6;
        color: #606266;
        white-space: pre-wrap;
        word-break: break-all;
      }
    }
  }

  .search-bar {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;

    .total-info {
      color: #909399;
      font-size: 14px;
    }
  }
}
</style>
