<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="活动状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable>-->
<!--          <el-option label="进行中" value="1" />-->
<!--          <el-option label="已结束" value="0" />-->
<!--          <el-option label="未开始" value="2" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="状态" prop="shelf">
        <el-select v-model="queryParams.shelf" placeholder="请选择商家状态" clearable>
          <el-option label="上架" value="1" />
          <el-option label="下架" value="2" />
        </el-select>
      </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" icon="el-icon-plus" size="mini" @click="handleAdd">+ 新增活动</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="activityList">
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="活动名称" align="center" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="活动内容" align="center" prop="content" :show-overflow-tooltip="true" />
      <el-table-column label="活动图片" align="center" prop="img" width="120">
        <template slot-scope="scope">
          <el-image
            style="width: 60px; height: 60px"
            :src="baseUrl + scope.row.img"
            :preview-src-list="[baseUrl + scope.row.img]"
            fit="cover"
            v-if="scope.row.img"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <i class="el-icon-picture-outline" v-else></i>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="120" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="120" />
<!--      <el-table-column label="活动状态" align="center" prop="status" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag :type="scope.row.s === '1' ? 'success' : scope.row.status === '2' ? 'warning' : 'info'">-->
<!--            {{ scope.row.status === '1' ? '进行中' : scope.row.status === '2' ? '未开始' : '已结束' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="商家状态" align="center" prop="shelf" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.shelf === '1' ? 'success' : 'danger'">
            {{ scope.row.shelf === '1' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120" />
      <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)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <el-input
            v-model="form.content"
            placeholder="请输入活动内容（只能填数字）"
            @input="validateNumberInput"
          />
        </el-form-item>
        <el-form-item label="活动图片" prop="img">
          <image-upload
            v-model="form.img"
            :limit="1"
            :file-type="['jpg', 'jpeg', 'png', 'gif']"
            action="/back/upload/config/file"
            :data="{type: 'activity'}"
          />
          <div class="el-upload__tip" slot="tip">
            图片将保存到服务器，请确保上传的图片符合要求
          </div>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商家状态" prop="shelf">
          <el-radio-group v-model="form.shelf">
            <el-radio label="1">上架</el-radio>
            <el-radio label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动链接" prop="activityUrl">
          <el-input v-model="form.activityUrl" placeholder="请输入活动链接" />
        </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 { listActivity, getActivity, delActivity, addActivity, updateActivity } from "@/api/activity/activity";
import { getImageUrl } from "@/utils/image";

// 获取服务器基础URL
const baseUrl = process.env.VUE_APP_BASE_API || '';

export default {
  name: "Activity",
  data() {
    // 验证结束时间必须大于开始时间
    const validateEndTime = (rule, value, callback) => {
      if (value && this.form.startTime) {
        if (new Date(value) <= new Date(this.form.startTime)) {
          callback(new Error('结束时间必须大于开始时间'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        shelf: null
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        content: null,
        img: null,
        startTime: null,
        endTime: null,
        status: "1",
        shelf: "1",
        activityUrl: null
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "活动名称不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "活动内容不能为空", trigger: "blur" },
          { pattern: /^\d+$/, message: "活动内容只能填数字", trigger: "blur" }
        ],
        img: [
          { required: true, message: "活动图片不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "change" },
          { validator: validateEndTime, trigger: "change" }
        ],
        shelf: [
          { required: true, message: "商家状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询活动列表 */
    getList() {
      this.loading = true;
      listActivity(this.queryParams).then(response => {
        this.activityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        content: null,
        img: null,
        startTime: null,
        endTime: null,
        status: "1",
        shelf: "1",
        activityUrl: 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 = "添加活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getActivity(id).then(response => {
        this.form = response.data;
        // 确保图片URL正确处理，用于回显
        if (this.form.img) {
          // 如果img不是完整URL，则处理为相对路径
          if (this.form.img.startsWith('http://') || this.form.img.startsWith('https://')) {
            // 完整URL保持不变
          } else {
            // 确保路径格式正确，移除baseUrl前缀（如果有）
            if (this.form.img.startsWith(baseUrl)) {
              this.form.img = this.form.img.substring(baseUrl.length);
            }
            // 确保路径不以/开头（因为上传组件期望的是相对路径）
            if (this.form.img.startsWith('/')) {
              this.form.img = this.form.img.substring(1);
            }
          }
        }
        this.open = true;
        this.title = "修改活动";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除活动编号为"' + ids + '"的数据项？').then(function() {
        return delActivity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 获取图片完整URL的方法
    getImageUrlMethod(imagePath) {
      if (!imagePath) {
        return '';
      }

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

      // 确保路径以/开头
      if (!imagePath.startsWith('/')) {
        imagePath = '/' + imagePath;
      }

      // 返回完整URL
      return baseUrl + imagePath;
    },
    // 验证活动内容只能输入数字
    validateNumberInput() {
      this.form.content = this.form.content.replace(/[^\d]/g, '');
    }
  }
};
</script>
