<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" label-width="80px">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="站点名称" prop="siteName">
                  <el-input v-model="queryParams.siteName" placeholder="请输入站点名称" clearable style="width: 100%" @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户名称" prop="clientId">
                  <el-select
                    v-model="queryParams.clientId"
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="searchQueryCustomer"
                    :loading="queryCustomerLoading"
                    placeholder="请选择客户"
                    clearable
                    style="width: 100%"
                    @focus="handleQueryCustomerFocus"
                  >
                    <el-option v-for="item in queryCustomerList" :key="item.id" :label="`${item.customerNo} ${item.customerName}`" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 100%">
                    <el-option label="启用" value="0" />
                    <el-option label="禁用" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发布时间" prop="startTimeRange">
                  <el-date-picker
                    v-model="queryParams.startTimeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="截止时间" prop="endTimeRange">
                  <el-date-picker
                    v-model="queryParams.endTimeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 表格区域 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-bold text-[#409EFF]">大客户专属站点信息列表</span>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </div>
      </template>

      <el-table v-loading="loading" border :data="siteList">
        <el-table-column label="客户编号" align="center" prop="clientNo" width="100" />
        <el-table-column label="客户名称" align="center" prop="clientName" min-width="100" />
        <el-table-column label="站点名称" align="center" prop="siteName" min-width="180" />
        <el-table-column label="站点域名" align="center" prop="siteDomain" min-width="220">
          <template #default="scope">
            <el-link type="primary" :href="scope.row.siteDomain" target="_blank">{{ scope.row.siteDomain }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'info'" size="small">
              {{ scope.row.status === '0' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <div class="flex flex-col items-center gap-1">
              <el-link type="primary" :underline="false" @click="handleSiteConfig(scope.row)">站点配置</el-link>
              <el-link type="primary" :underline="false" @click="handleProductConfig(scope.row)">商品配置</el-link>
              <el-link type="primary" :underline="false" @click="handleStyleDesign(scope.row)">样式设计</el-link>
              <el-link type="primary" :underline="false" @click="handleDiy(scope.row)">diy设计</el-link>
              <el-link :type="scope.row.status === '0' ? 'danger' : 'success'" :underline="false" @click="handleStatusChange(scope.row)">
                {{ scope.row.status === '0' ? '停 用' : '启 用' }}
              </el-link>
            </div>
          </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>
  </div>
</template>

<script setup name="VipSite" lang="ts">
import { listSite, getSite, delSite, addSite, updateSite } from '@/api/product/site';
import { SiteVO, SiteQuery } from '@/api/product/site/types';
import { getCustomerList, getCustomerInfo } from '@/api/customerOperation/customerList';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

const siteList = ref<SiteVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

// 搜索框客户下拉数据
const queryCustomerList = ref<any[]>([]);
const queryCustomerLoading = ref(false);

// 搜索框客户远程搜索
const searchQueryCustomer = async (query: string) => {
  queryCustomerLoading.value = true;
  try {
    const params: any = { pageSize: 20, pageNum: 1 };
    if (query) params.clientName = query;
    const res = await getCustomerList(params);
    queryCustomerList.value = res.rows || [];
  } catch (error) {
    queryCustomerList.value = [];
  } finally {
    queryCustomerLoading.value = false;
  }
};

// 搜索框客户聚焦时加载
const handleQueryCustomerFocus = () => {
  if (queryCustomerList.value.length === 0) {
    searchQueryCustomer('');
  }
};

// 查询参数
const queryParams = ref<SiteQuery & { startTimeRange?: string[]; endTimeRange?: string[] }>({
  pageNum: 1,
  pageSize: 10,
  siteName: undefined,
  clientId: undefined,
  status: undefined,
  startTimeRange: undefined,
  endTimeRange: undefined,
  params: {}
});

/** 通过客户接口回显列表中的客户编号和名称 */
const enrichListWithCustomerInfo = async () => {
  const uniqueClientIds = [...new Set(siteList.value.map((item) => item.clientId).filter(Boolean))];
  if (uniqueClientIds.length === 0) return;
  const customerMap = new Map<string, any>();
  await Promise.all(
    uniqueClientIds.map(async (clientId) => {
      try {
        const res = await getCustomerInfo(clientId as string | number);
        if (res.data) {
          customerMap.set(String(clientId), res.data);
        }
      } catch {}
    })
  );
  siteList.value = siteList.value.map((item) => {
    const customer = customerMap.get(String(item.clientId));
    if (customer) {
      return { ...item, clientNo: customer.customerNo || item.clientNo, clientName: customer.customerName || item.clientName };
    }
    return item;
  });
};

/** 查询客户站点配置列表 */
const getList = async () => {
  loading.value = true;
  try {
    // 处理日期范围参数
    const params: any = { ...queryParams.value };
    if (queryParams.value.startTimeRange && queryParams.value.startTimeRange.length === 2) {
      params.params = {
        ...params.params,
        beginStartTime: queryParams.value.startTimeRange[0],
        endStartTime: queryParams.value.startTimeRange[1]
      };
    }
    if (queryParams.value.endTimeRange && queryParams.value.endTimeRange.length === 2) {
      params.params = {
        ...params.params,
        beginEndTime: queryParams.value.endTimeRange[0],
        endEndTime: queryParams.value.endTimeRange[1]
      };
    }
    delete params.startTimeRange;
    delete params.endTimeRange;

    const res = await listSite(params);
    siteList.value = res.rows;
    total.value = res.total;
    await enrichListWithCustomerInfo();
  } catch (error) {
    console.error('获取站点列表失败:', error);
  } finally {
    loading.value = false;
  }
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    siteName: undefined,
    clientId: undefined,
    status: undefined,
    startTimeRange: undefined,
    endTimeRange: undefined,
    params: {}
  };
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push('/customerOperation/vipSite/siteConfig');
};

/** 站点配置 */
const handleSiteConfig = (row: SiteVO) => {
  router.push({
    path: '/customerOperation/vipSite/siteConfig',
    query: { id: row.id }
  });
};

/** 商品配置 */
const handleProductConfig = (row: SiteVO) => {
  router.push({
    path: '/customerOperation/vipSite/productConfig',
    query: { siteId: row.id, siteName: row.siteName, clientNo: row.clientNo, clientName: row.clientName }
  });
};

/** 样式设计 */
const handleStyleDesign = (row: SiteVO) => {
  router.push({
    path: '/customerOperation/vipSite/styleDesign',
    query: { siteId: row.id, siteName: row.siteName }
  });
};

const handleDiy = (row: any) => {
  router.push({
    path: '/customerOperation/pcList',
    query: { id: row.id, clientId: row.clientId }
  });
};

/** 状态切换 */
const handleStatusChange = async (row: SiteVO) => {
  const newStatus = row.status === '0' ? '1' : '0';
  const text = newStatus === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm(`确认要"${text}"站点"${row.siteName}"吗？`);
    await updateSite({ id: row.id, status: newStatus });
    proxy?.$modal.msgSuccess(`${text}成功`);
    await getList();
  } catch (error) {
    // 用户取消操作
  }
};

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