<template>
  <div class="p-2">
    <el-card shadow="always">
      <el-button type="primary" plain size="large" @click="close()">返回</el-button>
      <span style="margin-left: 20px">{{ isView ? '查看门店' : form.id ? '编辑门店' : '门店管理' }}</span>
    </el-card>
    <el-card shadow="always">
      <div width="1024px" :style="divStyle" style="overflow-y: auto; max-height: 80vh">
        <el-form ref="sysShopFormRef" :model="form" :rules="rules" label-width="110px" class="shop-form">
          <el-form-item label="门店logo：" prop="storeLogo">
            <div class="slideshow-container">
              <!-- 上传按钮区域 -->
              <div class="upload-buttons" v-if="!isView">
                <el-button
                  type="default"
                  @click="showLogoSelector = true"
                  :disabled="form.storeLogoFiles && form.storeLogoFiles.length >= 1"
                >
                  <el-icon><Picture /></el-icon>
                  选择图片
                </el-button>
              </div>

              <!-- 已选择的图片展示区域 -->
              <div class="selected-images-grid" v-if="form.storeLogoFiles && form.storeLogoFiles.length > 0">
                <div
                  v-for="(file, index) in form.storeLogoFiles"
                  :key="file.id || index"
                  class="image-item"
                >
                  <el-image
                    :src="getFileUrl(file)"
                    fit="cover"
                    class="slideshow-image"
                    :preview-disabled="false"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon size="20" color="#c0c4cc">
                          <Picture />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                  <!-- 删除按钮 -->
                  <div class="delete-btn" v-if="!isView" @click="removeLogoFile(index)">
                    <el-icon size="12" color="#fff">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>

              <!-- 提示信息 -->
              <div class="slideshow-tip">门店logo,建议大小200X200</div>
            </div>

            <!-- FileSelector 组件 -->
            <FileSelector
              v-model="showLogoSelector"
              :allowed-types="[1]"
              :multiple="false"
              :allow-upload="true"
              title="选择门店logo"
              @confirm="handleLogoSelected"
            />
          </el-form-item>

          <el-form-item label="店铺名称" prop="storeName">
            <el-input v-model="form.storeName" placeholder="请输入店铺名称" />
          </el-form-item>

          <el-form-item label="所属用户" prop="vestInUserId">
            <el-select
              v-model="form.vestInUserId"
              placeholder="请选择所属用户"
              :disabled="isView"
              filterable
              clearable
              @focus="loadShopManagerList"
              style="width: 100%"
            >
              <el-option
                v-for="manager in shopManagerList"
                :key="manager.userId"
                :label="manager.userInfo?.nickName || manager.userInfo?.userName"
                :value="manager.userId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="店铺描述" prop="storeDescribe">
            <el-input v-model="form.storeDescribe" type="textarea" placeholder="请输入内容" />
          </el-form-item>

            <el-form-item label="所属品牌" prop="brandId">
             <el-input v-model="form.brandName" readonly class="brand-input-disabled"/>
 <!--            <el-select v-model="form.brandId" placeholder="请选择所属品牌" filterable clearable>-->
 <!--              <el-option v-for="tenant in tenantOptions" :key="tenant.id" :label="tenant.brandName" :value="tenant.id" />-->
 <!--            </el-select>-->
            </el-form-item>

          <el-form-item label="店铺排序" prop="storeSort">
            <el-input-number
              v-model="form.storeSort"
              placeholder="请输入店铺排序"
              :min="0"
              :step="1"
              controls-position="right"
              @input="handleNumberInput('storeSort', $event)"
            />
          </el-form-item>

          <el-form-item label="店铺人气" prop="population">
            <el-input-number
              v-model="form.population"
              placeholder="请输入店铺人气"
              :min="0"
              :step="1"
              controls-position="right"
              @input="handleNumberInput('population', $event)"
            />
          </el-form-item>

          <el-form-item label="人均消费" prop="consume">
            <el-input-number
              v-model="form.consume"
              placeholder="请输入人均消费"
              :min="0"
              :step="1"
              controls-position="right"
              @input="handleNumberInput('consume', $event)"
            />
          </el-form-item>

          <el-form-item label="虚拟销量" prop="virtualSalesVolume">
            <el-input-number
              v-model="form.virtualSalesVolume"
              placeholder="请输入虚拟销量"
              :min="0"
              :step="1"
              controls-position="right"
              @input="handleNumberInput('virtualSalesVolume', $event)"
            />
          </el-form-item>

          <el-form-item label="等级评分" prop="ranking">
            <el-rate v-model="form.ranking" :max="5" show-text />
          </el-form-item>

          <el-form-item label="店铺电话" prop="storePhonenumber">
            <el-input v-model="form.storePhonenumber" placeholder="请输入店铺电话" />
          </el-form-item>
          <el-form-item label="营业时间*" prop="businessHours">
            <div class="business-hours-container">
              <!-- 营业时间段列表 -->
              <div class="business-hours-list" v-if="form.businessHoursList && form.businessHoursList.length > 0">
                <div
                  v-for="(timeSlot, index) in form.businessHoursList"
                  :key="index"
                  class="business-hours-item"
                >
                  <div class="time-inputs">
                    <div class="time-input-group">
                      <label class="time-label">开始时间</label>
                      <el-time-picker
                        v-model="timeSlot.startTime"
                        format="HH:mm"
                        value-format="HH:mm"
                        placeholder="选择开始时间"
                        :disabled="isView"
                        class="time-picker"
                        @change="updateBusinessHoursString"
                      />
                    </div>
                    <div class="time-input-group">
                      <label class="time-label">结束时间</label>
                      <el-time-picker
                        v-model="timeSlot.endTime"
                        format="HH:mm"
                        value-format="HH:mm"
                        placeholder="选择结束时间"
                        :disabled="isView"
                        class="time-picker"
                        @change="updateBusinessHoursString"
                      />
                      <el-button
                        v-if="!isView"
                        type="danger"
                        size="small"
                        @click="removeBusinessHours(index)"
                        class="delete-time-btn"
                      >
                        <el-icon><Close /></el-icon>
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 添加营业时间段按钮 -->
              <el-button
                v-if="!isView"
                type="primary"
                plain
                @click="addBusinessHours"
                class="add-business-hours-btn"
              >
                <el-icon><Plus /></el-icon>
                增加一个营业时间段
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="小程序分享图" prop="miniSharePic">
            <div class="slideshow-container">
              <!-- 上传按钮区域 -->
              <div class="upload-buttons" v-if="!isView">
                <el-button
                  type="default"
                  @click="showMiniSharePicSelector = true"
                  :disabled="form.miniSharePicFiles && form.miniSharePicFiles.length >= 1"
                >
                  <el-icon><Picture /></el-icon>
                  选择图片
                </el-button>
              </div>

              <!-- 已选择的图片展示区域 -->
              <div class="selected-images-grid" v-if="form.miniSharePicFiles && form.miniSharePicFiles.length > 0">
                <div
                  v-for="(file, index) in form.miniSharePicFiles"
                  :key="file.id || index"
                  class="image-item"
                >
                  <el-image
                    :src="getFileUrl(file)"
                    fit="cover"
                    class="slideshow-image"
                    :preview-disabled="false"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon size="20" color="#c0c4cc">
                          <Picture />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                  <!-- 删除按钮 -->
                  <div class="delete-btn" v-if="!isView" @click="removeMiniSharePicFile(index)">
                    <el-icon size="12" color="#fff">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>

              <!-- 提示信息 -->
              <div class="slideshow-tip">小程序分享图,建议大小200X200</div>
            </div>

            <!-- FileSelector 组件 -->
            <FileSelector
              v-model="showMiniSharePicSelector"
              :allowed-types="[1]"
              :multiple="false"
              :allow-upload="true"
              title="选择小程序分享图"
              @confirm="handleMiniSharePicSelected"
            />
          </el-form-item>

          <el-form-item label="店铺幻灯片" prop="lanternSlide">
            <div class="slideshow-container">
              <!-- 上传按钮区域 -->
              <div class="upload-buttons" v-if="!isView">
                <el-button
                  type="default"
                  @click="showLanternSlideSelector = true"
                  :disabled="form.lanternSlideFiles && form.lanternSlideFiles.length >= 10"
                >
                  <el-icon><Picture /></el-icon>
                  选择图片
                </el-button>
              </div>

              <!-- 已选择的图片展示区域 -->
              <div class="selected-images-grid" v-if="form.lanternSlideFiles && form.lanternSlideFiles.length > 0">
                <div
                  v-for="(file, index) in form.lanternSlideFiles"
                  :key="file.id || index"
                  class="image-item"
                >
                  <el-image
                    :src="getFileUrl(file)"
                    fit="cover"
                    class="slideshow-image"
                    :preview-disabled="false"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon size="20" color="#c0c4cc">
                          <Picture />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                  <!-- 删除按钮 -->
                  <div class="delete-btn" v-if="!isView" @click="removeLanternSlideFile(index)">
                    <el-icon size="12" color="#fff">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>

              <!-- 提示信息 -->
              <div class="slideshow-tip">店铺幻灯片,建议大小750X560,最多10张</div>
            </div>

            <!-- FileSelector 组件 -->
            <FileSelector
              v-model="showLanternSlideSelector"
              :allowed-types="[1]"
              :multiple="true"
              :allow-upload="true"
              title="选择店铺幻灯片"
              @confirm="handleLanternSlideSelected"
            />
          </el-form-item>

          <el-form-item label="幻灯片大小比例" prop="lanternSlideSize">
            <div class="size-ratio-container">
              <div class="size-inputs">
                <el-input v-model="form.lanternSlideSizeWide" placeholder="500" style="width: 100px">
                  <template #append>px</template>
                </el-input>
                <span class="size-separator">×</span>
                <el-input v-model="form.lanternSlideSizeHigh" placeholder="500" style="width: 100px">
                  <template #append>px</template>
                </el-input>
              </div>
              <div class="size-tip">设置的宽高不为实机演示的宽高,图片实机宽度为实机屏幕宽度,高度则以设置比例计算,不填即为默认的750X560。</div>
            </div>
          </el-form-item>

          <el-form-item label="店铺相册" prop="photoAlbum">
            <div class="slideshow-container">
              <!-- 上传按钮区域 -->
              <div class="upload-buttons" v-if="!isView">
                <el-button
                  type="default"
                  @click="showPhotoAlbumSelector = true"
                  :disabled="form.photoAlbumFiles && form.photoAlbumFiles.length >= 20"
                >
                  <el-icon><Picture /></el-icon>
                  选择图片
                </el-button>
              </div>

              <!-- 已选择的图片展示区域 -->
              <div class="selected-images-grid" v-if="form.photoAlbumFiles && form.photoAlbumFiles.length > 0">
                <div
                  v-for="(file, index) in form.photoAlbumFiles"
                  :key="file.id || index"
                  class="image-item"
                >
                  <el-image
                    :src="getFileUrl(file)"
                    fit="cover"
                    class="slideshow-image"
                    :preview-disabled="false"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon size="20" color="#c0c4cc">
                          <Picture />
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                  <!-- 删除按钮 -->
                  <div class="delete-btn" v-if="!isView" @click="removePhotoAlbumFile(index)">
                    <el-icon size="12" color="#fff">
                      <Close />
                    </el-icon>
                  </div>
                </div>
              </div>

              <!-- 提示信息 -->
              <div class="slideshow-tip">店铺相册,建议大小750X560,最多20张</div>
            </div>

            <!-- FileSelector 组件 -->
            <FileSelector
              v-model="showPhotoAlbumSelector"
              :allowed-types="[1]"
              :multiple="true"
              :allow-upload="true"
              title="选择店铺相册"
              @confirm="handlePhotoAlbumSelected"
            />
          </el-form-item>

          <el-form-item label="店铺详情" prop="shopDetails">
            <Editor v-model="form.shopDetails" :height="300" :fileSize="5" />
          </el-form-item>

          <el-form-item label="所属区域" prop="codeArr">
            <el-cascader
              v-model="form.codeArr"
              :options="regionData"
              placeholder="请选择"
              @change="handleChange"
              style="width: 100%"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="店铺地址" prop="storeAddress">
            <el-input v-model="form.storeAddress" placeholder="请输入店铺地址" />
          </el-form-item>

          <!-- <el-form-item label="地理位置" prop="geographicPosition">
            <el-input v-model="form.geographicPosition" placeholder="请输入地理位置" />
          </el-form-item> -->

          <el-form-item label="商户套餐" prop="packageId" class="long-input-field">
            <el-select v-model="form.packageId" placeholder="请选择商户套餐" clearable>
              <el-option
                v-for="option in packageOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="套餐名称" prop="packageName" class="long-input-field">
            <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
          </el-form-item> -->

          <el-form-item label="到期时间" prop="expireDate" class="long-input-field">
            <el-date-picker clearable v-model="form.expireDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择到期时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="商户状态" prop="storeStatus">
            <el-radio-group v-model="form.storeStatus">
              <el-radio v-for="dict in store_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        </el-form>
      </div>
    </el-card>

    <el-card shadow="always" class="card-footer" v-if="!isView">
      <div>
        <el-button type="primary" size="large" plain @click="close" v-hasPermi="['system:sysShop:add']">
          &nbsp;&nbsp;&nbsp;取消&nbsp;&nbsp;&nbsp;
        </el-button>
        <el-button type="primary" size="large" @click="submitForm" v-hasPermi="['system:sysShop:add']">
          &nbsp;&nbsp;&nbsp;保存&nbsp;&nbsp;&nbsp;
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup name="FoodIngredient" lang="ts">
import { listSysShop, getSysShop, delSysShop, addSysShop, updateSysShop, assignService } from '@/api/store/sysShop/index';
import { SysShopVO, SysShopQuery, SysShopForm } from '@/api/store/sysShop/types';
import { selectMyList, selectByTenantId } from '@/api/tenant/index';
import type { SysTenantVo } from '@/api/tenant/index';
import { regionData } from 'element-china-area-data';
import FileSelector from '@/components/FileSelector/index.js';
import { getFileInfo } from '@/api/file/info/index';
import { listShopManager } from '@/api/system/shopManager/index';
import type { SysShopManagerVO } from '@/api/system/shopManager/types';
// import { regionData } from 'element-china-area-data';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { store_status } = toRefs<any>(proxy?.useDict('store_status'));

// 区域选择数据
const provinceOptions = ref([
  { value: '110000', label: '北京市' },
  { value: '120000', label: '天津市' },
  { value: '130000', label: '河北省' },
  { value: '140000', label: '山西省' },
  { value: '150000', label: '内蒙古自治区' },
  { value: '210000', label: '辽宁省' },
  { value: '220000', label: '吉林省' },
  { value: '230000', label: '黑龙江省' },
  { value: '310000', label: '上海市' },
  { value: '320000', label: '江苏省' },
  { value: '330000', label: '浙江省' },
  { value: '340000', label: '安徽省' },
  { value: '350000', label: '福建省' },
  { value: '360000', label: '江西省' },
  { value: '370000', label: '山东省' },
  { value: '410000', label: '河南省' },
  { value: '420000', label: '湖北省' },
  { value: '430000', label: '湖南省' },
  { value: '440000', label: '广东省' },
  { value: '450000', label: '广西壮族自治区' },
  { value: '460000', label: '海南省' },
  { value: '500000', label: '重庆市' },
  { value: '510000', label: '四川省' },
  { value: '520000', label: '贵州省' },
  { value: '530000', label: '云南省' },
  { value: '540000', label: '西藏自治区' },
  { value: '610000', label: '陕西省' },
  { value: '620000', label: '甘肃省' },
  { value: '630000', label: '青海省' },
  { value: '640000', label: '宁夏回族自治区' },
  { value: '650000', label: '新疆维吾尔自治区' }
]);

const cityOptions = ref([]);
const districtOptions = ref([]);

// 门店管理员列表
const shopManagerList = ref<SysShopManagerVO[]>([]);

// 租户选项数据
const tenantOptions = ref<SysTenantVo[]>([]);

// 套餐选项数据
const packageOptions = ref([
  { label: '基础套餐', value: '1' },
  { label: '标准套餐', value: '2' },
  { label: '高级套餐', value: '3' },
  { label: '企业套餐', value: '4' },
  { label: '旗舰套餐', value: '5' }
]);

const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref<Array<string | number>>([]);

const divStyle = ref({
  minHeight: '620px'
});
const queryFormRef = ref<ElFormInstance>();
const sysShopFormRef = ref<ElFormInstance>();

const isView = ref<boolean>(false);
const route = useRoute();

// FileSelector 相关状态
const showLogoSelector = ref(false);
const showMiniSharePicSelector = ref(false);
const showLanternSlideSelector = ref(false);
const showPhotoAlbumSelector = ref(false);

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

const initFormData: SysShopForm = {
  id: undefined,
  storeLogo: undefined,
  storeName: undefined,
  storeDescribe: undefined,
  areaCode: undefined,
  province: '',
  city: '',
  district: '',
  vestInUserId: undefined,
  vestInUser: undefined,
  brandId: undefined,
  brandName: '',
  storeSort: undefined,
  population: undefined,
  consume: undefined,
  virtualSalesVolume: undefined,
  ranking: undefined,
  storePhonenumber: undefined,
  businessHours: '',
  businessHoursList: [],
  miniSharePic: undefined,
  lanternSlide: undefined,
  lanternSlideSizeWide: undefined,
  lanternSlideSizeHigh: undefined,
  photoAlbum: undefined,
  shopDetails: undefined,
  storeAddress: undefined,
  packageId: undefined,
  packageName: undefined,
  expireDate: undefined,
  storeStatus: '1',
  status: undefined,
  remark: undefined,
  codeArr: [],
  // 新增字段
  belongArea: '',
  geographicPosition: '',
  shopBusinessHoursBoList: [],
  // 新增文件数组字段
  storeLogoFiles: [],
  miniSharePicFiles: [],
  lanternSlideFiles: [],
  photoAlbumFiles: []
};

/** 数字验证函数 */
const validateNumber = (rule: any, value: any, callback: any) => {
  if (value === null || value === undefined || value === '') {
    callback();
    return;
  }

  // 检查是否为数字
  if (isNaN(Number(value)) || !/^\d+$/.test(String(value))) {
    callback(new Error('只能填写数字'));
    return;
  }

  callback();
};

/** 最大位数验证函数 */
const validateMaxDigits = (rule: any, value: any, callback: any) => {
  if (value === null || value === undefined || value === '') {
    callback();
    return;
  }

  const numStr = String(value);
  if (numStr.length > 8) {
    callback(new Error('最高为8位'));
    return;
  }

  callback();
};

const data = reactive<PageData<SysShopForm, SysShopQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeName: undefined,
    areaCode: undefined,
    vestInUserId: undefined,
    vestInUser: undefined,
    brandId: undefined,
    brandName: undefined,
    storeSort: undefined,
    storePhonenumber: undefined,
    miniSharePic: undefined,
    storeAddress: undefined,
    packageId: undefined,
    packageName: undefined,
    expireDate: undefined,
    storeStatus: undefined,
    params: {}
  },
  rules: {
    storeLogo: [{ required: true, message: '店铺logo不能为空', trigger: 'blur' }],
    storeName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
    vestInUserId: [{ required: true, message: '所属用户不能为空', trigger: 'change' }],
    storeDescribe: [{ required: true, message: '店铺描述不能为空', trigger: 'blur' }],
    brandId: [{ required: true, message: '所属品牌id不能为空', trigger: 'blur' }],
    storePhonenumber: [{ required: true, message: '店铺电话不能为空', trigger: 'blur' }],
    storeAddress: [{ required: true, message: '店铺地址不能为空', trigger: 'blur' }],
    expireDate: [{ required: true, message: '到期时间不能为空', trigger: 'blur' }],
    codeArr: [{ required: true, message: '所属区域不能为空', trigger: 'change' }],
    storeSort: [
      {
        validator: validateNumber,
        message: '只能填写数字',
        trigger: 'blur'
      },
      {
        validator: validateMaxDigits,
        message: '最高为8位',
        trigger: 'blur'
      }
    ],
    population: [
      {
        validator: validateNumber,
        message: '只能填写数字',
        trigger: 'blur'
      },
      {
        validator: validateMaxDigits,
        message: '最高为8位',
        trigger: 'blur'
      }
    ],
    consume: [
      {
        validator: validateNumber,
        message: '只能填写数字',
        trigger: 'blur'
      },
      {
        validator: validateMaxDigits,
        message: '最高为8位',
        trigger: 'blur'
      }
    ],
    virtualSalesVolume: [
      {
        validator: validateNumber,
        message: '只能填写数字',
        trigger: 'blur'
      },
      {
        validator: validateMaxDigits,
        message: '最高为8位',
        trigger: 'blur'
      }
    ]
  }
});

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

/** 处理数字输入 */
const handleNumberInput = (fieldName: string, value: any) => {
  // 如果输入为空，直接返回
  if (value === null || value === undefined || value === '') {
    return;
  }

  // 检查是否为数字
  if (isNaN(Number(value)) || !/^\d+$/.test(String(value))) {
    // 如果不是数字，触发验证错误
    sysShopFormRef.value?.validateField(fieldName);
    return;
  }

  // 检查位数是否超过8位
  const numStr = String(value);
  if (numStr.length > 8) {
    // 如果超过8位，触发验证错误
    sysShopFormRef.value?.validateField(fieldName);
    return;
  }

  // 清除之前的验证错误
  sysShopFormRef.value?.clearValidate(fieldName);
};

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

/** 关闭按钮 */
const close = () => {
  const obj = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/store/sysShop'
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  sysShopFormRef.value?.resetFields();
};



/** 处理区域选择变化 */
const handleChange = (val: string[]) => {
  form.value.areaCode = val.join(',');
  // 这里可以根据需要添加其他逻辑
};

/** 处理门店logo选择 */
const handleLogoSelected = (files: any[]) => {
  if (!form.value.storeLogoFiles) {
    form.value.storeLogoFiles = [];
  }

  // 门店logo只能选择一张，直接替换
  if (files.length > 0) {
    form.value.storeLogoFiles = [files[0]];
  } else {
    form.value.storeLogoFiles = [];
  }

  // 更新 storeLogo 字段为文件path字符串
  updateLogoString();
};

/** 删除门店logo文件 */
const removeLogoFile = (index: number) => {
  form.value.storeLogoFiles.splice(index, 1);
  updateLogoString();
};

/** 更新门店logo字符串 */
const updateLogoString = () => {
  if (form.value.storeLogoFiles && form.value.storeLogoFiles.length > 0) {
    form.value.storeLogo = form.value.storeLogoFiles[0].path;
  } else {
    form.value.storeLogo = '';
  }
};

/** 处理小程序分享图选择 */
const handleMiniSharePicSelected = (files: any[]) => {
  if (!form.value.miniSharePicFiles) {
    form.value.miniSharePicFiles = [];
  }

  // 小程序分享图只能选择一张，直接替换
  if (files.length > 0) {
    form.value.miniSharePicFiles = [files[0]];
  } else {
    form.value.miniSharePicFiles = [];
  }

  // 更新 miniSharePic 字段为文件path字符串
  updateMiniSharePicString();
};

/** 删除小程序分享图文件 */
const removeMiniSharePicFile = (index: number) => {
  form.value.miniSharePicFiles.splice(index, 1);
  updateMiniSharePicString();
};

/** 更新小程序分享图字符串 */
const updateMiniSharePicString = () => {
  if (form.value.miniSharePicFiles && form.value.miniSharePicFiles.length > 0) {
    form.value.miniSharePic = form.value.miniSharePicFiles[0].path;
  } else {
    form.value.miniSharePic = '';
  }
};

/** 处理店铺幻灯片选择 */
const handleLanternSlideSelected = (files: any[]) => {
  if (!form.value.lanternSlideFiles) {
    form.value.lanternSlideFiles = [];
  }

  // 合并新选择的文件，避免重复
  files.forEach(file => {
    const exists = form.value.lanternSlideFiles.some(f => f.path === file.path);
    if (!exists && form.value.lanternSlideFiles.length < 10) {
      form.value.lanternSlideFiles.push(file);
    }
  });

  // 更新 lanternSlide 字段为文件path字符串
  updateLanternSlideString();
};

/** 处理店铺相册选择 */
const handlePhotoAlbumSelected = (files: any[]) => {
  if (!form.value.photoAlbumFiles) {
    form.value.photoAlbumFiles = [];
  }

  // 合并新选择的文件，避免重复
  files.forEach(file => {
    const exists = form.value.photoAlbumFiles.some(f => f.path === file.path);
    if (!exists && form.value.photoAlbumFiles.length < 20) {
      form.value.photoAlbumFiles.push(file);
    }
  });

  // 更新 photoAlbum 字段为文件path字符串
  updatePhotoAlbumString();
};

/** 删除店铺幻灯片文件 */
const removeLanternSlideFile = (index: number) => {
  form.value.lanternSlideFiles.splice(index, 1);
  updateLanternSlideString();
};

/** 删除店铺相册文件 */
const removePhotoAlbumFile = (index: number) => {
  form.value.photoAlbumFiles.splice(index, 1);
  updatePhotoAlbumString();
};

/** 更新店铺幻灯片字符串 */
const updateLanternSlideString = () => {
  if (form.value.lanternSlideFiles && form.value.lanternSlideFiles.length > 0) {
    form.value.lanternSlide = form.value.lanternSlideFiles.map(file => file.path).join(',');
  } else {
    form.value.lanternSlide = '';
  }
};

/** 更新店铺相册字符串 */
const updatePhotoAlbumString = () => {
  if (form.value.photoAlbumFiles && form.value.photoAlbumFiles.length > 0) {
    form.value.photoAlbum = form.value.photoAlbumFiles.map(file => file.path).join(',');
  } else {
    form.value.photoAlbum = '';
  }
};

/** 获取文件URL */
const getFileUrl = (file: any) => {
  if (file.url) {
    if (file.url.startsWith('http://') || file.url.startsWith('https://')) {
      return file.url;
    }
    if (file.url.startsWith('/')) {
      return import.meta.env.VITE_APP_BASE_API + file.url;
    }
    return file.url;
  }

  if (file.path) {
    if (file.path.startsWith('http://') || file.path.startsWith('https://')) {
      return file.path;
    }
    if (file.path.startsWith('/')) {
      return import.meta.env.VITE_APP_BASE_API + file.path;
    }
    return file.path;
  }

  return '';
};

// 文件URL缓存
const fileUrlCache = ref<Map<string, string>>(new Map());

// 根据文件ID获取文件URL
const getFileUrlById = async (fileId: string | number): Promise<string> => {
  if (!fileId) return '';

  const idStr = String(fileId);

  // 如果已经是完整URL，直接返回
  if (idStr.startsWith('http://') || idStr.startsWith('https://')) {
    return idStr;
  }

  // 检查缓存
  if (fileUrlCache.value.has(idStr)) {
    return fileUrlCache.value.get(idStr) || '';
  }

  try {
    // 确保文件ID是有效的数字
    const numericId = Number(fileId);
    if (isNaN(numericId)) {
      console.warn('无效的文件ID:', fileId);
      return '';
    }

    const fileInfo = await getFileInfo(numericId);
    const url = fileInfo.data?.url || fileInfo.data?.path || '';

    // 缓存结果
    fileUrlCache.value.set(idStr, url);

    return url;
  } catch (error) {
    console.error('获取文件URL失败:', error);
    return '';
  }
};

/** 处理省份变化 */
const handleProvinceChange = (value: string) => {
  form.value.city = '';
  form.value.district = '';
  cityOptions.value = [];
  districtOptions.value = [];

  // 这里可以根据省份代码加载对应的城市数据
  // 为了演示，这里添加一些示例数据
  if (value === '110000') {
    cityOptions.value = [{ value: '110100', label: '北京市' }];
  } else if (value === '310000') {
    cityOptions.value = [{ value: '310100', label: '上海市' }];
  } else if (value === '440000') {
    cityOptions.value = [
      { value: '440100', label: '广州市' },
      { value: '440300', label: '深圳市' },
      { value: '440600', label: '佛山市' },
      { value: '440700', label: '江门市' }
    ];
  }

  updateAreaCode();
};

/** 处理城市变化 */
const handleCityChange = (value: string) => {
  form.value.district = '';
  districtOptions.value = [];

  // 这里可以根据城市代码加载对应的区县数据
  // 为了演示，这里添加一些示例数据
  if (value === '440100') {
    districtOptions.value = [
      { value: '440103', label: '荔湾区' },
      { value: '440104', label: '越秀区' },
      { value: '440105', label: '海珠区' },
      { value: '440106', label: '天河区' },
      { value: '440111', label: '白云区' },
      { value: '440112', label: '黄埔区' },
      { value: '440113', label: '番禺区' },
      { value: '440114', label: '花都区' },
      { value: '440115', label: '南沙区' },
      { value: '440117', label: '从化区' },
      { value: '440118', label: '增城区' }
    ];
  } else if (value === '440300') {
    districtOptions.value = [
      { value: '440303', label: '罗湖区' },
      { value: '440304', label: '福田区' },
      { value: '440305', label: '南山区' },
      { value: '440306', label: '宝安区' },
      { value: '440307', label: '龙岗区' },
      { value: '440308', label: '盐田区' },
      { value: '440309', label: '龙华区' },
      { value: '440310', label: '坪山区' },
      { value: '440311', label: '光明区' }
    ];
  }

  updateAreaCode();
};

/** 更新区域代码 */
const updateAreaCode = () => {
  const codes = [];
  if (form.value.province) codes.push(form.value.province);
  if (form.value.city) codes.push(form.value.city);
  if (form.value.district) codes.push(form.value.district);
  form.value.areaCode = codes.join(',');
};

/** 加载租户列表 */
const loadTenantList = async () => {
  try {
    const res = await selectMyList();
    console.log('租户接口返回数据:', res);
    // 根据接口返回的数据结构，取 data 字段
    tenantOptions.value = res.data;
    console.log('租户选项数据:', tenantOptions.value);
  } catch (error) {
    console.error('加载租户列表失败:', error);
    proxy?.$modal.msgError('加载租户列表失败');
  }
};

/** 加载门店管理员列表 */
const loadShopManagerList = async () => {
  try {
    const res = await listShopManager();
    console.log('门店管理员接口返回数据:', res);
    // 根据接口返回的数据结构，取 rows 字段
    shopManagerList.value = res.rows || [];
    console.log('门店管理员选项数据:', shopManagerList.value);
    console.log('当前表单中的 vestInUserId:', form.value.vestInUserId);
    
    // 检查当前选中的用户是否在列表中
    if (form.value.vestInUserId && shopManagerList.value.length > 0) {
      const selectedManager = shopManagerList.value.find(manager => manager.userId === form.value.vestInUserId);
      console.log('查找选中的用户:', selectedManager);
      if (selectedManager) {
        console.log('找到匹配的用户:', selectedManager.userInfo);
      } else {
        console.log('未找到匹配的用户，vestInUserId:', form.value.vestInUserId);
      }
    }
  } catch (error) {
    console.error('加载门店管理员列表失败:', error);
    proxy?.$modal.msgError('加载门店管理员列表失败');
  }
};

/** 添加营业时间段 */
const addBusinessHours = () => {
  if (!form.value.businessHoursList) {
    form.value.businessHoursList = [];
  }
  form.value.businessHoursList.push({
    startTime: '',
    endTime: ''
  });
  updateBusinessHoursString();
};

/** 删除营业时间段 */
const removeBusinessHours = (index: number) => {
  if (form.value.businessHoursList && form.value.businessHoursList.length > index) {
    form.value.businessHoursList.splice(index, 1);
    updateBusinessHoursString();
  }
};

/** 更新营业时间字符串 */
const updateBusinessHoursString = () => {
  if (form.value.businessHoursList && form.value.businessHoursList.length > 0) {
    const timeStrings = form.value.businessHoursList
      .filter(slot => slot.startTime && slot.endTime)
      .map(slot => `${slot.startTime}-${slot.endTime}`);
    form.value.businessHours = timeStrings.join(',');
  } else {
    form.value.businessHours = '';
  }
};

/** 提交按钮 */
const submitForm = () => {
  sysShopFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 解析省市区名称
        const areaNames = parseAreaNames(form.value.codeArr || []);
        console.log('区域代码:', form.value.codeArr);
        console.log('解析的省市区名称:', areaNames);

        // 调试文件路径信息
        console.log('门店logo路径:', form.value.storeLogo);
        console.log('小程序分享图路径:', form.value.miniSharePic);
        console.log('店铺幻灯片路径:', form.value.lanternSlide);
        console.log('店铺相册路径:', form.value.photoAlbum);

        // 准备提交的数据，确保格式与后端接口匹配
        const submitData = {
          ...form.value,
          // 确保 vestInUserId 是数字类型
          vestInUserId: safeNumber(form.value.vestInUserId),
          // 确保 brandId 是数字类型
          brandId: safeNumber(form.value.brandId),
          // 设置省市区名称
          province: areaNames.province,
          city: areaNames.city,
          district: areaNames.district,
          // 设置所属区域和地理位置（从区域代码解析）
          belongArea: form.value.areaCode || form.value.codeArr?.join(',') || '',
          geographicPosition: form.value.areaCode || form.value.codeArr?.join(',') || '',
          // 营业时间直接使用字符串
          businessHours: form.value.businessHours || '',
          // 将营业时间段转换为 shopBusinessHoursBoList 格式
          shopBusinessHoursBoList: form.value.businessHoursList?.map((slot, index) => ({
            id: undefined, // 新增时没有ID
            name: `营业时间段${index + 1}`,
            shopId: form.value.id || undefined,
            startTime: slot.startTime || '',
            endTime: slot.endTime || '',
            remark: ''
          })) || [],
          // 移除前端特有的字段
          storeLogoFiles: undefined,
          miniSharePicFiles: undefined,
          lanternSlideFiles: undefined,
          photoAlbumFiles: undefined
        };

        console.log('提交的营业时间数据:', {
          businessHours: submitData.businessHours,
          shopBusinessHoursBoList: submitData.shopBusinessHoursBoList,
          businessHoursList: form.value.businessHoursList
        });

        if (form.value.id) {
          await updateSysShop(submitData);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          const res = await addSysShop(submitData);
          form.value.id = res.data;
          proxy?.$modal.msgSuccess('新增成功');
        }

        // 延迟一下再跳转，让用户看到成功提示
        setTimeout(() => {
          close();
        }, 1500);
      } catch (error) {
        console.error('提交失败:', error);
        proxy?.$modal.msgError('操作失败');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

onMounted(async () => {
  // 设置品牌名字
  await getUserInfo();
  loadTenantList();
  // 预加载门店管理员列表
  await loadShopManagerList();

  // 获取路由参数中的门店ID
  const shopId = route.params.id;
  if (shopId && shopId !== '0') {
    // 编辑模式，加载门店详情
    const id = Array.isArray(shopId) ? shopId[0] : shopId;
    await loadShopDetail(id);
  }
});

import { useUserStore } from "@/store/modules/user";

/** 安全的数字转换函数 */
const safeNumber = (value: any): number | null => {
  if (value === null || value === undefined || value === '') {
    return null;
  }
  const num = Number(value);
  return isNaN(num) ? null : num;
};

/** 从区域代码解析省市区名称 */
const parseAreaNames = (codeArr: string[]): { province: string; city: string; district: string } => {
  if (!codeArr || codeArr.length < 3) {
    return { province: '', city: '', district: '' };
  }

  const [provinceCode, cityCode, districtCode] = codeArr;

  // 从 regionData 中查找对应的名称
  const findAreaName = (code: string, data: any[]): string => {
    for (const item of data) {
      if (item.value === code) {
        return item.label;
      }
      if (item.children) {
        const found = findAreaName(code, item.children);
        if (found) return found;
      }
    }
    return '';
  };

  return {
    province: findAreaName(provinceCode, regionData),
    city: findAreaName(cityCode, regionData),
    district: findAreaName(districtCode, regionData)
  };
};

const getUserInfo = async () => {
  try {
    const userStore = useUserStore();
    const res = await selectByTenantId(userStore.tenantId);
    // 更新表单数据中的品牌名称
    form.value.brandName = res.data.brandName;
    form.value.brandId = res.data.id;
    // 只在编辑门店时才自动设置用户信息，新增时保持为空
    if (route.query.id) {
      form.value.vestInUserId = safeNumber(userStore.userId);
      form.value.vestInUser = userStore.nickname;
    }
  } catch (error) {
    console.error('获取当前品牌名字失败:', error);
    proxy?.$modal.msgError('获取品牌信息失败');
  }
};

/** 加载门店详情 */
const loadShopDetail = async (shopId: string | number) => {
  try {
    loading.value = true;
    const res = await getSysShop(shopId);
    const shopData = res.data;

    // 填充表单数据
    form.value = {
      ...form.value,
      id: shopData.id,
      storeLogo: shopData.storeLogo,
      storeName: shopData.storeName,
      storeDescribe: shopData.storeDescribe,
      areaCode: shopData.areaCode,
      province: shopData.province,
      city: shopData.city,
      district: shopData.district,
      vestInUserId: shopData.vestInUserId,
      vestInUser: String(shopData.vestInUser),
      brandId: shopData.brandId,
      brandName: shopData.brandName,
      storeSort: shopData.storeSort,
      population: shopData.population,
      consume: shopData.consume,
      virtualSalesVolume: shopData.virtualSalesVolume,
      ranking: shopData.ranking,
      storePhonenumber: shopData.storePhonenumber,
      miniSharePic: shopData.miniSharePic,
      lanternSlide: shopData.lanternSlide,
      lanternSlideSizeWide: shopData.lanternSlideSizeWide,
      lanternSlideSizeHigh: shopData.lanternSlideSizeHigh,
      photoAlbum: shopData.photoAlbum,
      shopDetails: shopData.shopDetails,
      storeAddress: shopData.storeAddress,
      packageId: shopData.packageId,
      packageName: shopData.packageName,
      expireDate: shopData.expireDate,
      storeStatus: shopData.storeStatus,
      status: shopData.status,
      remark: shopData.remark,
      belongArea: shopData.belongArea,
      geographicPosition: shopData.geographicPosition,
      businessHours: shopData.businessHours || '',
      shopBusinessHoursBoList: shopData.shopBusinessHoursBoList || []
    };

    // 处理区域代码数组
    if (shopData.areaCode) {
      form.value.codeArr = shopData.areaCode.split(',');
    }

    // 处理营业时间数据
    form.value.businessHours = shopData.businessHours || '';

    // 解析营业时间段 - 优先使用 businessHoursVoList，如果没有则解析 businessHours 字符串
    console.log('开始解析营业时间数据:', {
      businessHoursVoList: shopData.businessHoursVoList,
      businessHours: shopData.businessHours
    });

    if (shopData.businessHoursVoList && shopData.businessHoursVoList.length > 0) {
      // 使用 businessHoursVoList 数据
      console.log('使用 businessHoursVoList 数据');
      form.value.businessHoursList = shopData.businessHoursVoList.map(item => ({
        startTime: item.startTime || '',
        endTime: item.endTime || ''
      }));
    } else if (shopData.businessHours && shopData.businessHours !== '') {
      // 如果没有 businessHoursVoList，则解析 businessHours 字符串
      console.log('解析 businessHours 字符串:', shopData.businessHours);
      const timeSlots = shopData.businessHours.split(',').map(timeStr => {
        const [startTime, endTime] = timeStr.split('-');
        return {
          startTime: startTime || '',
          endTime: endTime || ''
        };
      });
      form.value.businessHoursList = timeSlots;
      console.log('解析后的时间段:', timeSlots);
    } else {
      console.log('没有营业时间数据，设置为空数组');
      form.value.businessHoursList = [];
    }

    // 处理文件数据 - 异步加载文件URL
    await loadFileUrls(shopData);

    console.log('门店详情加载成功:', shopData);
    console.log('营业时间数据:', {
      businessHours: shopData.businessHours,
      businessHoursVoList: shopData.businessHoursVoList,
      businessHoursList: form.value.businessHoursList
    });
    console.log('所属用户数据:', {
      vestInUserId: shopData.vestInUserId,
      vestInUser: shopData.vestInUser,
      shopManagerList: shopManagerList.value
    });

    // 强制触发响应式更新
    console.log('当前 businessHoursList 长度:', form.value.businessHoursList?.length);
    console.log('当前 businessHoursList 内容:', JSON.stringify(form.value.businessHoursList));
  } catch (error) {
    console.error('加载门店详情失败:', error);
    proxy?.$modal.msgError('加载门店详情失败');
  } finally {
    loading.value = false;
  }
};

/** 异步加载文件URL */
const loadFileUrls = async (shopData: any) => {
  try {
    // 处理门店logo
    if (shopData.storeLogo && shopData.storeLogo !== '') {
      const logoUrl = await getFileUrlById(shopData.storeLogo);
      if (logoUrl) {
        form.value.storeLogoFiles = [{
          path: shopData.storeLogo,
          url: logoUrl
        }];
      }
    }

    // 处理小程序分享图
    if (shopData.miniSharePic && shopData.miniSharePic !== '') {
      const miniShareUrl = await getFileUrlById(shopData.miniSharePic);
      if (miniShareUrl) {
        form.value.miniSharePicFiles = [{
          path: shopData.miniSharePic,
          url: miniShareUrl
        }];
      }
    }

    // 处理店铺幻灯片
    if (shopData.lanternSlide && shopData.lanternSlide !== '') {
      const lanternPaths = shopData.lanternSlide.split(',').filter(path => path.trim() !== '');
      if (lanternPaths.length > 0) {
        const lanternUrls = await Promise.all(
          lanternPaths.map(path => getFileUrlById(path.trim()))
        );
        form.value.lanternSlideFiles = lanternPaths.map((path, index) => ({
          path: path.trim(),
          url: lanternUrls[index] || ''
        })).filter(item => item.url); // 只保留有URL的项目
      }
    }

    // 处理店铺相册
    if (shopData.photoAlbum && shopData.photoAlbum !== '') {
      const photoPaths = shopData.photoAlbum.split(',').filter(path => path.trim() !== '');
      if (photoPaths.length > 0) {
        const photoUrls = await Promise.all(
          photoPaths.map(path => getFileUrlById(path.trim()))
        );
        form.value.photoAlbumFiles = photoPaths.map((path, index) => ({
          path: path.trim(),
          url: photoUrls[index] || ''
        })).filter(item => item.url); // 只保留有URL的项目
      }
    }
  } catch (error) {
    console.error('加载文件URL失败:', error);
  }
};

</script>

<style lang="scss" scoped>
.card-footer {
  z-index: 99;
  bottom: 0px;
  left: calc(var(--left-menu-max-width) + var(--app-content-padding));
  right: 0px;
  height: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}

// 表单布局样式
.shop-form {
  // 整体向右移动，增加左边距
  margin-left: 60px;

  // 单列布局，每个表单项占一行
  .el-form-item {
    margin-bottom: 20px;

    :deep(.el-form-item__content) {
      max-width: 800px;
    }
  }

  // 指定字段的输入框拉长至与红框等长
  .el-form-item:nth-child(2), // 店铺名称
  .el-form-item:nth-child(3), // 所属用户
  .el-form-item:nth-child(4), // 店铺描述
  .el-form-item:nth-child(5), // 所属品牌
  .el-form-item:nth-child(6), // 店铺排序
  .el-form-item:nth-child(7), // 店铺人气
  .el-form-item:nth-child(8), // 人均消费
  .el-form-item:nth-child(9), // 虚拟销量
  .el-form-item:nth-child(10), // 等级评分
  .el-form-item:nth-child(11), // 店铺电话
  .el-form-item:nth-child(13), // 小程序分享图
  .el-form-item:nth-child(15), // 所属区域
  .el-form-item:nth-child(16), // 店铺地址
  // .el-form-item:nth-child(17), // 地理位置 (已隐藏)
  .el-form-item:nth-child(17), // 商户套餐
  // .el-form-item:nth-child(18), // 套餐名称 (已隐藏)
  .el-form-item:nth-child(18), // 到期时间
  .el-form-item:nth-child(19) { // 商户状态
    :deep(.el-form-item__content) {
      max-width: 800px;
    }

    :deep(.el-input) {
      width: 100%;
      max-width: 800px;
    }

    :deep(.el-input-number) {
      width: 100%;
      max-width: 800px;

      .el-input__inner {
        text-align: left !important;
      }
    }

    :deep(.el-select) {
      width: 100% !important;
      max-width: 800px !important;
    }

    :deep(.el-cascader) {
      width: 100%;
      max-width: 800px;
    }

    :deep(.el-date-picker) {
      width: 100%;
      max-width: 800px;
    }

    :deep(.el-textarea) {
      width: 100%;
      max-width: 800px;
    }
  }

  // 长输入框字段特殊处理（商户套餐、到期时间）
  .long-input-field {
    :deep(.el-form-item__content) {
      max-width: 800px;
    }

    :deep(.el-input) {
      width: 100%;
      max-width: 800px;
    }

    :deep(.el-select) {
      width: 100%;
      max-width: 800px;
    }

    :deep(.el-date-picker) {
      width: 100%;
      max-width: 800px;
    }
  }

  // 其他字段保持原有宽度
  :deep(.el-input) {
    width: 100%;
    max-width: 600px;
  }

  :deep(.el-select) {
    width: 100%;
    max-width: 600px;
  }

  :deep(.el-cascader) {
    width: 100%;
    max-width: 600px;
  }

  :deep(.el-date-picker) {
    width: 100%;
    max-width: 600px;
  }

  :deep(.el-textarea) {
    width: 100%;
    max-width: 600px;
  }

  // 图片上传组件保持原有宽度
  :deep(.image-upload) {
    max-width: none;
  }

  // 编辑器组件保持原有宽度
  :deep(.editor-container) {
    max-width: none;
  }

  // 品牌输入框样式 - 稍微暗一些，不允许输入
  .brand-input-disabled {
    :deep(.el-input__inner) {
      background-color: #f5f7fa !important;
      color: #606266 !important;
      cursor: not-allowed !important;
      border-color: #dcdfe6 !important;
    }

    :deep(.el-input__inner:hover) {
      border-color: #dcdfe6 !important;
    }

    :deep(.el-input__inner:focus) {
      border-color: #dcdfe6 !important;
      box-shadow: none !important;
    }
  }

  // 用户输入框样式 - 稍微暗一些，不允许输入
  .user-input-disabled {
    :deep(.el-input__inner) {
      background-color: #f5f7fa !important;
      color: #606266 !important;
      cursor: not-allowed !important;
      border-color: #dcdfe6 !important;
    }

    :deep(.el-input__inner:hover) {
      border-color: #dcdfe6 !important;
    }

    :deep(.el-input__inner:focus) {
      border-color: #dcdfe6 !important;
      box-shadow: none !important;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .shop-form {
    margin-left: 30px;

    .el-form-item {
      :deep(.el-form-item__content) {
        max-width: 600px;
      }
    }

    // 指定字段在中等屏幕上的宽度
    .el-form-item:nth-child(2),
    .el-form-item:nth-child(3),
    .el-form-item:nth-child(4),
    .el-form-item:nth-child(5),
    .el-form-item:nth-child(6),
    .el-form-item:nth-child(7),
    .el-form-item:nth-child(8),
    .el-form-item:nth-child(9),
    .el-form-item:nth-child(10),
    .el-form-item:nth-child(11),
    .el-form-item:nth-child(13),
    .el-form-item:nth-child(15),
    .el-form-item:nth-child(16),
    // .el-form-item:nth-child(17), // 地理位置 (已隐藏)
    .el-form-item:nth-child(17),
    // .el-form-item:nth-child(18), // 套餐名称 (已隐藏)
    .el-form-item:nth-child(18),
    .el-form-item:nth-child(19) {
      :deep(.el-form-item__content) {
        max-width: 600px;
      }

      :deep(.el-input),
      :deep(.el-input-number),
      :deep(.el-select),
      :deep(.el-cascader),
      :deep(.el-date-picker),
      :deep(.el-textarea) {
        max-width: 600px !important;
      }

      :deep(.el-input-number) {
        .el-input__inner {
          text-align: left !important;
        }
      }
    }

    :deep(.el-input),
    :deep(.el-input-number),
    :deep(.el-select),
    :deep(.el-cascader),
    :deep(.el-date-picker),
    :deep(.el-textarea) {
      max-width: 500px;
    }
  }
}

@media (max-width: 768px) {
  .shop-form {
    margin-left: 0;

    :deep(.el-form-item__label) {
      width: 100px !important;
    }

    :deep(.el-form-item__content) {
      margin-left: 100px !important;
      max-width: calc(100% - 100px) !important;
    }

    :deep(.el-input),
    :deep(.el-input-number),
    :deep(.el-select),
    :deep(.el-cascader),
    :deep(.el-date-picker),
    :deep(.el-textarea) {
      max-width: 100% !important;
    }
  }
}

/* 营业时间样式 */
.business-hours-container {
  width: 100%;
}

.business-hours-list {
  margin-bottom: 16px;
}

.business-hours-item {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.time-inputs {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.time-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.time-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
  min-width: 60px;
}

.time-picker {
  width: 120px;
}

.delete-time-btn {
  height: 32px;
  padding: 0 12px;
  margin-left: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.add-business-hours-btn {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
  background: #17a2b8;
  border-color: #17a2b8;
  color: white;
}

.add-business-hours-btn:hover {
  background: #138496;
  border-color: #138496;
}

.add-business-hours-btn .el-icon {
  margin-right: 4px;
}

.slideshow-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.size-ratio-container {
  width: 100%;
}

.size-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.size-separator {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.size-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.area-selectors {
  display: flex;
  gap: 12px;
  align-items: center;
}

.area-select {
  flex: 1;
  min-width: 120px;
}

/* 店铺幻灯片样式 - 仿照第一张图片的效果 */
.slideshow-container {
  width: 100%;
}

.upload-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.upload-buttons .el-button {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
}

.selected-images-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.image-item:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.slideshow-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 18px;
  height: 18px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.delete-btn:hover {
  background: rgba(255, 0, 0, 0.8);
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
}

.slideshow-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
