<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="药品名称" prop="medicineName">
        <el-input
          v-model="queryParams.medicineName"
          placeholder="请输入药品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入规格"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入当前价格"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺地址" prop="storeAddress">
        <el-input
          v-model="queryParams.storeAddress"
          placeholder="请输入店铺地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:recommendation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:recommendation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:recommendation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:recommendation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recommendationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="药品图片" align="center" prop="images" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="轮播图片" align="center" prop="imageUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="药品名称" align="center" prop="medicineName" :show-overflow-tooltip="true" />
      <el-table-column label="药品类型" align="center" prop="medicineType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.medicine_type" :value="scope.row.medicineType"/>
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" prop="specification" :show-overflow-tooltip="true" />
      <el-table-column label="当前价格" align="center" prop="price">
        <template slot-scope="scope">
          <span>¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="originalPrice">
        <template slot-scope="scope">
          <span v-if="scope.row.originalPrice">¥{{ scope.row.originalPrice }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="已售数量" align="center" prop="soldQuantity" />
      <el-table-column label="销售类型" align="center" prop="salesType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sales_type" :value="scope.row.salesType"/>
        </template>
      </el-table-column>
      <el-table-column label="适用症状" align="center" prop="indications" :show-overflow-tooltip="true" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" :show-overflow-tooltip="true" />

      <el-table-column label="专家推荐" align="center" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.expertId">
            <div style="font-weight: bold;">{{ scope.row.expertName }}</div>
            <div style="font-size: 12px; color: #999;">{{ scope.row.expertExpert }}</div>
          </div>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="推荐店铺" align="center" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.storeName">
            <div style="font-weight: bold;">{{ scope.row.storeName }}</div>
            <div style="font-size: 12px; color: #999;">{{ scope.row.storeAddress || '-' }}</div>
          </div>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:recommendation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:recommendation:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品推荐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <!-- 药品图片上传 -->
            <el-form-item label="药品图片" prop="images">
              <el-upload
                ref="medicineUpload"
                class="upload-demo"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :auto-upload="false"
                :file-list="medicineFileList"
                :on-change="handleMedicineFileChange"
                :on-remove="handleMedicineFileRemove"
                :on-success="handleMedicineUploadSuccess"
                :before-upload="beforeAvatarUpload"
                list-type="picture-card"
                :limit="1"
                accept=".jpg,.jpeg,.png,.gif,.bmp"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip" style="margin-top: 10px;">
                  支持jpg、jpeg、png、gif、bmp格式，单张图片不超过2MB，只能上传1张
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="药品图片" prop="images">
              <image-upload
                v-model="form.images"
                :limit="10"
                :file-size="2"
                :is-show-tip="true"
                :accept="['.jpg', '.jpeg', '.png', '.gif', '.bmp']"
                help-text="支持jpg、jpeg、png、gif、bmp格式，单张图片不超过2MB，最多上传10张"
              />
            </el-form-item>

            <!-- 轮播图片上传 -->
            <el-form-item label="轮播图片" prop="imageUrl">
              <el-upload
                ref="carouselUpload"
                class="upload-demo"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :auto-upload="false"
                :file-list="carouselFileList"
                :on-change="handleCarouselFileChange"
                :on-remove="handleCarouselFileRemove"
                :on-success="handleCarouselUploadSuccess"
                :before-upload="beforeAvatarUpload"
                list-type="picture-card"
                :limit="5"
                multiple
                accept=".jpg,.jpeg,.png,.gif,.bmp"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip" style="margin-top: 10px;">
                  支持jpg、jpeg、png、gif、bmp格式，单张图片不超过2MB，最多上传5张用于首页轮播展示
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="轮播图片" prop="imageUrl">
              <image-upload
                v-model="form.imageUrl"
                :limit="10"
                :file-size="2"
                :is-show-tip="true"
                :accept="['.jpg', '.jpeg', '.png', '.gif', '.bmp']"
                help-text="支持jpg、jpeg、png、gif、bmp格式，单张图片不超过2MB，最多上传10张"
              />
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <el-form-item label="药品名称" prop="medicineName">
                  <el-input v-model="form.medicineName" placeholder="请输入药品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="药品类型" prop="medicineType">
                  <el-select v-model="form.medicineType" placeholder="请选择药品类型" clearable style="width: 100%;">
                    <el-option
                      v-for="dict in dict.type.medicine_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="规格" prop="specification">
                  <el-input v-model="form.specification" placeholder="请输入规格" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销售类型" prop="salesType">
                  <el-select v-model="form.salesType" placeholder="请选择销售类型" clearable style="width: 100%;">
                    <el-option
                      v-for="dict in dict.type.sales_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="当前价格" prop="price">
                  <el-input v-model="form.price" placeholder="请输入当前价格" type="number" min="0">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原价" prop="originalPrice">
                  <el-input v-model="form.originalPrice" placeholder="请输入原价" type="number" min="0">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="已售数量" prop="soldQuantity">
                  <el-input v-model="form.soldQuantity" placeholder="请输入已售数量" type="number" min="0" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生产厂家" prop="manufacturer">
                  <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="贮藏方式" prop="storageMethod">
                  <el-input v-model="form.storageMethod" placeholder="请输入贮藏方式" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="有效期" prop="expiryDate">
                  <el-input v-model="form.expiryDate" placeholder="请输入有效期" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="适用症状" prop="indications">
              <el-input v-model="form.indications" type="textarea" placeholder="请输入适用症状" />
            </el-form-item>

            <el-form-item label="用法用量" prop="usageDosage">
              <el-input v-model="form.usageDosage" type="textarea" placeholder="请输入用法用量" />
            </el-form-item>

            <el-form-item label="注意事项" prop="precautions">
              <el-input v-model="form.precautions" type="textarea" placeholder="请输入注意事项" />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="专家推荐" name="expert">
            <el-form-item label="推荐专家" prop="expertId">
              <el-select
                v-model="form.expertId"
                placeholder="请选择推荐专家"
                clearable
                filterable
                style="width: 100%;"
              >
                <el-option
                  v-for="expert in expertList"
                  :key="expert.expertId"
                  :label="expert.realName + ' - ' + expert.expert"
                  :value="expert.expertId"
                />
              </el-select>
              <div style="font-size: 12px; color: #999; margin-top: 5px;">
                提示：选择为您推荐药品的专家
              </div>
            </el-form-item>

            <el-form-item label="推荐理由" prop="recommendReason">
              <el-input v-model="form.recommendReason" type="textarea" placeholder="请输入专家推荐理由" rows="4" />
            </el-form-item>

            <el-form-item label="推荐时间" prop="recommendTime">
              <el-date-picker
                v-model="form.recommendTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择推荐时间"
                style="width: 100%;"
              />
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="推荐店铺" name="store">
            <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="storePhone">
                  <el-input v-model="form.storePhone" placeholder="请输入店铺电话" />
                </el-form-item>
              </el-col>
            </el-row>

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

            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="form.businessHours" placeholder="例如：8:00-22:00" />
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="form.longitude" placeholder="请输入经度" type="number">
                    <template slot="append">°</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input v-model="form.latitude" placeholder="请输入纬度" type="number">
                    <template slot="append">°</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注" prop="storeRemark">
              <el-input v-model="form.storeRemark" type="textarea" placeholder="请输入店铺备注信息" rows="3" />
            </el-form-item>

            <div style="font-size: 12px; color: #999; margin-top: 10px;">
              <i class="el-icon-info"></i> 提示：经纬度用于地图定位，如不清楚可留空
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecommendation, getRecommendation, delRecommendation, addRecommendation, updateRecommendation } from "@/api/system/recommendation";
import { listExperts } from "@/api/vet/experts";
import { getToken } from "@/utils/auth";

export default {
  name: "Recommendation",
  dicts: ['medicine_type', 'sales_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品推荐表格数据
      recommendationList: [],
      // 专家列表
      expertList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的标签页
      activeTab: "basic",

      // 药品图片文件列表（单张）
      medicineFileList: [],
      // 轮播图片文件列表（最多5张）
      carouselFileList: [],

      // 上传URL
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传的请求头
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        medicineName: undefined,
        medicineType: undefined,
        specification: undefined,
        price: undefined,
        originalPrice: undefined,
        soldQuantity: undefined,
        indications: undefined,
        usageDosage: undefined,
        precautions: undefined,
        storageMethod: undefined,
        expiryDate: undefined,
        manufacturer: undefined,
        salesType: null,
        expertId: undefined,
        recommendReason: undefined,
        recommendTime: undefined,
        storeName: undefined,
        storeAddress: undefined,
      },

      // 表单参数
      form: {
        id: undefined,
        medicineName: undefined,
        medicineType: undefined,
        specification: undefined,
        price: undefined,
        originalPrice: undefined,
        soldQuantity: undefined,
        indications: undefined,
        usageDosage: undefined,
        precautions: undefined,
        storageMethod: undefined,
        expiryDate: undefined,
        manufacturer: undefined,
        salesType: null,
        expertId: undefined,
        recommendReason: undefined,
        recommendTime: undefined,
        images: undefined,        // 药品图片URL（单张）
        imageUrl: undefined,      // 轮播图片URL（多张，用逗号分隔）
        storeName: undefined,
        storeAddress: undefined,
        storePhone: undefined,
        businessHours: undefined,
        storeRemark: undefined,
        longitude: undefined,
        latitude: undefined,
      },

      // 表单校验
      rules: {
        medicineName: [
          { required: true, message: "药品名称不能为空", trigger: "blur" }
        ],
        medicineType: [
          { required: true, message: "药品类型不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "当前价格不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的价格格式", trigger: "blur" }
        ],
        specification: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getExpertList();
  },
  methods: {
    /** 查询药品推荐列表 */
    getList() {
      this.loading = true;
      listRecommendation(this.queryParams).then(response => {
        this.recommendationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取专家列表 */
    getExpertList() {
      listExperts({
        pageNum: 1,
        pageSize: 1000,
        status: '0'
      }).then(response => {
        if (response.code === 200) {
          this.expertList = response.rows || [];
        }
      }).catch(() => {
        this.expertList = [
          { expertId: 1, realName: '张医生', title: '主任医师' },
          { expertId: 2, realName: '李医生', title: '副主任医师' }
        ];
      });
    },

    // ========== 通用方法 ==========
    // 文件上传前的验证
    beforeAvatarUpload(file) {
      const isImage = /\.(jpg|jpeg|png|gif|bmp)$/i.test(file.name);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$modal.msgError("只能上传图片格式文件!");
        return false;
      }
      if (!isLt2M) {
        this.$modal.msgError("上传图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },

    // ========== 药品图片相关方法 ==========
    // 药品图片文件列表改变时（限制1张）
    handleMedicineFileChange(file, fileList) {
      if (fileList.length > 1) {
        this.$modal.msgWarning("药品图片只能上传1张");
        fileList.splice(-1, 1);
        return;
      }
      this.medicineFileList = fileList;

      // 更新表单的 images 字段
      if (fileList.length > 0) {
        const url = fileList[0].url || (fileList[0].response && fileList[0].response.url);
        this.form.images = url || '';
      } else {
        this.form.images = '';
      }
    },

    // 药品图片文件移除时
    handleMedicineFileRemove(file, fileList) {
      this.medicineFileList = fileList;
      // 更新表单的 images 字段
      this.form.images = '';
    },

    // 药品图片上传成功回调
    handleMedicineUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        const url = response.fileName || response.url;
        // 更新表单的 images 字段
        this.form.images = url;
        this.$modal.msgSuccess("药品图片上传成功");
      } else {
        this.$modal.msgError("药品图片上传失败: " + response.msg);
      }
    },

    // ========== 轮播图片相关方法 ==========
    // 轮播图片文件列表改变时（限制5张）
    handleCarouselFileChange(file, fileList) {
      if (fileList.length > 5) {
        this.$modal.msgWarning("最多只能上传5张轮播图片");
        fileList.splice(-1, 1);
        return;
      }
      this.carouselFileList = fileList;

      // 更新表单的 imageUrl 字段（多个URL用逗号分隔）
      const urls = fileList.map(item => item.url || (item.response && item.response.url)).filter(url => url);
      this.form.imageUrl = urls.join(',');
    },

    // 轮播图片文件移除时
    handleCarouselFileRemove(file, fileList) {
      this.carouselFileList = fileList;
      // 更新表单的 imageUrl 字段
      const urls = fileList.map(item => item.url || (item.response && item.response.url)).filter(url => url);
      this.form.imageUrl = urls.join(',');
    },

    // 轮播图片上传成功回调
    handleCarouselUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 更新表单的 imageUrl 字段
        const urls = fileList.map(item => item.url || (item.response && item.response.url)).filter(url => url);
        this.form.imageUrl = urls.join(',');
        this.$modal.msgSuccess("轮播图片上传成功");
      } else {
        this.$modal.msgError("轮播图片上传失败: " + response.msg);
      }
    },

    // ========== 上传所有文件 ==========
    uploadAllFiles() {
      return new Promise((resolve, reject) => {
        // 上传药品图片
        const medicinePromise = this.uploadMedicineFile();
        // 上传轮播图片
        const carouselPromise = this.uploadCarouselFiles();

        Promise.all([medicinePromise, carouselPromise])
          .then(([medicineImage, carouselImages]) => {
            // 确保表单字段是最新的
            this.form.images = medicineImage;
            this.form.imageUrl = carouselImages;

            resolve({
              images: medicineImage,
              imageUrl: carouselImages
            });
          })
          .catch(error => {
            this.$modal.msgError("文件上传失败: " + error.message);
            reject(error);
          });
      });
    },

    // 上传药品图片（单张）
    uploadMedicineFile() {
      return new Promise((resolve, reject) => {
        if (this.medicineFileList.length === 0) {
          resolve(this.form.images || '');
          return;
        }

        const fileToUpload = this.medicineFileList.find(file => file.raw);

        if (!fileToUpload) {
          // 如果没有新文件要上传，直接使用现有的URL
          const existingUrl = this.medicineFileList[0]?.url || (this.medicineFileList[0]?.response && this.medicineFileList[0]?.response.url);
          const result = existingUrl || '';
          this.form.images = result;
          resolve(result);
          return;
        }

        const formData = new FormData();
        formData.append('file', fileToUpload.raw);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', this.uploadUrl, true);
        xhr.setRequestHeader('Authorization', 'Bearer ' + getToken());

        xhr.onload = () => {
          if (xhr.status === 200) {
            try {
              const response = JSON.parse(xhr.responseText);
              if (response.code === 200) {
                const result = response.fileName || response.url;
                this.form.images = result;
                resolve(result);
              } else {
                reject(new Error(response.msg || '上传失败'));
              }
            } catch (e) {
              reject(new Error('解析响应失败'));
            }
          } else {
            reject(new Error('上传失败，状态码：' + xhr.status));
          }
        };

        xhr.onerror = () => {
          reject(new Error('网络错误'));
        };

        xhr.send(formData);
      });
    },

    // 上传轮播图片（多张）
    uploadCarouselFiles() {
      return new Promise((resolve, reject) => {
        if (this.carouselFileList.length === 0) {
          resolve(this.form.imageUrl || '');
          return;
        }

        const filesToUpload = this.carouselFileList.filter(file => file.raw);

        if (filesToUpload.length === 0) {
          // 如果没有新文件要上传，直接使用现有的URL
          const existingUrls = this.carouselFileList.map(item => item.url || (item.response && item.response.url)).filter(url => url);
          const result = existingUrls.join(',');
          this.form.imageUrl = result;
          resolve(result);
          return;
        }

        const uploadPromises = filesToUpload.map(file => {
          return new Promise((uploadResolve, uploadReject) => {
            const formData = new FormData();
            formData.append('file', file.raw);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', this.uploadUrl, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + getToken());

            xhr.onload = () => {
              if (xhr.status === 200) {
                try {
                  const response = JSON.parse(xhr.responseText);
                  if (response.code === 200) {
                    uploadResolve(response.fileName || response.url);
                  } else {
                    uploadReject(new Error(response.msg || '上传失败'));
                  }
                } catch (e) {
                  uploadReject(new Error('解析响应失败'));
                }
              } else {
                uploadReject(new Error('上传失败，状态码：' + xhr.status));
              }
            };

            xhr.onerror = () => {
              uploadReject(new Error('网络错误'));
            };

            xhr.send(formData);
          });
        });

        Promise.all(uploadPromises)
          .then(urls => {
            const existingUrls = this.carouselFileList.filter(file => !file.raw && file.url).map(file => file.url);
            const allUrls = [...existingUrls, ...urls];
            const result = allUrls.join(',');
            this.form.imageUrl = result;
            resolve(result);
          })
          .catch(error => {
            this.$modal.msgError("轮播图片上传失败: " + error.message);
            reject(error);
          });
      });
    },

    // ========== 表单操作 ==========
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        medicineName: undefined,
        medicineType: undefined,
        specification: undefined,
        price: undefined,
        originalPrice: undefined,
        soldQuantity: undefined,
        indications: undefined,
        usageDosage: undefined,
        precautions: undefined,
        storageMethod: undefined,
        expiryDate: undefined,
        manufacturer: undefined,
        salesType: null,
        expertId: undefined,
        recommendReason: undefined,
        recommendTime: undefined,
        images: undefined,
        imageUrl: undefined,
        storeName: undefined,
        storeAddress: undefined,
        storePhone: undefined,
        businessHours: undefined,
        storeRemark: undefined,
        longitude: undefined,
        latitude: undefined,
      };
      this.medicineFileList = [];
      this.carouselFileList = [];
      this.activeTab = "basic";
      this.resetForm("form");
    },

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

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加药品推荐";
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getRecommendation(id).then(response => {
        this.form = response.data;

        // 初始化药品图片文件列表（单张）
        if (this.form.images) {
          this.medicineFileList = [{
            name: 'medicine_image.jpg',
            url: this.form.images,
            status: 'success'
          }];
        }

        // 初始化轮播图片文件列表（多张）
        if (this.form.imageUrl) {
          const imageUrls = this.form.imageUrl.split(',');
          this.carouselFileList = imageUrls.map((url, index) => ({
            name: `carousel_${index + 1}.jpg`,
            url: url.trim(),
            status: 'success'
          }));
        }

        this.open = true;
        this.title = "修改药品推荐";
      });
    },

    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          try {
            // 上传所有文件
            const { images, imageUrl } = await this.uploadAllFiles();

            const formData = {
              ...this.form,
              price: this.form.price ? Number(this.form.price) : undefined,
              originalPrice: this.form.originalPrice ? Number(this.form.originalPrice) : undefined,
              soldQuantity: this.form.soldQuantity ? parseInt(this.form.soldQuantity) : undefined,
              longitude: this.form.longitude ? Number(this.form.longitude) : undefined,
              latitude: this.form.latitude ? Number(this.form.latitude) : undefined,
              images: images,
              imageUrl: imageUrl
            };

            if (this.form.id !== undefined) {
              updateRecommendation(formData).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRecommendation(formData).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } catch (error) {
            this.$modal.msgError("提交失败，请重试");
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除药品推荐编号为"' + ids + '"的数据项？').then(function() {
        return delRecommendation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/recommendation/export', {
        ...this.queryParams
      }, `recommendation_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>

<style scoped>
/* 图片上传样式 */
.upload-demo {
  width: 100%;
}
.upload-demo .el-upload {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.upload-demo .el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>
