<template>
  <div class="form-container">
    <div>
      <!-- 进度条 -->
      <el-button class="back-btn" @click="handleBack"> 返回 </el-button>
      <div class="progress-container">
        <el-steps :active="currentStep" style="max-width: 1500px" align-center>
          <el-step v-for="(item, index) in entryList" :key="index">
            <template #title>
              <div class="step-title-wrapper">
                <span class="step-title">{{ item.title }}</span>
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>
    </div>
    <!-- 第一步：个人实名 -->
    <div v-if="currentStep === 1">
      <!-- 表单 -->
      <div class="form-content">
        <el-form :model="step1Form" :rules="step1Rules" ref="step1FormRef" label-width="120px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="step1Form.name" placeholder="请输入姓名" style="width: 400px" />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber">
            <el-input v-model="step1Form.idNumber" placeholder="请输入身份证号码" style="width: 400px" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 按钮 -->
      <div class="form-actions">
        <el-button type="primary" size="large" @click="handleNextStep"> 下一步 </el-button>
      </div>
    </div>
    <!-- 第二步：填写信息 -->
    <div v-if="currentStep === 2">
      <!-- 表单内容 -->
      <div class="form-content step2-form">
        <el-form :model="step2Form" :rules="step2Rules" ref="step2FormRef" label-width="125px">
          <div class="form-row">
            <!-- 左列 -->
            <div class="form-col">
              <el-form-item label="店铺名称" prop="storeName">
                <el-input v-model="step2Form.storeName" placeholder="请输入店铺名称" maxlength="30" />
              </el-form-item>

              <el-form-item label="容纳人数" prop="storeCapacity">
                <el-input-number v-model="step2Form.storeCapacity" :min="1" :max="9999" />
              </el-form-item>

              <el-form-item label="门店面积" prop="storeArea">
                <el-radio-group v-model="step2Form.storeArea">
                  <el-radio label="小于20平米" value="1"> 小于20平米 </el-radio>
                  <el-radio label="20-50平米" value="2"> 20-50平米 </el-radio>
                  <el-radio label="50-100平米" value="3"> 50-100平米 </el-radio>
                  <el-radio label="100-300平米" value="4"> 100-300平米 </el-radio>
                  <el-radio label="500-1000平米" value="5"> 500-1000平米 </el-radio>
                  <el-radio label="大于1000平米" value="6"> 大于1000平米 </el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="所在地区" prop="region">
                <el-cascader :props="areaProps" v-model="step2Form.region" style="width: 100%" />
              </el-form-item>

              <el-form-item label="详细地址" prop="storeDetailAddress">
                <el-input v-model="step2Form.storeDetailAddress" type="textarea" :rows="3" placeholder="请输入" maxlength="255" />
              </el-form-item>

              <el-form-item label="门店简介" prop="storeBlurb">
                <el-input v-model="step2Form.storeBlurb" type="textarea" :rows="3" placeholder="请输入" maxlength="300" />
              </el-form-item>

              <el-form-item label="经营板块" prop="businessSection">
                <el-radio-group v-model="step2Form.businessSection" @change="changeBusinessSector">
                  <el-radio
                    v-for="businessSection in businessSectionList"
                    :value="businessSection.value"
                    :key="businessSection.value"
                  >
                    {{ businessSection.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="经营种类" prop="businessTypes">
                <el-checkbox-group v-model="step2Form.businessTypes">
                  <el-checkbox
                    v-for="businessType in businessTypeList"
                    :key="businessType"
                    :label="businessType.label"
                    :value="businessType.value"
                  />
                </el-checkbox-group>
              </el-form-item>
            </div>

            <!-- 右列 -->
            <div class="form-col">
              <el-form-item label="门店营业状态" prop="businessType">
                <el-radio-group v-model="step2Form.businessType">
                  <el-radio label="正常营业"> 正常营业 </el-radio>
                  <el-radio label="暂停营业"> 暂停营业 </el-radio>
                  <el-radio label="筹建中"> 筹建中 </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="经度" prop="storePositionLongitude" v-show="latShow">
                <el-input disabled v-model="step2Form.storePositionLongitude" placeholder="请填写经度" clearable />
              </el-form-item>
              <el-form-item label="纬度" prop="storePositionLatitude" v-show="latShow">
                <el-input disabled v-model="step2Form.storePositionLatitude" placeholder="请填写纬度" clearable />
              </el-form-item>
              <el-form-item label="经纬度查询" prop="address">
                <el-select
                  v-model="step2Form.address"
                  filterable
                  placeholder="请输入地址进行查询"
                  remote
                  reserve-keyword
                  :remote-method="getLonAndLat"
                  @change="selectAddress"
                >
                  <el-option v-for="item in addressList" :key="item.id" :label="item.name" :value="item.location">
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">{{ item.district }}</span>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="营业执照" prop="businessLicenseAddress">
                <el-upload
                  v-model:file-list="step2Form.businessLicenseAddress"
                  :http-request="handleHttpUpload"
                  list-type="picture-card"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-success="handleUploadSuccess"
                  :on-preview="handlePictureCardPreview"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">({{ step2Form.businessLicenseAddress.length }}/1)</div>
                  </template>
                </el-upload>
              </el-form-item>

              <el-form-item label="合同图片" prop="contractImageList">
                <el-upload
                  v-model:file-list="step2Form.contractImageList"
                  :http-request="handleHttpUpload"
                  list-type="picture-card"
                  :limit="20"
                  :on-exceed="handleExceed"
                  :on-success="handleUploadSuccess"
                  :on-preview="handlePictureCardPreview"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">({{ step2Form.contractImageList.length }}/20)</div>
                  </template>
                </el-upload>
              </el-form-item>

              <el-form-item label="食品经营许可证" prop="foodLicenceImgList">
                <el-upload
                  v-model:file-list="step2Form.foodLicenceImgList"
                  :http-request="handleHttpUpload"
                  list-type="picture-card"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-success="handleUploadSuccess"
                  :on-preview="handlePictureCardPreview"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">({{ step2Form.foodLicenceImgList.length }}/1)</div>
                  </template>
                </el-upload>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>

      <!-- 按钮 -->
      <div class="form-actions">
        <el-button type="primary" size="large" @click="handleSubmit"> 提交 </el-button>
      </div>
    </div>
    <!-- 第三步: 等待审核-->
    <!-- <div v-if="currentStep === 3">
      <div class="button-container">
        <el-button type="danger" size="large" class="register-btn-red" @click="handleGoToEnter" v-if="storeApplicationStatus == 2">
          审核拒绝，重新入驻
        </el-button>
        <el-button type="primary" size="large" class="register-btn" @click="handleGoToEnter" v-if="storeApplicationStatus == 0"> 等待审核 </el-button>
      </div>
    </div> -->
  </div>

  <!-- 图片预览 -->
  <el-image-viewer
    v-if="imageViewerVisible"
    :url-list="imageViewerUrlList"
    :initial-index="imageViewerInitialIndex"
    @close="imageViewerVisible = false"
  />
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  UploadProps,
  UploadUserFile,
  UploadRequestOptions
} from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import { verifyIdInfo, applyStore, getMerchantByPhone } from "@/api/modules/homeEntry";
import { getBusinessSection, getBusinessSectionTypes, getInputPrompt, getDistrict, uploadImg } from "@/api/modules/newLoginApi";
import { localGet, localSet } from "@/utils/index";
import { useAuthStore } from "@/stores/modules/auth";

const authStore = useAuthStore();
const userInfo = localGet("geeker-user")?.userInfo || {};
const latShow = ref(false);

// 图片预览相关
const imageViewerVisible = ref(false);
const imageViewerUrlList = ref<string[]>([]);
const imageViewerInitialIndex = ref(0);
const entryList = ref([
  {
    title: "个人实名"
  },
  {
    title: "填写信息"
  },
  {
    title: "等待审核"
  },
  {
    title: "入驻成功"
  }
]);

const step2Rules: FormRules = {
  storeName: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
  storeCapacity: [{ required: true, message: "请输入容纳人数", trigger: "blur" }],
  storeArea: [{ required: true, message: "请选择门店面积", trigger: "change" }],
  storeBlurb: [{ required: true, message: "请输入门店简介", trigger: "change" }],
  storeIntro: [{ required: true, message: "请输入门店简介", trigger: "blur" }],
  businessSection: [{ required: true, message: "请选择经营板块", trigger: "change" }],
  businessTypes: [{ required: true, message: "请选择经营种类", trigger: "change" }],
  address: [{ required: true, message: "请输入经纬度", trigger: "blur" }],
  businessLicenseAddress: [{ required: true, message: "请上传营业执照", trigger: "change" }],
  contractImageList: [{ required: true, message: "请上传合同图片", trigger: "change" }],
  foodLicenceImgList: [{ required: true, message: "请上传食品经营许可证", trigger: "change" }]
};

//地址集合
const addressList = ref<any[]>([]);
//查询地址名称
const queryAddress = ref<string>("");

const props = defineProps({
  currentStep: {
    type: Number,
    value: 0
  },
  storeApplicationStatus: {
    type: Number,
    value: 0
  }
});
const emit = defineEmits(["update:currentStep", "update:get-user-info"]);

// 调用父组件的 getUserInfo 方法
const callGetUserInfo = () => {
  emit("update:get-user-info");
};

// 内部步骤状态，和父组件同步
const currentStep = ref<number>(props.currentStep || 0);
const storeApplicationStatus = ref<number>(props.storeApplicationStatus || 0);
console.log(storeApplicationStatus);
watch(
  () => props.currentStep,
  val => {
    if (typeof val === "number") currentStep.value = val;
  }
);
watch(
  () => props.storeApplicationStatus,
  val => {
    if (typeof val === "number") storeApplicationStatus.value = val;
  }
);

// 隐藏财务管理菜单的函数
const hideFinancialManagementMenu = () => {
  const hideMenus = (menuList: any[]) => {
    menuList.forEach(menu => {
      // 根据菜单名称判断是否需要隐藏财务管理
      if (menu.name && menu.name === "financialManagement") {
        menu.meta.isHide = true;
      }
      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        hideMenus(menu.children);
      }
    });
  };
  if (authStore.authMenuList && authStore.authMenuList.length > 0) {
    hideMenus(authStore.authMenuList);
  }
};

// 显示财务管理菜单的函数
const showFinancialManagementMenu = () => {
  const showMenus = (menuList: any[]) => {
    menuList.forEach(menu => {
      // 根据菜单名称判断是否需要显示财务管理
      if (menu.name && menu.name === "financialManagement") {
        menu.meta.isHide = false;
      }
      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        showMenus(menu.children);
      }
    });
  };
  if (authStore.authMenuList && authStore.authMenuList.length > 0) {
    showMenus(authStore.authMenuList);
  }
};

// 更新缓存中的 storeId
const updateStoreIdInCache = async () => {
  try {
    const geekerUser = localGet("geeker-user");
    if (!geekerUser || !geekerUser.userInfo || !geekerUser.userInfo.phone) {
      console.error("用户信息不存在");
      return;
    }
    const phone = geekerUser.userInfo.phone;
    const res: any = await getMerchantByPhone({ phone });
    if (res && res.code == 200 && res.data && res.data.storeId) {
      // 更新缓存中的 storeId
      geekerUser.userInfo.storeId = res.data.storeId;
      localSet("geeker-user", geekerUser);
      // 同时更新 createdId 缓存
      if (res.data.storeId) {
        localSet("createdId", res.data.storeId);
      }
    }
  } catch (error) {
    console.error("更新 storeId 缓存失败:", error);
  }
};

// 监听步骤和审核状态，如果是待审核或审核拒绝，则更新 storeId
watch([() => currentStep.value, () => storeApplicationStatus.value], ([step, status]) => {
  if (step === 3 && (status === 0 || status === 2)) {
    updateStoreIdInCache();
  }
  // 如果是审核拒绝状态，隐藏财务管理菜单
  if (status === 2) {
    hideFinancialManagementMenu();
  }
  // 如果是审核通过状态，显示财务管理菜单
  if (status === 1) {
    showFinancialManagementMenu();
  }
});

// 监听菜单列表变化，根据审核状态显示或隐藏财务管理菜单
watch(
  () => authStore.authMenuList.length,
  newLength => {
    if (newLength > 0) {
      // 如果审核状态是拒绝，隐藏财务管理菜单
      if (storeApplicationStatus.value === 2) {
        hideFinancialManagementMenu();
      }
      // 如果审核状态是通过，显示财务管理菜单
      if (storeApplicationStatus.value === 1) {
        showFinancialManagementMenu();
      }
    }
  }
);

onMounted(() => {
  getBusinessSectionList();
  getBusinessTypes(null);
  callGetUserInfo();
  // 如果当前已经是待审核或审核拒绝状态，则更新 storeId
  if (currentStep.value === 3 && (storeApplicationStatus.value === 0 || storeApplicationStatus.value === 2)) {
    updateStoreIdInCache();
  }
  // 根据审核状态显示或隐藏财务管理菜单
  if (storeApplicationStatus.value === 2) {
    hideFinancialManagementMenu();
  } else if (storeApplicationStatus.value === 1) {
    showFinancialManagementMenu();
  }
});

const changeRefuse = () => {
  currentStep.value = 2;
};

// 跳转到 go-enter 组件（首页）
const handleGoToEnter = () => {
  setStep(0);
};
const setStep = (val: number) => {
  currentStep.value = val;
  emit("update:currentStep", val);
};

// 第一步表单
const step1FormRef = ref<FormInstance>();
const step1Form = reactive({
  name: "",
  idNumber: ""
});

const step1Rules: FormRules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  idNumber: [
    { required: true, message: "请输入身份证号码", trigger: "blur" },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
      message: "请输入正确的身份证号码",
      trigger: "blur"
    }
  ]
};

// 第二步表单
const step2FormRef = ref<FormInstance>();
const step2Form = reactive({
  storeName: "", //门店名称
  storeCapacity: 1, //容纳人数
  storeArea: "1", //门店面积
  isChain: 0, //是否连锁
  storeDetailAddress: "", //详细地址
  region: [],
  administrativeRegionProvinceAdcode: "", //省
  administrativeRegionCityAdcode: "", //市
  administrativeRegionDistrictAdcode: "", //区
  storeAddress: "", //门店地址（完整地址）
  storeBlurb: "", //门店简介
  businessSection: "1", //经营板块
  businessSectionName: "KTV",
  businessTypes: [], //经营种类
  businessTypesList: [], //经营种类集合
  businessStatus: 0, //营业状态
  storeStatus: 1, //门店状态
  businessType: "正常营业", //门店营业状态（用于表单显示）
  storePositionLongitude: "", //经度
  storePositionLatitude: "", //纬度
  businessLicenseAddress: [] as UploadUserFile[], //营业执照地址
  contractImageList: [] as UploadUserFile[], //合同图片集合
  foodLicenceImgList: [] as UploadUserFile[], //食品经营许可证
  address: ""
});

// 返回按钮
const handleBack = () => {
  if (currentStep.value === 1) {
    setStep(0);
  } else if (currentStep.value === 2) {
    setStep(1);
  } else if (currentStep.value === 3) {
    setStep(2);
  }
};
// 地区选择
const areaProps: any = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level } = node;
    try {
      let param = { adCode: node.data.adCode ? node.data.adCode : "" };
      // 调用后台接口获取数据
      const response: any = await getDistrict(param as any);
      // 转换数据格式
      const nodes = (response?.data?.districts?.[0]?.districts || []).map((item: any) => ({
        value: item.adcode,
        adCode: item.adcode,
        label: item.name,
        leaf: level >= 2 // 假设最多三级，可以根据实际需求调整
      }));
      console.log(nodes);
      // 返回数据
      resolve(nodes);
    } catch (error) {
      resolve([]);
    }
  }
};
watch(
  () => step2Form.region,
  (newVal: any[]) => {
    if (newVal.length > 0) {
      step2Form.administrativeRegionProvinceAdcode = newVal[0];
      step2Form.administrativeRegionCityAdcode = newVal[1];
      step2Form.administrativeRegionDistrictAdcode = newVal[2];
    }
  }
);

//经营板块
const businessSectionList = ref<any[]>([]);
const getBusinessSectionList = async () => {
  let res: any = await getBusinessSection();
  let addData: any[] = [];
  (res?.data || []).forEach((element: any) => {
    addData.push({ value: element.dictId, label: element.dictDetail, parentId: element.parentId });
  });
  businessSectionList.value = addData;
  // 如果businessSection有默认值，自动设置对应的id和name
  if (step2Form.businessSection) {
    const selectedSection = addData.find((item: any) => item.value === step2Form.businessSection);
    if (selectedSection) {
      step2Form.businessSection = selectedSection.value;
      step2Form.businessSectionName = selectedSection.label;
    }
  }
};
const changeBusinessSector = async (val: any) => {
  // 根据选中的value从businessSectionList中查找对应的项
  const selectedSection = businessSectionList.value.find((item: any) => item.value === val);
  if (selectedSection) {
    step2Form.businessSection = selectedSection.value; // dictId
    step2Form.businessSectionName = selectedSection.label; // dictDetail
  } else {
    step2Form.businessSection = "";
    step2Form.businessSectionName = "";
  }
  // 清空之前选中的经营种类
  step2Form.businessTypesList = [];
  step2Form.businessTypes = [];
  getBusinessTypes(val);
};

//经营种类
const businessTypeList = ref<any[]>([]);
const getBusinessTypes = async (val: any) => {
  let res: any = await getBusinessSectionTypes({ parentId: val ? val : step2Form.businessSection });
  let addData1: any[] = [];
  (res?.data || []).forEach((element: any) => {
    addData1.push({ value: element.dictId, label: element.dictDetail });
  });
  businessTypeList.value = addData1;
};

// 经纬度查询
const getLonAndLat = async (keyword: string) => {
  if (keyword) {
    console.log("地址查询", keyword);
    let param = {
      addressName: keyword
    };
    let res: any = await getInputPrompt(param as any);
    if (res.code == "200") {
      addressList.value = res?.data?.tips || [];
      console.log("res", res);
    } else {
      ElMessage.error("新增失败！");
    }
  } else {
    addressList.value = [];
  }
};
const selectAddress = async (param: any) => {
  // 安全检查：确保 address 存在且是字符串类型
  if (!step2Form.address || typeof step2Form.address !== "string") {
    ElMessage.warning("地址格式不正确，请重新选择");
    return;
  }

  // 检查是否包含逗号（经纬度格式应该是 "经度,纬度"）
  if (!step2Form.address.includes(",")) {
    ElMessage.warning("地址格式不正确，缺少经纬度信息");
    return;
  }

  // 安全地分割地址字符串
  let locationList = step2Form.address.split(",");

  // 检查分割后的数组长度
  if (locationList.length < 2) {
    ElMessage.warning("地址格式不正确，无法获取经纬度");
    return;
  }

  // 查找对应的地址名称
  addressList.value.forEach((item: any) => {
    if (item.location == step2Form.address) {
      queryAddress.value = item.name;
    }
  });

  // 设置经纬度，并去除可能的空格
  step2Form.storePositionLongitude = locationList[0]?.trim() || "";
  step2Form.storePositionLatitude = locationList[1]?.trim() || "";

  // 验证经纬度是否为有效数字
  if (!step2Form.storePositionLongitude || !step2Form.storePositionLatitude) {
    ElMessage.warning("无法获取有效的经纬度信息");
    return;
  }

  latShow.value = true;
};
//文件上传
const handleHttpUpload = async (options: UploadRequestOptions) => {
  let formData = new FormData();
  formData.append("file", options.file);
  try {
    const res: any = await uploadImg(formData);
    // 上传成功，将URL保存到文件对象中
    const fileUrl = res?.data?.fileUrl || res?.data?.[0] || res?.fileUrl;
    if (fileUrl) {
      // 调用 onSuccess 回调，传入响应数据
      options.onSuccess({ fileUrl });
    } else {
      throw new Error("上传失败：未获取到文件URL");
    }
  } catch (error) {
    options.onError(error as any);
    ElMessage.error("文件上传失败，请重试");
  }
};

// 文件上传成功回调
const handleUploadSuccess = (response: any, uploadFile: UploadUserFile) => {
  // 将URL保存到文件对象中
  if (response?.fileUrl) {
    uploadFile.url = response.fileUrl;
  }
};

// 图片预览处理函数
const handlePictureCardPreview = (file: UploadUserFile) => {
  // 如果文件正在上传中，允许预览（使用本地预览）
  if (file.status === "uploading" && file.url) {
    imageViewerUrlList.value = [file.url];
    imageViewerInitialIndex.value = 0;
    imageViewerVisible.value = true;
    return;
  }
  // 获取当前上传组件的所有图片 URL 列表（只包含已上传成功的图片）
  let urlList: string[] = [];
  let currentFileList: UploadUserFile[] = [];

  // 根据文件对象判断是哪个上传组件的文件
  if (step2Form.businessLicenseAddress.some((f: UploadUserFile) => f.uid === file.uid)) {
    currentFileList = step2Form.businessLicenseAddress;
  } else if (step2Form.contractImageList.some((f: UploadUserFile) => f.uid === file.uid)) {
    currentFileList = step2Form.contractImageList;
  } else if (step2Form.foodLicenceImgList.some((f: UploadUserFile) => f.uid === file.uid)) {
    currentFileList = step2Form.foodLicenceImgList;
  }

  // 获取所有已上传成功的图片 URL
  urlList = currentFileList
    .filter((item: UploadUserFile) => item.status === "success" && (item.url || (item.response as any)?.fileUrl))
    .map((item: UploadUserFile) => item.url || (item.response as any)?.fileUrl);

  // 找到当前点击的图片索引
  const currentUrl = file.url || (file.response as any)?.fileUrl;
  const currentIndex = urlList.findIndex((url: string) => url === currentUrl);

  if (currentIndex < 0) {
    ElMessage.warning("图片尚未上传完成，无法预览");
    return;
  }

  imageViewerUrlList.value = urlList;
  imageViewerInitialIndex.value = currentIndex;
  imageViewerVisible.value = true;
};
// 下一步
const handleNextStep = async () => {
  if (!step1FormRef.value) return;

  await step1FormRef.value.validate(async valid => {
    if (valid) {
      const params = {
        name: step1Form.name,
        idCard: step1Form.idNumber,
        appType: 1
      };
      const res: any = await verifyIdInfo(params);
      if (res && res.code == 200) {
        ElMessage.success(res.msg);

        // 更新本地存储中的idCard
        try {
          const geekerUser = localGet("geeker-user");
          if (geekerUser && geekerUser.userInfo) {
            // 获取最新的用户信息
            const phone = geekerUser.userInfo.phone;
            if (phone) {
              const userRes: any = await getMerchantByPhone({ phone });
              if (userRes && userRes.code == 200 && userRes.data) {
                // 更新本地存储中的用户信息，特别是idCard
                geekerUser.userInfo.idCard = userRes.data.idCard || step1Form.idNumber;
                geekerUser.userInfo.name = userRes.data.name || step1Form.name;
                localSet("geeker-user", geekerUser);
              } else {
                // 如果获取失败，至少更新idCard字段
                geekerUser.userInfo.idCard = step1Form.idNumber;
                geekerUser.userInfo.name = step1Form.name;
                localSet("geeker-user", geekerUser);
              }
            } else {
              // 如果没有phone，直接更新idCard
              geekerUser.userInfo.idCard = step1Form.idNumber;
              geekerUser.userInfo.name = step1Form.name;
              localSet("geeker-user", geekerUser);
            }
          }
        } catch (error) {
          console.error("更新本地存储失败:", error);
        }

        setStep(2);
      }
    } else {
      ElMessage.error("请完善表单信息");
    }
  });
};

// 提取文件列表中的URL
const getFileUrls = (fileList: UploadUserFile[]): string[] => {
  return fileList
    .map((file: UploadUserFile) => {
      // 优先使用 url，如果没有则使用 response 中的 fileUrl
      const response = file.response as any;
      return file.url || response?.fileUrl || "";
    })
    .filter((url: string) => url); // 过滤掉空字符串
};

// 根据adcode获取地区详细信息
const getDistrictInfo = async (adcode: string) => {
  try {
    const response: any = await getDistrict({ adCode: adcode } as any);
    const district = response?.data?.districts?.[0];
    if (district) {
      return {
        citycode: district.citycode ? [district.citycode] : [],
        adcode: district.adcode,
        level: district.level,
        center: district.center,
        name: district.name,
        districts: []
      };
    }
  } catch (error) {
    console.error("获取地区信息失败:", error);
  }
  return null;
};

// 构建whereAddress数组
const buildWhereAddress = async (regionCodes: string[]) => {
  const whereAddress: any[] = [];
  if (regionCodes && regionCodes.length > 0) {
    for (const code of regionCodes) {
      const districtInfo = await getDistrictInfo(code);
      if (districtInfo) {
        whereAddress.push(districtInfo);
      }
    }
  }
  return whereAddress;
};

// 提交
const handleSubmit = async () => {
  if (!step2FormRef.value) return;

  await step2FormRef.value.validate(async valid => {
    if (valid) {
      // 提取上传图片的URL
      const businessLicenseUrls = getFileUrls(step2Form.businessLicenseAddress);
      const contractImageUrls = getFileUrls(step2Form.contractImageList);
      const foodLicenceUrls = getFileUrls(step2Form.foodLicenceImgList);

      // 构建whereAddress数组
      const whereAddress = await buildWhereAddress(step2Form.region);

      // 处理营业状态映射
      let storeStatus = 1; // 默认值
      if (step2Form.businessType === "正常营业") {
        storeStatus = 1;
      } else if (step2Form.businessType === "暂停营业") {
        storeStatus = 0;
      } else if (step2Form.businessType === "筹建中") {
        storeStatus = 2;
      }

      // 处理门店面积：转换为数字
      const storeAreaNum = typeof step2Form.storeArea === "string" ? parseInt(step2Form.storeArea) : step2Form.storeArea;

      // 构建地址对象
      const addressObj = {
        address: queryAddress.value || "",
        longitude: parseFloat(step2Form.storePositionLongitude) || 0,
        latitude: parseFloat(step2Form.storePositionLatitude) || 0
      };

      // 构建门店位置字符串
      const storePosition =
        step2Form.storePositionLongitude && step2Form.storePositionLatitude
          ? `${step2Form.storePositionLongitude},${step2Form.storePositionLatitude}`
          : "";

      // 构建完整地址（省市区+详细地址）
      let fullStoreAddress = "";
      if (whereAddress.length > 0) {
        const provinceName = whereAddress[0]?.name || "";
        const cityName = whereAddress[1]?.name || "";
        const districtName = whereAddress[2]?.name || "";
        fullStoreAddress = `${provinceName}${cityName}${districtName}`;
      }

      const params = {
        storeTel: userInfo.phone,
        storeName: step2Form.storeName,
        storeCapacity: step2Form.storeCapacity,
        storeArea: storeAreaNum,
        isChain: step2Form.isChain,
        storeDetailAddress: step2Form.storeDetailAddress,
        storeBlurb: step2Form.storeBlurb,
        businessSection: step2Form.businessSection,
        businessTypesList: step2Form.businessTypes.length > 0 ? step2Form.businessTypes : step2Form.businessTypesList,
        storeStatus: storeStatus,
        businessStatus: step2Form.businessStatus,
        address: addressObj,
        businessLicenseAddress: businessLicenseUrls,
        contractImageList: contractImageUrls,
        foodLicenceImgList: foodLicenceUrls,
        storeAddress: fullStoreAddress,
        whereAddress: whereAddress,
        updatedTime: null,
        queryAddress: queryAddress.value,
        storePosition: storePosition,
        storePositionLatitude: parseFloat(step2Form.storePositionLatitude) || 0,
        storePositionLongitude: parseFloat(step2Form.storePositionLongitude) || 0,
        businessSectionName: step2Form.businessSectionName,
        businessTypes: step2Form.businessTypes.length > 0 ? step2Form.businessTypes : step2Form.businessTypesList,
        foodLicenceUrl: foodLicenceUrls.length > 0 ? foodLicenceUrls[0] : "",
        userAccount: userInfo.id, // 需要从用户信息中获取
        administrativeRegionProvinceAdcode: step2Form.administrativeRegionProvinceAdcode,
        administrativeRegionCityAdcode: step2Form.administrativeRegionCityAdcode,
        administrativeRegionDistrictAdcode: step2Form.administrativeRegionDistrictAdcode,
        storeContact: step1Form.name,
        idCard: step1Form.idNumber
      };

      ElMessageBox.confirm("确认提交入驻申请吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            const res: any = await applyStore(params);
            if (res && res.code == 200) {
              // 重新提交后，状态应该变为等待审核（0）
              storeApplicationStatus.value = 0;
              ElMessage.success(res.msg);
              // 通知父组件重新获取用户信息，更新状态
              callGetUserInfo();
              // 跳转到 go-enter 组件（首页）
              setStep(0);
            } else {
              ElMessage.error(res.msg || "提交失败");
            }
          } catch (error) {
            ElMessage.error("提交失败，请重试");
          }
        })
        .catch(() => {
          // 取消提交
        });
    } else {
      ElMessage.error("请完善表单信息");
    }
  });
};

// 文件上传超出限制
const handleExceed = () => {
  ElMessage.warning("文件数量超出限制");
};
</script>

<style scoped lang="scss">
// 表单页面样式
.form-container {
  min-height: calc(100vh - 100px);
  padding: 30px;
  background: #ffffff;
  border-radius: 8px;
  .back-btn {
    margin-bottom: 30px;
    color: #606266;
    border-color: #dcdfe6;
  }
  .progress-container {
    margin-bottom: 40px;
    :deep(.el-step__head.is-process .el-step__icon) {
      color: #909399;
      border-color: #909399 !important; /* 设置圆圈边框为灰色 */
    }
    :deep(.el-steps) {
      .is-finish {
        .el-step__icon {
          color: #ffffff;
          background-color: #6c8ff8 !important; /* 设置已完成步骤的圆圈背景色 */
          border-color: #6c8ff8 !important; /* 设置已完成步骤的圆圈边框色 */
        }
      }
      .el-step__head {
        .el-step__icon {
          width: 30px;
          height: 30px;
          font-size: 16px;
          font-weight: 600;
        }
      }
      .el-step__title {
        .step-title-wrapper {
          display: flex;
          flex-direction: column;
          gap: 8px;
          align-items: center;
          .step-title {
            font-size: 16px;
            font-weight: 600;
            color: #6c8ff8;
          }
        }
      }
    }
  }
  .form-content {
    max-width: 800px;
    margin: 0 auto;
    &.step2-form {
      max-width: 100%;
      .form-row {
        display: flex;
        gap: 40px;
        .form-col {
          flex: 1;
        }
      }
    }
  }
  .form-actions {
    display: flex;
    gap: 20px;
    justify-content: center;
    padding-top: 30px;
    margin-top: 40px;
    border-top: 1px solid #e4e7ed;
    .el-button {
      width: 200px;
      height: 44px;
      font-size: 16px;
      font-weight: 500;
      color: #ffffff;
      background: #6c8ff8;
      border: none;
      border-radius: 4px;
      outline: none;
    }
  }
}
.button-container {
  display: flex;
  align-items: center;
  justify-content: center;
  .register-btn {
    width: 200px;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    background: #6c8ff8;
    border: 0;
    border-radius: 4px;
    outline: none;
  }
  .register-btn-red {
    width: 200px;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    border: 0;
    border-radius: 4px;
    outline: none;
  }
}
</style>
