<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">门店管理</span>
          </div>
          <div class="header-right">
            <el-input v-model="queryParams.storeOrContact" placeholder="搜索门店名称/联系人" class="search-input"
              prefix-icon="Search" clearable @keyup.enter="handleQuery" />
            <el-cascader v-model="searchRegionValue" :options="areaOptions" :props="{ value: 'id', label: 'name' }"
              placeholder="所属站点" class="station-select" style="width: 240px" clearable
              @change="handleSearchAreaChange" />
            <el-select v-model="queryParams.status" placeholder="状态" class="status-select" clearable
              @change="handleQuery">
              <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:store:add']">新增门店</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="storeList" style="width: 100%"
        :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
        <el-table-column label="门店信息" min-width="240">
          <template #default="scope">
            <div class="store-info-box">
              <image-preview :src="scope.row.logoUrl" :width="50" :height="50" class="store-logo" />
              <div class="store-desc">
                <div class="name">{{ scope.row.name }}</div>
                <div class="tags">
                  <el-tag size="small" type="warning" effect="plain" v-if="scope.row.tenantName">{{ scope.row.tenantName
                    }}</el-tag>
                  <el-tag size="small" type="success" effect="plain" v-if="scope.row.tenantCatergoriesName">{{
                    scope.row.tenantCatergoriesName }}</el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="服务项目" min-width="180">
          <template #default="scope">
            <div class="service-tags">
              <el-tag v-for="service in scope.row.services" :key="service" size="small" effect="light"
                class="service-tag">
                {{ getServiceName(service) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="资质认证" align="center" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.businessLicenseUrl" :width="40" :height="40" />
          </template>
        </el-table-column>

        <el-table-column label="归属区域/站点" min-width="150">
          <template #default="scope">
            <div class="region-info">
              <div class="region-name">{{ getRegionNameBySite(scope.row.site) }}</div>
              <div class="site-name">
                <el-icon>
                  <Location />
                </el-icon>
                <span>{{ scope.row.siteName }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="服务单" align="center" width="100" prop="serviceOrder" sortable />

        <el-table-column label="营业时间" align="center" width="140">
          <template #default="scope">
            <span class="time-text">{{ formatTime(scope.row.startBusinessTime) }},{{
              formatTime(scope.row.endBusinessTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="联系方式" min-width="160">
          <template #default="scope">
            <div class="contact-info">
              <div class="contact-item">
                <el-icon>
                  <User />
                </el-icon><span>{{ scope.row.contact }}</span>
              </div>
              <div class="contact-item phone">
                <el-icon>
                  <Phone />
                </el-icon><span>{{ scope.row.contactNumber }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="门店地址" prop="detailAddress" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            {{ getFullAddress(scope.row) }}
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <template v-for="item in statusList" :key="item.value">
              <el-tag v-if="scope.row.status === item.value" :type="item.style" size="small" effect="light">
                {{ item.label }}
              </el-tag>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="right" width="180" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-button link type="primary" @click="handleDetail(scope.row)"
                v-hasPermi="['system:store:query']">详情</el-button>
              <el-button link type="primary" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:store:edit']">编辑</el-button>
              <el-dropdown trigger="click" @command="(cmd) => handleCommand(cmd, scope.row)">
                <el-button link type="primary" class="more-btn">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleRenew" v-hasPermi="['system:store:renew']">续期</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.status === 1 && checkPermi(['system:store:disable'])"
                      command="handleBan" class="delete-item">禁用</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.status === 3 && checkPermi(['system:store:enable'])"
                      command="handleEnable">启用</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <pagination v-show="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <!-- 添加或修改门店管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="storeFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="门店Logo" prop="logo">
          <image-upload v-model="form.logo" :limit="1" />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <image-upload v-model="form.businessLicense" :limit="1" />
        </el-form-item>
        <el-form-item label="门店名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="服务项目" prop="services">
          <el-checkbox-group v-model="form.services">
            <el-checkbox v-for="service in serviceList" :key="service.id" :label="service.id" border>
              {{ service.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="商户分类" prop="tenantCatergories">
          <PageSelect v-model="form.tenantCatergories"
            :options="tenantCategoriesList.map(item => ({ value: item.id, label: item.name }))"
            :total="tenantCategoriesTotal" :pageSize="10" placeholder="请选择商户分类"
            @page-change="handleTenantCategoriesPageChange" @visible-change="handleTenantCategoriesVisibleChange" />
        </el-form-item>
        <el-form-item label="所属品牌" prop="tenantId">
          <PageSelect v-model="form.tenantId"
            :options="brandList.map(item => ({ value: item.tenantId, label: item.name }))" :total="brandTotal"
            :pageSize="10" placeholder="请选择所属品牌" @page-change="handleBrandPageChange"
            @visible-change="handleBrandSelectVisibleChange" />
        </el-form-item>
        <el-form-item label="营业时间" prop="startBusinessTime">
          <el-row :gutter="10">
            <el-col :span="10">
              <el-time-picker clearable v-model="form.startBusinessTime" format="HH:mm" value-format="HH:mm"
                placeholder="开始时间" style="width: 100%" />
            </el-col>
            <el-col :span="4" style="text-align: center; line-height: 32px">至</el-col>
            <el-col :span="10">
              <el-time-picker clearable v-model="form.endBusinessTime" format="HH:mm" value-format="HH:mm"
                placeholder="结束时间" style="width: 100%" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="合作有效期" prop="validity">
          <el-date-picker :disabled="!!form.id" clearable v-model="form.validity" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择合作有效期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="所属站点" prop="site">
          <el-cascader v-model="regionValue" :options="areaOptions" :props="{ value: 'id', label: 'name' }"
            placeholder="选择站点" style="width: 100%" @change="handleAreaChange" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-row :gutter="10" style="margin-bottom: 10px">
            <el-col :span="24">
              <RegionCascader v-model="addressCascaderValue" placeholder="选择省市区" />
            </el-col>
          </el-row>
          <el-input v-model="form.detailAddress" type="textarea" placeholder="输入详细地址" rows="3" style="width: 100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="getGeolocation" :loading="geoLoading">获取经纬度</el-button>
          <div v-if="geoErrorMsg" class="geo-error-tip">{{ geoErrorMsg }}</div>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请获取/输入位置经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请获取/输入位置纬度" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 门店详情对话框 -->
    <el-dialog :title="detailDialog.title" v-model="detailDialog.visible" width="800px" append-to-body>
      <el-tabs v-model="activeTab" style="padding: 0 10px;">
        <el-tab-pane label="基础信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="门店名称">{{ detailData.name }}</el-descriptions-item>
            <el-descriptions-item label="商户分类">{{ detailData.tenantCatergoriesName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="所属品牌">{{ detailData.tenantName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="营业时间">{{ formatTime(detailData.startBusinessTime) }} - {{
              formatTime(detailData.endBusinessTime) }}</el-descriptions-item>
            <el-descriptions-item label="合作有效期">{{ parseTime(detailData.validity, '{y}-{m}-{d}')
              }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ detailData.contact }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ detailData.contactNumber }}</el-descriptions-item>
            <el-descriptions-item label="归属站点">{{ detailData.siteName }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ getFullAddress(detailData) }}</el-descriptions-item>
            <el-descriptions-item label="营业执照">
              <image-preview v-if="detailData.businessLicenseUrl" :src="detailData.businessLicenseUrl" :width="80"
                :height="60" />
              <span v-else>-</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="服务订单记录" name="orders">
          <el-table :data="orderList" border style="width: 100%" v-loading="orderLoading">
            <el-table-column label="订单号" prop="code" min-width="150" />
            <el-table-column label="服务项目" min-width="120">
              <template #default="scope">
                {{ getServiceName(scope.row.service) }}
              </template>
            </el-table-column>
            <el-table-column label="客户" prop="customer" min-width="100" />
            <el-table-column label="金额" min-width="100">
              <template #default="scope">
                <span>¥{{ (scope.row.price / 100).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="下单时间" prop="createTime" min-width="160" />
            <el-table-column label="状态" align="center" width="100">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)" effect="plain" size="small">{{
                  getOrderStatusName(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="orderTotal > 0" :total="orderTotal" v-model:page="orderQueryParams.pageNum"
            v-model:limit="orderQueryParams.pageSize" @pagination="getOrderList" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 门店续期对话框 -->
    <el-dialog title="门店续期" v-model="renewDialog.visible" width="400px" append-to-body>
      <el-form :model="renewForm" label-width="80px">
        <el-form-item label="合作有效期">
          <el-date-picker v-model="renewForm.to" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renewDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitRenew" :loading="renewLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Store" lang="ts">
import { listStore, getStore, delStore, addStore, updateStore, listStoreStatus, renewStore, banStore, enableStore } from '@/api/system/store';
import { listSubOrderOnStore } from '@/api/order/subOrder/index';
import { StoreVO, StoreForm, StoreQuery, StoreStatusVO, SysStorePageBo } from '@/api/system/store/types';
import { listOnStore } from '@/api/system/tenant';
import { listOnStore as listTenantCategoriesOnStore } from '@/api/system/tenantCategories';
import { listAllService } from '@/api/service/list';
import { listAreaStation } from '@/api/system/areaStation';
import { getMapSetting } from '@/api/system/mapSetting';
import { AreaStationVO } from '@/api/system/areaStation/types';
import RegionCascader from '@/components/RegionCascader/index.vue';
import { useRegionData } from '@/hooks/useRegionData';
import PageSelect from '@/components/PageSelect/index.vue';
import { checkPermi } from '@/utils/permission';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { codeToName, loadRegionData } = useRegionData();

const storeList = ref<StoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const total = ref(0);

const storeFormRef = ref<ElFormInstance>();

const searchRegionValue = ref<any[]>([]); // 搜索的区域值
const searchSiteOptions = ref<any[]>([]); // 搜索的站点选项
const regionValue = ref<any[]>([]); // 所在区域/站点的路径值

const province = ref('');
const city = ref('');
const district = ref('');
const addressCascaderValue = ref<any[]>([]); // 省市区级联选择器值
const brandList = ref<any[]>([]); // 品牌列表
const brandLoading = ref(false); // 品牌加载状态
const currentPage = ref(1); // 当前页码
const brandKeyword = ref(''); // 搜索关键词
const brandSelectVisible = ref(false); // 品牌选择框可见状态
const brandTotal = ref(0); // 品牌总数
const serviceList = ref<any[]>([]); // 服务项目列表
const statusList = ref<StoreStatusVO[]>([]); // 状态列表
const tenantCategoriesList = ref<any[]>([]); // 商户分类列表
const tenantCategoriesTotal = ref(0); // 商户分类总数
const areaStationList = ref<AreaStationVO[]>([]); // 区域站点列表
const areaOptions = ref<any[]>([]); // 所在区域树形选项
const siteOptions = ref<any[]>([]); // 归属站点选项

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const detailDialog = reactive({
  visible: false,
  title: '门店详情'
});
const activeTab = ref('basic');
const detailData = ref<any>({});
const orderList = ref<any[]>([]);
const orderTotal = ref(0);
const orderLoading = ref(false);
const orderQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  storeId: undefined as any
});

const getOrderStatusName = (status: number) => {
  const map: any = { 0: '待派单', 1: '待接单', 2: '待服务', 3: '服务中', 4: '已完成', 5: '已取消' };
  return map[status] || '未知';
};

const getOrderStatusType = (status: number) => {
  const map: any = { 0: 'info', 1: 'warning', 2: 'primary', 3: 'success', 4: 'success', 5: 'danger' };
  return map[status] || 'info';
};

/** 查询订单记录 */
const getOrderList = async () => {
  orderLoading.value = true;
  try {
    const res: any = await listSubOrderOnStore(orderQueryParams);
    orderList.value = res.rows;
    orderTotal.value = res.total;
  } finally {
    orderLoading.value = false;
  }
};

/** 详情按钮操作 */
const handleDetail = async (row: StoreVO) => {
  const res = await getStore(row.id);
  detailData.value = { ...row, ...res.data };
  activeTab.value = 'basic';
  orderQueryParams.storeId = row.id;
  orderQueryParams.pageNum = 1;
  getOrderList();
  detailDialog.visible = true;
};

/** 续期对话框 */
const renewDialog = reactive({
  visible: false
});
const renewForm = reactive({
  id: undefined as string | number | undefined,
  to: ''
});
const renewLoading = ref(false);

/** 处理下拉菜单命令 */
const handleCommand = (command: string, row: StoreVO) => {
  switch (command) {
    case 'handleRenew':
      handleRenew(row);
      break;
    case 'handleBan':
      handleBan(row);
      break;
    case 'handleEnable':
      handleEnable(row);
      break;
    default:
      break;
  }
};

/** 续期按钮操作 */
const handleRenew = (row: StoreVO) => {
  renewForm.id = row.id;
  renewForm.to = '';
  renewDialog.visible = true;
};

/** 提交续期 */
const submitRenew = async () => {
  if (!renewForm.to) {
    proxy?.$modal.msgError("请选择有效期");
    return;
  }
  renewLoading.value = true;
  try {
    await renewStore({
      id: renewForm.id!,
      to: renewForm.to
    });
    proxy?.$modal.msgSuccess("续期成功");
    renewDialog.visible = false;
    getList();
  } finally {
    renewLoading.value = false;
  }
};

/** 禁用按钮操作 */
const handleBan = async (row: StoreVO) => {
  try {
    await proxy?.$modal.confirm('是否确认禁用门店？');
    loading.value = true;
    await banStore({ id: row.id });
    proxy?.$modal.msgSuccess("禁用成功");
    getList();
  } catch (err) {
  } finally {
    loading.value = false;
  }
};

/** 启用按钮操作 */
const handleEnable = async (row: StoreVO) => {
  try {
    await proxy?.$modal.confirm('是否确认启用门店？');
    loading.value = true;
    await enableStore({ id: row.id });
    proxy?.$modal.msgSuccess("启用成功");
    getList();
  } catch (err) {
  } finally {
    loading.value = false;
  }
};

const initFormData: StoreForm = {
  id: undefined,
  logo: undefined,
  businessLicense: undefined,
  name: undefined,
  tenantCatergories: undefined,
  startBusinessTime: undefined,
  endBusinessTime: undefined,
  contact: undefined,
  contactNumber: undefined,
  validity: undefined,
  site: undefined,
  detailAddress: undefined,
  status: undefined,
  longitude: undefined,
  latitude: undefined,
  tenantId: undefined,
  services: [],
  regionId: undefined,
  areaCode: undefined,
}
const data = reactive<PageData<StoreForm, SysStorePageBo>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeOrContact: undefined,
    area: undefined,
    station: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: "门店名称不能为空", trigger: "blur" }],
    detailAddress: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    tenantCatergories: [{ required: true, message: "商户分类不能为空", trigger: "change" }],
    startBusinessTime: [{ required: true, message: "开始营业时间不能为空", trigger: "blur" }],
    endBusinessTime: [{ required: true, message: "结束营业时间不能为空", trigger: "blur" }],
    contact: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
    contactNumber: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
    validity: [{ required: true, message: "合作有效期不能为空", trigger: "blur" }],
    tenantId: [{ required: true, message: "所属品牌不能为空", trigger: "change" }],
    regionId: [{ required: true, message: "所在区域不能为空", trigger: "change" }],
    site: [{ required: true, message: "归属站点不能为空", trigger: "change" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询门店管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStore(queryParams.value);
  storeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  regionValue.value = [];
  province.value = '';
  city.value = '';
  district.value = '';
  addressCascaderValue.value = [];
  tenantCategoriesList.value = [];
  tenantCategoriesTotal.value = 0;
  brandList.value = [];
  brandTotal.value = 0;
  storeFormRef.value?.resetFields();
}

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

/** 新增按钮操作 */
const handleAdd = () => {
  const hasStation = areaStationList.value.some(item => item.type === 2);
  if (!hasStation) {
    proxy?.$modal.msgWarning("请先配置站点");
    return;
  }
  reset();
  dialog.visible = true;
  dialog.title = "添加门店管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row: StoreVO) => {
  reset();
  const res = await getStore(row.id);
  Object.assign(form.value, res.data);

  // 确保 services 为字符串数组类型，避免由于类型不匹配导致 el-checkbox-group 无法匹配和选中
  if (form.value.services) {
    if (typeof form.value.services === 'string') {
      form.value.services = (form.value.services as string).split(',').filter(v => v !== '');
    }
    // 保持原始字符串类型，不使用 Number() 强制转换
  } else {
    form.value.services = [];
  }

  if (form.value.startBusinessTime) {
    form.value.startBusinessTime = formatTime(form.value.startBusinessTime);
  }
  if (form.value.endBusinessTime) {
    form.value.endBusinessTime = formatTime(form.value.endBusinessTime);
  }

  if (res.data.tenantCatergories && (res.data as any).tenantCatergoriesName) {
    tenantCategoriesList.value = [{
      id: res.data.tenantCatergories,
      name: (res.data as any).tenantCatergoriesName
    }];
    tenantCategoriesTotal.value = 1;
  }
  if (res.data.tenantId && (res.data as any).tenantName) {
    brandList.value = [{
      tenantId: res.data.tenantId,
      name: (res.data as any).tenantName
    }];
    brandTotal.value = 1;
  }

  if (res.data.areaCode) {
    if (Array.isArray(res.data.areaCode)) {
      addressCascaderValue.value = res.data.areaCode;
    } else if (typeof res.data.areaCode === 'string') {
      addressCascaderValue.value = res.data.areaCode.split(',');
    }
  }

  if (res.data.site) {
    const path: any[] = [];
    let currentId = res.data.site;
    while (currentId && String(currentId) !== '0') {
      path.unshift(currentId);
      const currentArea = areaStationList.value.find((item: any) => String(item.id) === String(currentId));
      if (currentArea) {
        currentId = currentArea.parentId;
      } else {
        break;
      }
    }
    regionValue.value = path;
    form.value.site = res.data.site;
    const siteNode = areaStationList.value.find(n => n.id === res.data.site);
    if (siteNode) {
      form.value.regionId = siteNode.parentId;
    }
  }

  dialog.visible = true;
  dialog.title = "修改门店管理";
}

const geoLoading = ref(false);
const geoErrorMsg = ref('');

/** 提交按钮 */
const submitForm = () => {
  storeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!form.value.areaCode) {
        proxy?.$modal.msgError("请选择省市区");
        return;
      }
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateStore(form.value);
        } else {
          await addStore(form.value);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}

/** 动态加载高德地图脚本 */
const loadAMapScript = async (): Promise<any> => {
  try {
    // 从接口获取配置
    const res = await getMapSetting(1);
    if (res.code !== 200) {
      return Promise.reject(res.msg);
    }
    const { apiKey, apiSecret } = res.data;

    if (!apiKey) {
      return Promise.reject('No Map Key Configured');
    }

    // 设置安全密钥
    (window as any)._AMapSecurityConfig = {
      securityJsCode: apiSecret,
    };

    return new Promise((resolve, reject) => {
      if ((window as any).AMap) {
        resolve((window as any).AMap);
        return;
      }
      const script = document.createElement('script');
      script.src = `https://webapi.amap.com/maps?v=2.0&key=${apiKey}`;
      script.onload = () => resolve((window as any).AMap);
      script.onerror = () => {
        reject(new Error('Script load failed'));
      };
      document.head.appendChild(script);
    });
  } catch (error) {
    console.error('Map config fetch error:', error);
    // 此处不重复弹窗，因为接口请求失败通常已有全局拦截器处理显示错误
    return Promise.reject(error);
  }
};

/** 根据详细地址使用高德地图 Geocoder 获取经纬度 */
const getGeolocation = async () => {
  // 拼接完整地址（省市区 + 详细地址）
  let areaText = '';
  if (addressCascaderValue.value && addressCascaderValue.value.length > 0) {
    areaText = addressCascaderValue.value.map((code: string) => codeToName(code)).join('');
  }
  const detailAddr = form.value.detailAddress || '';
  const fullAddress = (areaText + detailAddr).trim();

  if (!fullAddress) {
    proxy?.$modal.msgWarning('请先填写省市区和详细地址');
    return;
  }

  geoLoading.value = true;
  geoErrorMsg.value = '';
  try {
    // 确保高德地图脚本已加载
    await loadAMapScript();

    const AMap = (window as any).AMap;
    if (!AMap) {
      throw new Error('AMap is not defined');
    }

    const location: any = await new Promise((resolve, reject) => {
      AMap.plugin('AMap.Geocoder', () => {
        const geocoder = new AMap.Geocoder();
        geocoder.getLocation(fullAddress, (status: string, result: any) => {
          if (status === 'complete' && result.info === 'OK') {
            resolve(result.geocodes[0]?.location);
          } else {
            console.error('Geocoder fail:', status, result);
            reject(new Error(result.info || status || 'fail'));
          }
        });
      });
      // 增加 8s 超时
      setTimeout(() => reject(new Error('timeout')), 8000);
    });

    if (location) {
      form.value.longitude = location.lng.toFixed(6);
      form.value.latitude = location.lat.toFixed(6);
      proxy?.$modal.msgSuccess('获取经纬度成功');
    } else {
      throw new Error('no location');
    }
  } catch (err) {
    console.error('getGeolocation error:', err);
    geoErrorMsg.value = '经纬度获取失败，请联系管理员处理';
  } finally {
    geoLoading.value = false;
  }
};

/** 获取品牌列表 */
const getBrandList = async (pageNum = 1, keyword = '', append = false) => {
  brandLoading.value = true;
  const res = await listOnStore({ pageNum, pageSize: 10 });
  if (res.code === 200) {
    brandList.value = append ? [...brandList.value, ...res.rows] : res.rows;
    brandTotal.value = res.total || 0;
  }
  brandLoading.value = false;
};

/** 获取服务项目列表 */
const getServiceList = async () => {
  try {
    const res = await listAllService();
    serviceList.value = res.data || res;
  } catch (error) {
    console.error('获取服务项目列表失败:', error);
  }
};

/** 获取区域站点列表 */
const getAreaStationList = async () => {
  try {
    const res = await listAreaStation();
    const data = res.data || res;
    areaStationList.value = data;
    areaOptions.value = buildTree(data, 0);
  } catch (error) {
    console.error('获取区域站点列表失败:', error);
  }
};

/** 构建树形结构 */
const buildTree = (data: any[], parentId: any): any[] => {
  return data
    .filter(item => String(item.parentId) === String(parentId))
    .map(item => {
      const children = buildTree(data, item.id);
      const res: any = {
        id: item.id,
        name: item.name,
        // 如果不是站点且没有下级了，则不可选（防止误选区域叶子点）
        disabled: Number(item.type) !== 2 && (!children || children.length === 0)
      };
      if (children && children.length > 0) {
        res.children = children;
      }
      return res;
    });
};

/** 处理搜索区域选择变化 */
const handleSearchAreaChange = (value: any[]) => {
  if (value && value.length > 0) {
    const lastId = value[value.length - 1];
    queryParams.value.station = lastId;
    const node = areaStationList.value.find(item => item.id === lastId);
    if (node) {
      queryParams.value.area = node.parentId;
    }
  } else {
    queryParams.value.station = undefined;
    queryParams.value.area = undefined;
  }
  handleQuery();
};

/** 处理对话框中的所在区域选择变化 */
const handleAreaChange = (value: any[]) => {
  if (value && value.length > 0) {
    const lastId = value[value.length - 1];
    form.value.site = lastId;
    const node = areaStationList.value.find(item => item.id === lastId);
    if (node) {
      form.value.regionId = node.parentId;
    }
  } else {
    form.value.site = undefined;
    form.value.regionId = undefined;
  }
};

/** 获取商户分类列表 */
const getTenantCategoriesList = async (pageNum = 1) => {
  try {
    const res = await listTenantCategoriesOnStore({ pageNum, pageSize: 10 });
    if (res.code === 200) {
      tenantCategoriesList.value = res.rows;
      tenantCategoriesTotal.value = res.total || 0;
    }
  } catch (error) {
    console.error('获取商户分类列表失败:', error);
  }
};

const handleBrandPageChange = (page: number) => { getBrandList(Number(page), brandKeyword.value, false); };
const handleTenantCategoriesPageChange = (page: number) => { getTenantCategoriesList(Number(page)); };
const handleTenantCategoriesVisibleChange = (visible: boolean) => { if (visible) getTenantCategoriesList(1); };
const handleBrandSelectVisibleChange = (visible: boolean) => {
  brandSelectVisible.value = visible;
  if (visible) {
    currentPage.value = 1;
    getBrandList(1, brandKeyword.value, false);
  }
};

watch(addressCascaderValue, (newValue) => {
  form.value.areaCode = newValue && newValue.length > 0 ? newValue.join(',') : undefined;
}, { deep: true });

const getServiceName = (serviceId: number): string => {
  const service = serviceList.value.find(item => item.id === serviceId);
  return service ? service.name : '未知服务';
};

const getStatusList = async () => {
  try {
    const res: any = await listStoreStatus();
    statusList.value = res.data || res.rows || res;
  } catch (error) {
    console.error('获取状态列表失败:', error);
  }
};

const formatTime = (time: string | number): string => {
  if (!time) return '';
  if (typeof time === 'string' && /^\d{2}:\d{2}$/.test(time)) return time;
  if (typeof time === 'string' && /^\d{2}:\d{2}:\d{2}$/.test(time)) return time.substring(0, 5);
  let date = (typeof time === 'string' && !time.includes('-') && !time.includes('T')) ? null : new Date(time);
  if (!date || isNaN(date.getTime())) return String(time);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

const getFullAddress = (row: any): string => {
  let areaText = '';
  if (row.areaCode) {
    const codes = typeof row.areaCode === 'string' ? row.areaCode.split(',') : row.areaCode;
    areaText = codes.map((code: string) => codeToName(code)).join('');
  }
  return areaText ? `${areaText} ${row.detailAddress || ''}` : (row.detailAddress || '');
};

/** 根据站点ID获取区域全称（向上遍历树形关系） */
const getRegionNameBySite = (siteId: string | number): string => {
  if (!siteId || areaStationList.value.length === 0) return '正在加载...';

  const site = areaStationList.value.find(item => String(item.id) === String(siteId));
  if (!site) return '未知区域';

  let parentNames: string[] = [];
  let currentParentId = site.parentId;

  // 向上遍历直到父级ID为0或没找到父级
  while (currentParentId && String(currentParentId) !== '0') {
    const parent = areaStationList.value.find(item => String(item.id) === String(currentParentId));
    if (parent) {
      parentNames.unshift(parent.name);
      currentParentId = parent.parentId;
    } else {
      break;
    }
  }

  return parentNames.length > 0 ? parentNames.join('/') : '顶级区域';
};

onMounted(() => {
  getList();
  getBrandList();
  getServiceList();
  getAreaStationList();
  getStatusList();
  // 提前加载高德地图脚本，加快首次地理编码速度
  loadAMapScript().catch(() => {
    console.warn('高德地图预加载失败，将在首次使用时重试');
  });

  loadRegionData();
});
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background-color: #f5f7f9;
  min-height: 100%;
}

.table-card {
  border: none;
  border-radius: 8px;

  :deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}

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

.header-left {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.header-right {
  display: flex;
  gap: 12px;

  .search-input {
    width: 200px;
  }

  .station-select {
    width: 420px;
    flex-shrink: 0;
  }

  .status-select {
    width: 140px;
  }

  :deep(.el-input__wrapper) {
    background-color: #f4f5f7;
    box-shadow: none;
    border: 1px solid transparent;

    &:hover,
    &.is-focus {
      border-color: #409eff;
      background-color: #fff;
    }
  }
}

.store-info-box {
  display: flex;
  align-items: center;
  gap: 12px;

  .store-desc {
    .name {
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .tags {
      display: flex;
      gap: 4px;
    }
  }
}

.service-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.region-info {
  .region-name {
    font-weight: 500;
    color: #333;
  }

  .site-name {
    font-size: 12px;
    color: #909399;
    display: flex;
    align-items: center;
    gap: 4px;
    margin-top: 2px;
  }
}

.contact-info {
  .contact-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: #606266;

    &.phone {
      color: #409eff;
      margin-top: 2px;
    }

    .el-icon {
      font-size: 14px;
    }
  }
}

.time-text,
.count-text {
  font-weight: 500;
  color: #606266;
}

.status-tag {
  border: none;
  font-weight: 500;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.geo-error-tip {
  color: #f56c6c;
  font-size: 13px;
  margin-top: 8px;
  width: 100%;
  text-align: center;
}

.delete-item {
  color: #f56c6c !important;

  &:hover {
    color: #f56c6c !important;
    background-color: #fef0f0 !important;
  }
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  --el-table-border-color: #f0f0f0;

  th.el-table__cell {
    font-weight: 600;
  }

  td.el-table__cell {
    padding: 12px 0;
  }
}
</style>
