<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="120px">

      <el-divider content-position="left">基础信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="店铺名称" prop="storeName">
            <el-input v-model="form.storeName" placeholder="请输入店铺名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入店铺电话"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商家Id" prop="merchantId">
            <el-input v-model="form.merchantId" placeholder="请输入商家Id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺Id" prop="storeSeq">
            <el-input v-model="form.storeSeq" placeholder="请输入店铺Id" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="企业全称" prop="fullName">
        <el-input v-model="form.fullName" placeholder="请输入企业全称"/>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="店铺LOGO" prop="logoUrl">
            <el-upload
              v-model="form.logoUrl"
              :action="uploadUrl"
              :headers="headers"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              class="avatar-uploader"
            >
              <!-- 图片容器（包含图片和删除按钮，仅在有图片时显示） -->
              <div class="avatar-wrapper" v-if="form.logoUrl">
                <img :src="form.logoUrl" class="avatar" width="200px">
                <!-- 悬停显示的删除按钮 -->
                <div class="delete-mask" @click.stop="handleDeleteLogo">
                  <i class="el-icon-delete"></i>
                </div>
              </div>
              <!-- 未上传图片时显示的默认图标 -->
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="店铺介绍" prop="descs">
            <el-input v-model="form.descs" placeholder="请输入店铺介绍" type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属城市" prop="cityIds">
            <el-cascader
              ref="citySelect"
              v-model="form.cityIds"
              :options="citys"
              @change="handleCityChange"
            >
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址" prop="enterpriseAddress">
            <el-input v-model="form.enterpriseAddress" placeholder="请输入地址"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法人姓名" prop="legalPersonName">
            <el-input v-model="form.legalPersonName" placeholder="请输入法人姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="form.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="营业范围" prop="businessScope">
        <el-input v-model="form.businessScope" placeholder="请输入营业范围" type="textarea"/>
      </el-form-item>

      <!-- 证书上传相关字段 -->
      <el-divider content-position="left">资质证书信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="营业执照上传" prop="businessLicense">
            <el-upload
              :action="uploadUrl"
              :headers="headers"
              :before-upload="beforeAvatarUpload"
              :on-success="(response, file) => handleFileSuccess(response, file, 'businessLicense')"
              :show-file-list="false"
              class="avatar-uploader"
            >
              <div class="avatar-wrapper" v-if="form.businessLicense">
                <img :src="form.businessLicense" class="avatar" width="200px">
<!--                <div class="delete-mask" @click.stop="handleDelete5">-->
<!--                  <i class="el-icon-delete"></i>-->
<!--                </div>-->
                <div class="button-group">
                  <div class="preview-btn" @click.stop="previewImage(form.businessLicense)">
                    <i class="el-icon-zoom-in"></i>
                  </div>
                  <div v-if="!isViewMode" class="delete-btn" @click.stop="handleDelete5">
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </div>
              <!-- 未上传图片时显示的默认图标 -->
              <div v-else class="no-image-placeholder">
                <span v-if="isViewMode">用户未上传</span>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </el-upload>
          </el-form-item>
          <el-col :span="12">
            <el-form-item label="营业执照编号" prop="businessCode" style="margin-left: 5px;margin-bottom: 20px">
              <el-input v-model="form.businessCode" placeholder="请输入营业制造编号" />
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="12">
          <el-form-item label="营业执照是否长期有效" prop="isBusinessLicensePermanent">
            <el-switch
              @change="switchChange()"
              v-model="switchValue"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
          <el-form-item label="营业执照失效日期" prop="businessLicenseExpire" v-if="!switchValue">
            <el-date-picker
              v-model="form.businessLicenseExpire"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="medicalMallConfig.isMedicalMall">
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品经营许可证上传" prop="drugLicense">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
              :headers="headers"
                :show-file-list="false"
                :on-success="(response, file) => handleFileSuccess(response, file, 'drugLicense')"
                :before-upload="beforeAvatarUpload">
                <div class="avatar-wrapper" v-if="form.drugLicense">
                  <img :src="form.drugLicense" class="avatar" width="200px">
<!--                  <div class="delete-mask" @click.stop="handleDelete6">-->
<!--                    <i class="el-icon-delete"></i>-->
<!--                  </div>-->
                  <div class="button-group">
                    <div class="preview-btn" @click.stop="previewImage(form.drugLicense)">
                      <i class="el-icon-zoom-in"></i>
                    </div>
                    <div v-if="!isViewMode" class="delete-btn" @click.stop="handleDelete6">
                      <i class="el-icon-delete"></i>
                    </div>
                  </div>
                </div>
                <!-- 未上传图片时显示的默认图标 -->
                <div v-else class="no-image-placeholder">
                  <span v-if="isViewMode">用户未上传</span>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </el-upload>
            </el-form-item>

            <el-col :sapn="24">
              <el-form-item label="药品经营许可证经营范围" prop="drugLicenseBusinessScope" style="margin-left: 5px">
                <el-input v-model="form.drugLicenseBusinessScope" placeholder="请输入药品经营许可证经营范围" type="textarea"/>
              </el-form-item>
            </el-col>

            <!-- 新增的单选框 -->
<!--            <el-col :span="24">-->
<!--              <el-form-item label="药品经营许可证范围是否包含" prop="drugScopeHasFrozen" style="margin-left: 5px">-->
<!--                <el-radio-group v-model="form.drugScopeHasFrozen">-->
<!--                  <el-radio label="0">否</el-radio>-->
<!--                  <el-radio label="1">冷冻</el-radio>-->
<!--                  <el-radio label="2">冷藏</el-radio>-->
<!--                  <el-radio label="3">冷冻冷藏</el-radio>-->
<!--                </el-radio-group>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <!-- 结束 -->

            <el-col :span="14">
              <el-form-item label="药品经营许可证编号" prop="drugCode" style="margin-left: 5px">
                <el-input v-model="form.drugCode" placeholder="请输入药品经营许可证编号" />
              </el-form-item>
            </el-col>

          </el-col>
          <el-col :span="12">
            <el-form-item label="药品经营许可证有效期" prop="drugLicenseExpiry">
              <el-date-picker
                v-model="form.drugLicenseExpiry"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="2类医疗器械备案证书上传" prop="medicalDevice2">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
              :headers="headers"
                :show-file-list="false"
                :on-success="(response, file) => handleFileSuccess(response, file, 'medicalDevice2')"
                :before-upload="beforeAvatarUpload">
                <div class="avatar-wrapper" v-if="form.medicalDevice2">
                  <img :src="form.medicalDevice2" class="avatar" width="200px">
<!--                  <div class="delete-mask" @click.stop="handleDelete7">-->
<!--                    <i class="el-icon-delete"></i>-->
<!--                  </div>-->
                  <div class="button-group">
                    <div class="preview-btn" @click.stop="previewImage(form.medicalDevice2)">
                      <i class="el-icon-zoom-in"></i>
                    </div>
                    <div v-if="!isViewMode" class="delete-btn" @click.stop="handleDelete7">
                      <i class="el-icon-delete"></i>
                    </div>
                  </div>
                </div>
                <!-- 未上传图片时显示的默认图标 -->
                <div v-else class="no-image-placeholder">
                  <span v-if="isViewMode">用户未上传</span>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </el-upload>
            </el-form-item>
            <el-col :sapn="24">
              <el-form-item label="2类器械经营范围" prop="medicalDevice2BusinessScope" style="margin-left: 5px">
                <el-input v-model="form.medicalDevice2BusinessScope" placeholder="请输入2类器械经营范围" type="textarea"/>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="2类器械生产备案编号" prop="medicalDevice2Code" style="margin-left: 5px">
                <el-input v-model="form.medicalDevice2Code" placeholder="请输入2类器械生产备案编号" />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-form-item label="2类医疗器械备案是否长期有效" prop="isMedicalDevice2ExpiryPermanent">
              <el-switch
                @change="switchChange()"
                v-model="medicalDevice2ExpiryValue"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
            <el-form-item label="2类医疗器械备案有效期" prop="medicalDevice2Expiry" v-if="!medicalDevice2ExpiryValue">
              <el-date-picker
                v-model="form.medicalDevice2Expiry"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="3类器械经营许可证上传" prop="medicalDevice3">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
              :headers="headers"
                :show-file-list="false"
                :on-success="(response, file) => handleFileSuccess(response, file, 'medicalDevice3')"
                :before-upload="beforeAvatarUpload">
                <div class="avatar-wrapper" v-if="form.medicalDevice3">
                  <img :src="form.medicalDevice3" class="avatar" width="200px">
<!--                  <div class="delete-mask" @click.stop="handleDelete2">-->
<!--                    <i class="el-icon-delete"></i>-->
<!--                  </div>-->
                  <div class="button-group">
                    <div class="preview-btn" @click.stop="previewImage(form.medicalDevice3)">
                      <i class="el-icon-zoom-in"></i>
                    </div>
                    <div v-if="!isViewMode" class="delete-btn" @click.stop="handleDelete2">
                      <i class="el-icon-delete"></i>
                    </div>
                  </div>
                </div>
                <!-- 未上传图片时显示的默认图标 -->
                <div v-else class="no-image-placeholder">
                  <span v-if="isViewMode">用户未上传</span>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </el-upload>
            </el-form-item>

            <el-form-item label="3类器械生产备案编号" prop="medicalDevice3Code" style="margin-left: 5px">
              <el-input v-model="form.medicalDevice3Code" placeholder="请输入3类器械生产备案编号" />
            </el-form-item>

            <el-col :sapn="24">
              <el-form-item label="3类器械经营范围" prop="medicalDevice3BusinessScope">
                <el-input v-model="form.medicalDevice3BusinessScope" placeholder="请输入3类器械经营范围" type="textarea"/>
              </el-form-item>
            </el-col>
          </el-col>

          <el-col :span="12">
            <el-form-item label="3类器械经营许可证是否长期有效" prop="isMedicalDevice3ExpiryPermanent">
              <el-switch
                @change="switchChange()"
                v-model="medicalDevice3ExpiryValue"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>

            <el-form-item label="3类器械经营许可证有效期" prop="medicalDevice3Expiry" v-if="!medicalDevice3ExpiryValue">
              <el-date-picker
                v-model="form.medicalDevice3Expiry"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

          <el-row>
            <el-col :span="12">
              <!-- 替换原有的食品经营许可证上传部分 -->
              <el-form-item label="食品经营许可证/备案凭证上传" prop="foodLicense">
                <!-- 显示已上传的图片 -->
                <div v-if="form.foodLicense && Array.isArray(form.foodLicense) && form.foodLicense.length > 0"
                     class="uploaded-images-preview">
                  <div v-for="(url, index) in form.foodLicense" :key="index" class="image-wrapper">
                    <img :src="url" class="uploaded-image" />
                    <div class="image-overlay">
                      <i class="el-icon-zoom-in" @click.stop="previewImage(url)"></i>
                      <i class="el-icon-delete" @click.stop="handleDeleteFoodLicense(index)" v-if="!isViewMode"></i>
                    </div>
                  </div>
                </div>

                <!-- 上传控件 - 始终显示 -->
                <div class="upload-area-wrapper">
                  <el-upload
                    class="avatar-uploader small-uploader"
                    :action="uploadUrl"
              :headers="headers"
                    :show-file-list="false"
                    :on-success="handleFoodLicenseSuccess"
                    :before-upload="beforeAvatarUpload"
                    :limit="3"
                    :on-exceed="handleFoodLicenseExceed"
                    :file-list="foodLicenseFileList">
                    <div class="no-image-placeholder small-placeholder">
                      <span v-if="isViewMode">用户未上传</span>
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </div>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="食品经营许可证/备案凭证编号" prop="foodCode" style="margin-left: 5px">
                <el-input v-model="form.foodCode" placeholder="请输入食品经营许可证/备案凭证编号" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="食品经营许可证/备案凭证是否长期有效" prop="isFoodLicenseExpiryPermanent">
                <el-switch
                  @change="switchChange()"
                  v-model="foodLicenseExpiryValue"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
              </el-form-item>
              <el-form-item label="食品经营许可证/备案凭证有效期" prop="foodLicenseExpiry" v-if="!foodLicenseExpiryValue">
                <el-date-picker
                  v-model="form.foodLicenseExpiry"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :sapn="24">
              <el-form-item label="食品经营许可证/备案凭证经营范围" prop="foodLicenseBusinessScope">
                <el-input v-model="form.foodLicenseBusinessScope" placeholder="请输入食品经营许可证/备案凭证经营范围" type="textarea"/>
              </el-form-item>
            </el-col>

          </el-row>
      </div>
      <el-divider content-position="left">店铺配置信息</el-divider>
      <el-col :span="12">
        <el-form-item label="网销报告" prop="reportUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
              :headers="headers"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="(response, file) => handleReportUploadSuccess(response, file, 'reportUrl')"
            :before-upload="beforeReportUpload"
            :disabled="!!form.reportUrl"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf"
          >
            <div class="report-file-wrapper" v-if="form.reportUrl">
              <img
                v-if="isImageFile(form.reportUrl)"
                :src="form.reportUrl"
                class="uploaded-file-thumb"
                width="100px"
                @click="viewReportFile('reportUrl')"
              />
              <div v-else class="document-file-icon" @click="viewReportFile('reportUrl')">
                <i class="el-icon-document"></i>
                <span class="file-name">{{ getFileName(form.reportUrl) }}</span>
              </div>
            </div>
            <div v-else class="upload-btn-wrapper">
              <el-button size="small" type="primary">点击上传</el-button>
            </div>
            <div v-if="form.reportUrl" class="report-preview-btn">
              <el-button size="mini" type="success" @click.stop="viewReportFile('reportUrl')">查看已上传文件</el-button>
              <el-button size="mini" type="danger" @click.stop="handleReportRemove('reportUrl')">删除</el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="备案" prop="filingUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
              :headers="headers"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="(response, file) => handleReportUploadSuccess(response, file, 'filingUrl')"
            :before-upload="beforeReportUpload"
            :disabled="!!form.filingUrl"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf"
          >
            <div class="report-file-wrapper" v-if="form.filingUrl">
              <img
                v-if="isImageFile(form.filingUrl)"
                :src="form.filingUrl"
                class="uploaded-file-thumb"
                width="100px"
                @click="viewReportFile('filingUrl')"
              />
              <div v-else class="document-file-icon" @click="viewReportFile('filingUrl')">
                <i class="el-icon-document"></i>
                <span class="file-name">{{ getFileName(form.filingUrl) }}</span>
              </div>
            </div>
            <div v-else class="upload-btn-wrapper">
              <el-button size="small" type="primary">点击上传</el-button>
            </div>
            <div v-if="form.filingUrl" class="report-preview-btn">
              <el-button size="mini" type="success" @click.stop="viewReportFile('filingUrl')">查看已上传文件</el-button>
              <el-button size="mini" type="danger" @click.stop="handleReportRemove('filingUrl')">删除</el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-form-item label="退货地址" prop="refundAddress">
        <el-input v-model="form.refundAddress" placeholder="请输入退货地址"/>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="退货电话" prop="refundPhone">
            <el-input v-model="form.refundPhone" placeholder="请输入退货电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="退货收货人" prop="refundConsignee">
            <el-input v-model="form.refundConsignee" placeholder="请输入退货收货人"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="寄件人电话" prop="sendPhone">
        <el-input v-model="form.sendPhone" placeholder="请输入寄件人电话"/>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品总数" prop="productCount">
            <el-input-number v-model="form.productCount"  :min="0" label="描述文字"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销量" prop="salesCount">
            <el-input-number v-model="form.salesCount"  :min="0" label="描述文字"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="累计金额" prop="totalMoney">
            <el-input-number v-model="form.totalMoney" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status" disabled>
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="parseInt(dict.dictValue)"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="false">
          <el-form-item label="分佣方式" prop="brokerageType">
            <el-radio-group v-model="form.brokerageType" disabled>
              <el-radio label="1" >每盒</el-radio>
              <el-radio label="2" >总价</el-radio>
            </el-radio-group>
          </el-form-item>
         </el-col>
      </el-row>
      <el-form-item label="配送方式" prop="shippingType" v-if="false">
        <el-checkbox-group v-model="form.shippingType" size="medium">
          <el-checkbox v-for="(item, index) in shippingTypeOptions" :key="index" :label="item.value"
                       :disabled="item.disabled">{{item.label}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-divider content-position="left">登录信息</el-divider>
      <el-form-item label="登录帐号" prop="account" v-if="title != '修改店铺管理'">
        <el-input v-model="form.account" placeholder="请输入登录帐号"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="close">关 闭</el-button>
    </div>

    <!-- 图片预览对话框，支持鼠标滚轮缩放 -->
    <el-dialog :visible.sync="imagePreviewVisible" width="1100px" append-to-body :modal-append-to-body="false" @close="onImagePreviewClose">
      <div slot="title">
        <span>图片预览</span>
        <span style="margin-left: 16px; font-size: 13px; color: #909399;">{{ previewScale }}%</span>
      </div>
      <div
        class="img-preview-body"
        @wheel.prevent="onPreviewWheel"
        @mousedown="onImgMouseDown"
        @mousemove="onImgMouseMove"
        @mouseup="onImgMouseUp"
        @mouseleave="onImgMouseUp"
      >
        <img
          :src="previewImageUrl"
          :style="{
            transform: `translate(${dragOffset.x}px, ${dragOffset.y}px) scale(${previewScale / 100})`,
            transition: isDragging ? 'none' : 'transform .15s',
            cursor: isDragging ? 'grabbing' : (previewScale > 100 ? 'grab' : 'default')
          }"
          style="max-width: 100%; max-height: 65vh; user-select: none;"
          @dragstart.prevent
        />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button-group>
          <el-button size="small" icon="el-icon-zoom-out" :disabled="previewScale <= 25" @click="zoomOut">缩小</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="resetZoom">复位</el-button>
          <el-button size="small" icon="el-icon-zoom-in" :disabled="previewScale >= 300" @click="zoomIn">放大</el-button>
        </el-button-group>
        <el-button size="small" style="float: right;" @click="imagePreviewVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
  </template>

<script>
import { addStore, updateStore, editData} from '@/api/store/store'
import { getConfigByKey } from '@/api/system/config'
import { getCitys } from '@/api/store/city'
import { getStoreInfo, businessLicenseCheck} from '@/api/hisStore/store'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      isViewMode: false, // 添加这一行
      reportFileList:[],
      fileList:[],
      previewImageUrl: '', // 添加预览图片URL
      imagePreviewVisible: false,// 添加图片预览对话框可见性控制
      previewScale: 100, // 预览图片缩放比例
      dragOffset: { x: 0, y: 0 }, // 拖动偏移
      isDragging: false, // 是否正在拖动
      dragStart: { x: 0, y: 0 }, // 拖动起始坐标
      originalForm: null, // 原始表单快照
      excludedFields: [
        'storeId', 'createTime', 'updateTime',
        'balance', 'totalMoney', 'salesCount', 'productCount',
        'qualificationUpdateTime', 'nextQualificationUpdateTime', 'daysDiff', 'remainDays',
        'permStatus', 'storeSeq', 'merchantId', 'selectableProductTypes',
        'doctorList', 'queryStoreId', 'hasErpInfo',
        'shippingType', 'brokerageType', 'brokerageRate', 'status',
        'password', 'licenseImages'
      ],
      agreementFields: [
        'settlementAgreement', 'settlementAgreementFileName', 'settlementAgreementCode',
        'settlementAgreementStart', 'settlementAgreementEnd', 'settlementAgreementExpiry', 'settlementAgreementFileType',
        'qualityAssuranceAgreement', 'qualityAssuranceAgreementFileName', 'qualityAssuranceAgreementCode',
        'qualityAssuranceAgreementStart', 'qualityAssuranceAgreementEnd', 'qualityAssuranceAgreementExpiry', 'qualityAssuranceAgreementFileType',
        'otherSpecialQualification', 'otherSpecialQualificationFileName', 'otherSpecialQualificationCode',
        'otherSpecialQualificationStart', 'otherSpecialQualificationEnd', 'otherSpecialQualificationExpiry', 'otherSpecialQualificationFileType',
        'titleNameOne', 'titleNameTwo', 'titleNameThree',
        'isEffectivePermanent1', 'isEffectivePermanent2', 'isEffectivePermanent3'
      ],
      switchMedicalValue: false,
      dialogVisible: false,
      switchValue: false,
      medicalDevice2ExpiryValue: false,
      medicalLicenseExpiryValue: false,
      title: '',
      statusOptions: [],
      citys: [],
      medicalMallConfig: {},
      drugLicenseValue:false,
      medicalDevice3ExpiryValue:false,
      foodLicenseExpiryValue:false,
      medicalDevice2BusinessScope:null,
      medicalDevice3BusinessScope:null,
      shippingTypeOptions: [{
        "label": "配送",
        "value": "1"
      }, {
        "label": "自提",
        "value": "2"
      }, {
        "label": "配送自提",
        "value": "3"
      }],
      // 表单参数
      form: {},
      // 食品经营许可证上传文件列表
      foodLicenseFileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/uploadOSS',
      // 上传鉴权头，上传前会刷新 Token
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      // 表单校验
      rules: {
        drugLicenseBusinessScope: [
          { required: true, message: "药品经营许可证范围不能为空", trigger: "blur" }
        ],
        businessLicense: [
          { required: true, message: '营业执照不能为空', trigger: 'blur' }
        ],
        businessCode:[
          { required: true, message: '营业执照编号不能为空', trigger: 'blur' }
        ],
        drugLicense: [
          { required: true, message: '药品经营许可证不能为空', trigger: 'blur' }
        ],
        drugLicenseExpiry: [
          { required: true, message: '药品经营许可证有效期不能为空', trigger: 'blur' }
        ],
        drugCode: [
          { required: true, message: '药品经营许可证编号不能为空', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '店铺名称不能为空', trigger: 'blur' }
        ],
        fullName: [
          { required: true, message: '店铺名称不能为空', trigger: 'blur' }
        ],
        businessLicenseExpire: [
          { required: true, message: '营业执照失效日期不能为空', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '店铺LOGO不能为空', trigger: 'blur' }
        ],
        cityIds: [
          { required: true, message: '所属城市不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        licenseImages: [
          { required: true, message: '资质证书不能为空', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '登录账号不能为空', trigger: 'blur' }
        ],
        refundPhone: [
          { required: true, message: '退货电话不能为空', trigger: 'blur' }
        ],
        refundAddress: [
          { required: true, message: '退货地址不能为空', trigger: 'blur' }
        ],
        refundConsignee: [
          { required: true, message: '退货收货人不能为空', trigger: 'blur' }
        ],
        sendPhone: [
          { required: true, message: '寄件人电话不能为空', trigger: 'blur' }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
            required: true
          }
        ],
        // 新增字段校验规则
        enterpriseShortName: [
          { required: true, message: '企业简称不能为空', trigger: 'blur' }
        ],
        enterpriseFullName: [
          { required: true, message: '企业全称不能为空', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' }
        ],
        enterpriseAddress: [
          { required: true, message: '企业地址不能为空', trigger: 'blur' }
        ],
        legalPersonName: [
          { required: true, message: '法人姓名不能为空', trigger: 'blur' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }
        ],
        businessScope: [
          { required: true, message: '营业范围不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        // 添加新的验证规则
        // drugScopeHasFrozen: [
        //   { required: true, message: "请选择药品经营许可证范围是否包含冷冻/冷藏", trigger: "change" }
        // ],
      }
    }
  },
  created() {
    this.getCitys()
    this.handleUpdate()
    getConfigByKey('medicalMall.func.switch').then(response => {
      if (response.data && response.data.configValue) {
        this.medicalMallConfig = JSON.parse(response.data.configValue)
      }
    })
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // 处理食品经营许可证上传成功
    handleFoodLicenseSuccess(response, file) {
      if (response.code === 200) {
        // 确保 foodLicense 是数组格式进行处理
        let currentFiles = [];
        if (this.form.foodLicense) {
          if (typeof this.form.foodLicense === 'string') {
            currentFiles = this.form.foodLicense.split(',').filter(url => url.trim() !== '');
          } else if (Array.isArray(this.form.foodLicense)) {
            currentFiles = this.form.foodLicense;
          }
        }
        // 检查是否超过最大上传数量
        if (currentFiles.length >= 3) {
          this.$message.warning('最多只能上传3张图片');
          return;
        }
        // 添加新上传的图片URL到数组中
        currentFiles.push(response.url);
        // 更新表单数据
        this.$set(this.form, 'foodLicense', currentFiles);
        // 更新上传文件列表
        this.foodLicenseFileList.push(file);
        // 更新视图
        this.$forceUpdate();
      } else {
        this.msgError(response.msg);
      }
    },
    // 处理超出最大上传数量限制
    handleFoodLicenseExceed(files, fileList) {
      // 检查当前实际的图片数量
      let currentCount = 0;
      if (this.form.foodLicense) {
        if (typeof this.form.foodLicense === 'string') {
          currentCount = this.form.foodLicense.split(',').filter(url => url.trim() !== '').length;
        } else if (Array.isArray(this.form.foodLicense)) {
          currentCount = this.form.foodLicense.length;
        }
      }

      // 只有当实际图片数量达到上限时才提示
      if (currentCount >= 3) {
        this.$message.warning('最多只能上传3张图片');
      }
    },
    // 删除指定索引的食品经营许可证图片
    handleDeleteFoodLicense(index) {
      this.$confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let files = [];
        if (typeof this.form.foodLicense === 'string' && this.form.foodLicense) {
          files = this.form.foodLicense.split(',').filter(url => url.trim() !== '');
        } else if (Array.isArray(this.form.foodLicense)) {
          files = this.form.foodLicense;
        }
        files.splice(index, 1);
        this.$set(this.form, 'foodLicense', files);
        // 重置上传文件列表
        this.foodLicenseFileList = [];
        this.$forceUpdate();
        this.$message.success('图片已删除');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 添加图片预览方法
    previewImage(url) {
      this.previewImageUrl = url;
      this.previewScale = 100;
      this.imagePreviewVisible = true;
    },

    // 店铺logo
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.form.logoUrl = res.url
        self.$forceUpdate()
      } else {
        this.msgError(res.msg)
      }
    },
    beforeAvatarUpload(file) {
      this.headers.Authorization = 'Bearer ' + getToken()
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isLt1M
    },

    // 图片预览缩放相关
    onImagePreviewClose() {
      this.previewScale = 100;
      this.dragOffset = { x: 0, y: 0 };
      this.isDragging = false;
      this.imagePreviewVisible = false;
    },
    zoomOut() {
      if (this.previewScale > 25) {
        this.previewScale = Math.max(25, this.previewScale - 25);
        this.dragOffset = { x: 0, y: 0 };
      }
    },
    zoomIn() {
      if (this.previewScale < 300) {
        this.previewScale = Math.min(300, this.previewScale + 25);
      }
    },
    resetZoom() {
      this.previewScale = 100;
      this.dragOffset = { x: 0, y: 0 };
    },
    onPreviewWheel(e) {
      if (e.deltaY < 0) {
        this.zoomIn()
      } else {
        this.zoomOut()
      }
    },
    onImgMouseDown(e) {
      this.isDragging = true;
      this.dragStart = { x: e.clientX - this.dragOffset.x, y: e.clientY - this.dragOffset.y };
    },
    onImgMouseMove(e) {
      if (!this.isDragging) return;
      this.dragOffset = {
        x: e.clientX - this.dragStart.x,
        y: e.clientY - this.dragStart.y
      };
    },
    onImgMouseUp() {
      this.isDragging = false;
    },

    // 网销报告/备案文件相关
    isImageFile(url) {
      if (!url) return false;
      return /\.(jpg|jpeg|png|gif|bmp|webp)(\?|$)/i.test(url);
    },
    getFileName(url) {
      if (!url) return '';
      const parts = url.split('/');
      return parts[parts.length - 1] || url;
    },
    handleReportUploadSuccess(response, file, field) {
      if (response.code === 200) {
        this.$set(this.form, field, response.url);
        this.$message.success(`文件：${file.name}上传成功`);
        this.$forceUpdate();
      } else {
        this.msgError(response.msg);
      }
    },
    handleReportRemove(field) {
      this.$set(this.form, field, '');
      this.$message.info('文件已移除');
    },
    beforeReportUpload(file) {
      this.headers.Authorization = 'Bearer ' + getToken()
      const acceptTypes = [
        'image/jpeg', 'image/png', 'image/gif', 'image/bmp',
        'application/pdf'
      ];
      if (!acceptTypes.includes(file.type)) {
        this.$message.error('仅支持 JPG/PNG/GIF/BMP 图片或 PDF 文件');
        return false;
      }
      const maxSize = 10 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过 10MB');
        return false;
      }
      return true;
    },
    viewReportFile(field) {
      const url = this.form[field];
      if (!url) {
        this.$message.warning('暂无文件');
        return;
      }
      if (this.isImageFile(url)) {
        this.previewImageUrl = url;
        this.previewScale = 100;
        this.imagePreviewVisible = true;
      } else {
        window.open(url, '_blank');
      }
    },

    // 表单变更检测
    fieldsEqual(a, b) {
      if (a === b) return true;
      if (a == null && b == null) return true;
      if (a == null || b == null) return false;
      if (Array.isArray(a) && Array.isArray(b)) {
        if (a.length !== b.length) return false;
        return a.every((v, i) => this.fieldsEqual(v, b[i]));
      }
      if ((a === '' && b === null) || (a === null && b === '')) return true;
      return String(a) === String(b);
    },
    getChangedFields(original, current) {
      const changed = [];
      for (const key of Object.keys(original)) {
        if (this.excludedFields.indexOf(key) !== -1) continue;
        if (!this.fieldsEqual(original[key], current[key])) {
          changed.push(key);
        }
      }
      return changed;
    },

    //关闭
    close() {
      this.$store.dispatch('tagsView/delView', this.$route)
      // 检查当前路径，避免重复跳转
      if (this.$route.path !== '/index') {
        this.$router.replace({ path: '/index' })
      }
    },
    // 通用文件上传成功处理函数
    handleFileSuccess(response, file, field) {
      if (response.code === 200) {
        this.$set(this.form, field, response.url);
        // 如果是营业执照上传，进行校验
        if (field === 'businessLicense') {
          businessLicenseCheck({ imageUrl: response.url }).then(checkResponse => {
            if (checkResponse.data.flag === false) {
              this.$message.error(checkResponse.data.message || '营业执照校验失败');
              // 清除已上传的营业执照图片
              this.$set(this.form, field, '');
              this.$forceUpdate();
            }else{
              // 检查成功，回填数据
              this.form.legalPersonName = checkResponse.data.person; // 法人姓名
              this.form.unifiedSocialCreditCode = checkResponse.data.regNum; // 统一社会信用代码
              this.form.businessScope = checkResponse.data.businessStr; // 营业范围
              this.form.businessCode = checkResponse.data.regNum; // 营业执照编号
            }
          }).catch(error => {
            this.$message.error('营业执照校验异常');
            this.$set(this.form, field, '');
            this.$forceUpdate();
          });
        }
        this.$forceUpdate();
      } else {
        this.msgError(response.msg);
      }
    },
    // 表单重置
    reset() {
      this.switchValue = false;
      this.switchMedicalValue=false;
      this.form = {
        foodLicense: [],               // 食品经营许可证文件,用户要求是多张，这里采用数组
        storeId: null,
        cityIds: null,
        storeName: null,
        descs: null,
        logoUrl: null,
        address: null,
        lng: null,
        lat: null,
        phone: null,
        licenseImages: null,
        productCount: null,
        status: 0,
        createTime: null,
        updateTime: null,
        salesCount: null,
        balance: null,
        totalMoney: null,
        isAudit: 0,
        account: null,
        password: null,
        shippingType: ["1"],
        brokerageType: "1",
        brokerageRate: 0,
        fullName: null,
        // 重置新增字段
        enterpriseShortName: null,        // 企业简称
        enterpriseFullName: null,         // 企业全称
        contactPhone: null,               // 联系电话
        enterpriseAddress: null,          // 企业地址
        legalPersonName: null,            // 法人姓名
        unifiedSocialCreditCode: null,    // 统一社会信用代码
        businessScope: null,              // 营业范围
        // 重置证书相关字段
        businessLicense: null,                    // 营业执照文件
        businessLicenseExpire: null,              // 营业执照失效日期
        drugLicense: null,             // 药品经营许可证有效期
        drugLicenseExpiry: null,               // 药品经营许可证文件
        // 医疗器械相关证书
        medicalDevice1: null,          // 一类医疗器械备案证书
        medicalDevice1Expiry: null,        // 二类医疗器械备案有效期
        medicalDevice2: null,          // 二类器械生产备案文件
        medicalDevice2Expiry: null,        // 一类生产备案有效期
        medicalDevice3: null,         // 三类器械经营许可证文件
        medicalDevice3Expiry: null,       // 三类器械经营许可证有效期
        // 其他许可证相关字段
        foodLicenseExpiry: null,             // 食品经营许可证有效期
        medicalLicense: null,  // 医疗机构执业许可证文件
        medicalLicenseExpiry: null, // 医疗机构执业许可证有效期
        settlementAgreement: null,  //其它资质-入驻协议
        settlementAgreementExpiry: null,//其它资质-有效期
        qualityAssuranceAgreement: null,//质量保证协议
        qualityAssuranceAgreementExpiry: null,//质量保证协议有效期
        otherSpecialQualification: null,//其它特殊资质
        otherSpecialQualificationExpiry: null,//其它特殊资质有效期
        businessCode: null,
        drugCode:null,
        drugLicenseBusinessScope: null,
        drugScopeHasFrozen: 0,
        medicalDevice1Code:null,
        medicalDevice2Code:null,
        medicalDevice3Code:null,
        foodCode:null,
        medicalCode:null,
        otherSpecialQualificationCode:null,
        qualityAssuranceAgreementCode:null,
        settlementAgreementCode: null,
        medicalDevice2BusinessScope: null,
        medicalDevice3BusinessScope: null,
        foodLicenseBusinessScope: null,
      };
      this.resetForm('form')
      this.originalForm = null;
    },
    //所有的日期控件校验
    checkDate(){
      const currentDate = new Date();
      //营业执照证
      if(!this.switchValue){
        const businessLicenseExpireEndDate = new Date(this.form.businessLicenseExpire[1]);
        if (businessLicenseExpireEndDate < currentDate) {
          this.$message.warning('营业执照证已过期，无法提交');
          return false;
        }
    }
      //药品经营许
      const drugLicenseExpiryEndDate = new Date(this.form.drugLicenseExpiry[1]);
      if (drugLicenseExpiryEndDate < currentDate) {
        this.$message.warning('药品经营许可证已过期，无法提交');
        return false;
      }
      //2类
      if(!!this.form.medicalDevice2 && !this.medicalDevice2ExpiryValue){
        if(!this.form.medicalDevice2Expiry){
          this.$message.warning('2类医疗器械备案有效期不为空！');
          return false;
        }else{
          const medicalDevice2ExpiryEndDate = new Date(this.form.medicalDevice2Expiry[1]);
          if (medicalDevice2ExpiryEndDate < currentDate) {
            this.$message.warning('2类医疗器械可证已过期，无法提交');
            return false;
          }
        }
      }
      //3类医疗器械备案
      if(!!this.form.medicalDevice3 && !this.medicalDevice3ExpiryValue){
        if(!this.form.medicalDevice3Expiry){
          this.$message.warning('3类医疗器械备案有效期不为空！');
          return false;
        }else{
          const medicalDevice3ExpiryEndDate = new Date(this.form.medicalDevice3Expiry[1]);
          if (medicalDevice3ExpiryEndDate < currentDate) {
            this.$message.warning('3类医疗器械可证已过期，无法提交');
            return false;
          }
        }
      }
      //食品经营许可证
      if(this.form.foodLicense.length > 0 && !this.foodLicenseExpiryValue){
        if(!this.form.foodLicenseExpiry){
          this.$message.warning('食品经营许可证/备案凭证有效期不为空！');
          return false;
        }else{
          const foodLicenseExpiryEndDate = new Date(this.form.foodLicenseExpiry[1]);
          if (foodLicenseExpiryEndDate < currentDate) {
            this.$message.warning('食品经营许可证/备案凭证已过期，无法提交');
            return false;
          }
        }
      }
      return true;
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(!this.checkDate()){
            return;
          }
          const isEdit = this.form.storeId != null;
          if (isEdit && this.originalForm) {
            const changedFields = this.getChangedFields(this.originalForm, this.form);
            if (changedFields.length === 0) {
              this.$message.warning("未检测到任何修改，无需提交");
              return;
            }
          }
          // 营业执照是必填项，直接进行校验
          businessLicenseCheck({ imageUrl: this.form.businessLicense }).then(checkResponse => {
            if (checkResponse.data.flag === false) {
              this.$message.error(checkResponse.data.message || '营业执照校验失败');
              return;
            }
            // 校验通过，继续提交流程
            this.submitFormData();
          }).catch(error => {
            this.$message.error('营业执照校验异常');
          });
        }
      });
    },

    /** 提交按钮 */
    submitFormData() {
      const formData = Object.assign({}, this.form);
      // 特别处理 foodLicense 字段，将其转换为逗号分隔的字符串
      if (Array.isArray(formData.foodLicense)) {
        formData.foodLicense = formData.foodLicense.join(',');
      } else if (!formData.foodLicense) {
        formData.foodLicense = ''; // 确保空值处理
      }
      //空值处理
      if(formData.foodLicenseExpiry == null){
        formData.foodLicenseExpiryEnd = null;
        formData.foodLicenseExpiryStart = null;
      }
      if(formData.medicalDevice2Expiry == null){
        formData.medicalDevice2ExpiryStart = null;
        formData.medicalDevice2ExpiryEnd = null;
      }
      if(formData.medicalDevice3Expiry == null){
        formData.medicalDevice3ExpiryStart = null;
        formData.medicalDevice3ExpiryEnd = null;
      }
      // 处理城市ID
      if (formData.cityIds) {
        formData.cityIds = formData.cityIds.toString();
      }
      // 处理配送方式
      if (formData.shippingType) {
        formData.shippingType = formData.shippingType.toString()
      }
      // 处理日期范围字段
      const dateRangeFields = [
        'drugLicenseExpiry',
        'medicalDevice2Expiry',
        'medicalDevice1Expiry',
        'medicalDevice3Expiry',
        'foodLicenseExpiry',
        'medicalLicenseExpiry',
        'businessLicenseExpire'
      ]
      dateRangeFields.forEach(field => {
        if (formData[field] && formData[field].length === 2) {
          formData[`${field}Start`] = formData[field][0]
          formData[`${field}End`] = formData[field][1]
        }
      })
      //其他上传的日期检查
      const agreementFields = [
        {
          expiryField: 'settlementAgreementExpiry',
          startField: 'settlementAgreementStart',
          endField: 'settlementAgreementEnd',
          agreementField: 'settlementAgreement',
          permanentFlag: this.form.isEffectivePermanent1 == 1,
          message: '其它资质-入驻协议，有效期开始日期或结束日期不能为空！'
        },
        {
          expiryField: 'qualityAssuranceAgreementExpiry',
          startField: 'qualityAssuranceAgreementStart',
          endField: 'qualityAssuranceAgreementEnd',
          agreementField: 'qualityAssuranceAgreement',
          permanentFlag: this.form.isEffectivePermanent2 == 1,
          message: '质量保证协议，有效期开始日期或结束日期不能为空！'
        },
        {
          expiryField: 'otherSpecialQualificationExpiry',
          startField: 'otherSpecialQualificationStart',
          endField: 'otherSpecialQualificationEnd',
          agreementField: 'otherSpecialQualification',
          permanentFlag: this.form.isEffectivePermanent3 == 1,
          message: '其它特殊资质，有效期开始日期或结束日期不能为空！'
        }
      ]
      for (const field of agreementFields) {
        if (field.permanentFlag) continue;
        if (formData[field.expiryField] && formData[field.expiryField].length === 2) {
          formData[field.startField] = formData[field.expiryField][0]
          formData[field.endField] = formData[field.expiryField][1]
        } else {
          if (formData[field.agreementField] != null) {
            return this.$message.warning(field.message)
          }
        }
      }

      // 优化开关值转换逻辑，使用更简洁的方式设置永久有效标志位
      formData.isBusinessLicensePermanent = this.switchValue ? 1 : 0
      formData.isMedicalDevice1ExpiryPermanent = this.switchMedicalValue ? 1 : 0
      formData.isMedicalDevice2ExpiryPermanent = this.medicalDevice2ExpiryValue ? 1 : 0
      formData.isMedicalLicenseExpiryPermanent = this.medicalLicenseExpiryValue ? 1 : 0
      // 补充缺失的永久有效标志位设置
      formData.isDrugLicensePermanent = this.drugLicenseValue ? 1 : 0
      formData.isMedicalDevice3ExpiryPermanent = this.medicalDevice3ExpiryValue ? 1 : 0
      formData.isFoodLicenseExpiryPermanent = this.foodLicenseExpiryValue ? 1 : 0

      if (formData.storeId != null) {
        updateStore(formData).then(response => {
          this.msgSuccess('修改成功')
          this.originalForm = JSON.parse(JSON.stringify(this.form))
          this.open = false
        })
      } else {
        addStore(formData).then(response => {
          this.msgSuccess('新增成功')
          this.open = false
        })
      }
    },
    //城市控制
    handleCityChange(value) {
      var nodes = this.$refs.citySelect.getCheckedNodes()
      this.form.address = nodes[0].pathLabels[0] + nodes[0].pathLabels[1] + nodes[0].pathLabels[2]
      this.form.cityIds = value.toString()
    },
    getCitys() {
      getCitys().then(res => {
        this.loading = false
        this.citys = res.data
      })
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset()
      getStoreInfo().then(response => {
        const data = response.data || {};

        if (data.brokerageType) {
          data.brokerageType = data.brokerageType.toString();
        }
        if (data.drugScopeHasFrozen === undefined) {
          data.drugScopeHasFrozen = 0;
        }

        // 空值保护，避免 split 报错导致后续日期等字段无法回填
        data.shippingType = data.shippingType ? data.shippingType.split(',') : [];
        data.cityIds = data.cityIds ? data.cityIds.split(',').map(Number) : [];

        const dateFields = [
          'drugLicenseExpiry',
          'medicalDevice1Expiry',
          'medicalDevice2Expiry',
          'medicalDevice3Expiry',
          'foodLicenseExpiry',
          'medicalLicenseExpiry',
          'businessLicenseExpire'
        ];
        dateFields.forEach(field => {
          const startField = field + 'Start';
          const endField = field + 'End';
          if (data[startField] && data[endField]) {
            data[field] = [data[startField], data[endField]];
          }
        });

        if (data.settlementAgreementStart && data.settlementAgreementEnd) {
          data.settlementAgreementExpiry = [data.settlementAgreementStart, data.settlementAgreementEnd];
        }
        if (data.qualityAssuranceAgreementStart && data.qualityAssuranceAgreementEnd) {
          data.qualityAssuranceAgreementExpiry = [data.qualityAssuranceAgreementStart, data.qualityAssuranceAgreementEnd];
        }
        if (data.otherSpecialQualificationStart && data.otherSpecialQualificationEnd) {
          data.otherSpecialQualificationExpiry = [data.otherSpecialQualificationStart, data.otherSpecialQualificationEnd];
        }

        if (data.foodLicense) {
          if (typeof data.foodLicense === 'string') {
            data.foodLicense = data.foodLicense.split(',').filter(url => url.trim() !== '');
          } else if (!Array.isArray(data.foodLicense)) {
            data.foodLicense = [];
          }
        } else {
          data.foodLicense = [];
        }

        this.form = data;

        this.switchValue = this.form.isBusinessLicensePermanent == 1;
        this.switchMedicalValue = this.form.isMedicalDevice1ExpiryPermanent == 1;
        this.medicalDevice2ExpiryValue = this.form.isMedicalDevice2ExpiryPermanent == 1;
        this.medicalLicenseExpiryValue = this.form.isMedicalLicenseExpiryPermanent == 1;
        this.foodLicenseExpiryValue = this.form.isFoodLicenseExpiryPermanent == 1;
        this.medicalDevice3ExpiryValue = this.form.isMedicalDevice3ExpiryPermanent == 1;
        this.drugLicenseValue = this.form.isDrugLicensePermanent == 1;

        this.open = true;
        this.title = '修改店铺';
        this.reportFileList = this.urlToFileList(this.form.reportUrl);
        this.fileList = this.urlToFileList(this.form.filingUrl);
        this.originalForm = JSON.parse(JSON.stringify(this.form));
      })
    },
    //长期有效营业执照选择
    switchChange(){
      // console.log(this.form.isBusinessLicensePermanent);
    },
    // 优化所有图片的删除逻辑，避免冗余代码、阅读困难
    handleDeleteLogo() {
      this.deleteImage('logoUrl', '图片');
    },
    handleDelete2() {
      this.deleteImage('medicalDevice3', '3类器械经营许可证');
    },
    handleDelete3() {
      this.deleteImage('foodLicense', '食品经营许可证');
    },
    handleDelete4() {
      this.deleteImage('medicalLicense', '医疗机构执业许可证');
    },
    handleDelete5() {
      this.deleteImage('businessLicense', '营业执照');
    },
    handleDelete6() {
      this.deleteImage('drugLicense', '药品经营许可证');
    },
    handleDelete7() {
      this.deleteImage('medicalDevice2', '2类医疗器械备案证书');
    },
    deleteImage(fieldName, displayName) {
      this.isDeleting = true; // 临时禁用上传组件
      this.$confirm(`确定要删除${displayName}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form[fieldName] = ''; // 清空图片URL
        this.$message.success(`${displayName}已删除`);
      }).catch(() => {
        this.$message.info('已取消删除');
      }).finally(() => {
        this.isDeleting = false; // 无论操作结果，恢复上传组件可用
        this.$forceUpdate(); // 强制刷新确保状态同步
      });
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 将逗号分隔的URL字符串转换为文件对象数组
    urlToFileList(urlStr) {
      if (!urlStr) return [];
      return urlStr.split(',').map(url => {
        const fileName = url.substring(url.lastIndexOf('/') + 1);
        return {
          name: fileName,
          url: url,
          uid: Date.now() + Math.random().toString(36).substr(2, 9) // 生成唯一ID
        };
      });
    },

  }
}
</script>

<style>
/* 上传区域包装器样式 */
.upload-area-wrapper {
  display: inline-block;
  margin-top: 10px;
}

/* 小尺寸上传控件样式 */
.small-uploader .small-placeholder {
  width: 100px;
  height: 100px;
}

.small-uploader .avatar-uploader-icon {
  font-size: 28px;
  line-height: 100px;
}

/* 已上传图片样式 - 更大尺寸 */
.uploaded-images-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.image-wrapper {
  position: relative;
  display: inline-block;
}

.uploaded-image {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #ddd;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 6px;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-overlay i {
  color: white;
  cursor: pointer;
  font-size: 20px;
}

/* LOGO上传区域样式优化 */
.avatar-wrapper {
  position: relative;
  display: inline-block;
}
.avatar {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}
.delete-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  opacity: 0;
  cursor: pointer;
  transition: opacity 0.3s ease;
  border-radius: 4px;
}
.avatar-wrapper:hover .delete-mask {
  opacity: 1;
}
.avatar-uploader {
  display: inline-block;
}

/* 并排按钮样式 */
.button-group {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
}

.preview-btn,
.delete-btn {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.preview-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.delete-btn:hover {
  background-color: #f56c6c;
}

/* 无图片占位符样式 */
.no-image-placeholder {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  background-color: #fafafa;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
}

.avatar {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.thumbnail-wrapper {
  position: relative;
  display: inline-block;
}

.thumbnail-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.thumbnail-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 4px;
}

.thumbnail-wrapper:hover .thumbnail-overlay {
  opacity: 1;
}

.thumbnail-overlay i {
  color: white;
  cursor: pointer;
  font-size: 14px;
}

.report-file-wrapper {
  display: inline-block;
}

.uploaded-file-thumb {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  vertical-align: middle;
}

.document-file-icon {
  width: 150px;
  height: 100px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  cursor: pointer;
  vertical-align: middle;
}

.document-file-icon .el-icon-document {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 4px;
}

.document-file-icon .file-name {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
  text-align: center;
}

.upload-btn-wrapper {
  display: inline-block;
}

.report-preview-btn {
  margin-top: 8px;
}

.img-preview-body {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  min-height: 200px;
}
</style>
