<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="Banner名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入Banner名称"
          clearable
          style="width: 200px"
          @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-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['content:banner:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="Banner ID" align="center" prop="id" min-width="100" />
      <el-table-column label="Banner名称" align="center" prop="name" min-width="150" />
      <el-table-column label="排序" align="center" prop="sort" min-width="80" />
      <el-table-column label="跳转链接" align="center" prop="jumpUrl" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column label="Banner图片" align="center" prop="bannerAddr" min-width="120">
        <template slot-scope="scope">
          <el-image 
            style="width: 80px; height: 50px"
            :src="getImageUrlMethod(scope.row.bannerAddr)" 
            :preview-src-list="[getImageUrlMethod(scope.row.bannerAddr)]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['content:banner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['content:banner: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"
    />

    <!-- 添加或修改Banner对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="Banner名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入Banner名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort" required>
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="jumpUrl" required>
          <el-input v-model="form.jumpUrl" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="Banner图片" required>
          <el-upload
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
            :before-upload="beforeImageUpload"
            class="avatar-uploader"
          >
            <img v-if="form.previewUrl" :src="form.previewUrl" class="avatar">
            <img v-else-if="form.bannerAddr" :src="getImageUrlMethod(form.bannerAddr)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </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 { listBanner, getBanner, delBanner, addBanner, updateBanner } from "@/api/content/banner";
import { getImageUrl } from "@/utils/image.js";
import request from '@/utils/request';

export default {
  name: "Banner",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Banner表格数据
      bannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "Banner名称不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        jumpUrl: [
          { required: true, message: "跳转链接不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取图片完整URL的方法
    getImageUrlMethod(imagePath) {
      return getImageUrl(imagePath);
    },
    /** 查询Banner列表 */
    getList() {
      this.loading = true;
      listBanner(this.queryParams).then(response => {
        this.bannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        sort: 0,
        jumpUrl: null,
        bannerAddr: null,
        previewUrl: null,
        file: null
      };
      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 = "添加Banner";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBanner(id).then(response => {
        this.form = response.data;
        // 设置图片回显
        if (this.form.bannerAddr) {
          this.form.previewUrl = this.getImageUrlMethod(this.form.bannerAddr);
        }
        this.open = true;
        this.title = "修改Banner";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 手动检查图片字段
      if (!this.form.id) {
        // 新增操作：必须上传图片
        if (!this.form.bannerAddr) {
          this.$message.error('Banner图片不能为空');
          return;
        }
      } else {
        // 编辑操作：如果有原图片或新图片都可以
        if (!this.form.bannerAddr) {
          this.$message.error('Banner图片不能为空');
          return;
        }
      }
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑操作：使用bannerAddr字段（上传后的地址）
            updateBanner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBanner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除Banner编号为"' + ids + '"的数据项？').then(function() {
        return delBanner(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 图片选择处理
    handleImageChange(file) {
      // 保存文件对象用于提交
      this.form.file = file.raw;
      // 创建本地预览URL
      this.form.previewUrl = URL.createObjectURL(file.raw);
      
      // 上传图片到服务器
      this.uploadImage(file.raw);
      
      // 强制更新视图
      this.$forceUpdate();
    },
    // 上传图片到服务器
    uploadImage(file) {
      const formData = new FormData();
      formData.append('file', file);
      
      // 调用上传接口
      request({
        url: '/back/upload/config/file',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response.code === 200) {
          // 上传成功，保存返回的图片地址
          this.form.bannerAddr = response.data;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('图片上传失败：' + response.msg);
        }
      }).catch(error => {
        console.error('图片上传失败:', error);
        this.$message.error('图片上传失败');
      });
    },
    // 图片上传前的处理
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 200px;
  height: 120px;
  display: block;
}
</style> 