<template>
  <div class="app-container">
    <!-- 检索区：第一个 el-card -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="图片名称" prop="bannerName">
          <el-input
            v-model="queryParams.bannerName"
            placeholder="请输入图片名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="enableFlag">
          <el-select v-model="queryParams.enableFlag" placeholder="全部" clearable style="width: 120px">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </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-form-item>
      </el-form>
    </el-card>

    <!-- 列表区：第二个 el-card，表格带 border -->
    <el-card shadow="never" class="table-card">
      <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="['agri:banner:add']"
          >添加</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="['agri:banner:remove']"
          >批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图片名称" align="center" prop="bannerName" :show-overflow-tooltip="true" min-width="140" />
      <el-table-column label="图片" align="center" width="120">
        <template slot-scope="scope">
          <image-preview :src="scope.row.bannerImage" :width="80" :height="40" />
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="enableFlag" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.enableFlag === '1'" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" width="150">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.sortNo"
            :min="0"
            :precision="0"
            :controls="false"
            size="mini"
            style="width: 90px"
            @blur="handleSortBlur(scope.row)"
          />
          <el-button
            type="text"
            icon="el-icon-check"
            size="mini"
            @click="handleSortSave(scope.row)"
            v-hasPermi="['agri:banner:edit']"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['agri:banner:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['agri: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"
      />
    </el-card>

    <!-- 添加或编辑 Banner 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="图片名称" prop="bannerName">
          <el-input v-model="form.bannerName" placeholder="请输入图片名称" maxlength="64" show-word-limit />
        </el-form-item>
        <el-form-item label="图片" prop="bannerImage">
          <image-upload v-model="form.bannerImage" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
          <div class="form-tip">建议宽高比 2:1（如 750×375），单张不超过 5MB；禁用后 C 端不展示</div>
        </el-form-item>
        <el-form-item label="是否启用" prop="enableFlag">
          <el-radio-group v-model="form.enableFlag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input-number v-model="form.sortNo" :min="0" :precision="0" controls-position="right" />
          <span class="form-tip-inline">数值越小越靠前</span>
        </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, addBanner, updateBanner, updateBannerSortNo, delBanner } from "@/api/agri/banner"

export default {
  name: "AgriBanner",
  data() {
    return {
      // 列表加载遮罩
      loading: true,
      // 勾选的 bannerId 数组
      ids: [],
      // 是否未勾选（批量按钮禁用）
      multiple: true,
      // 是否显示检索区
      showSearch: true,
      // 列表总条数
      total: 0,
      // Banner 表格数据
      bannerList: [],
      // 弹窗标题
      title: "",
      // 是否显示弹窗
      open: false,
      // 行内排序原始值，用于判断是否变更
      sortNoSnapshot: {},
      // 列表检索参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bannerName: undefined,
        enableFlag: undefined
      },
      // 表单数据
      form: {},
      // 表单校验规则
      rules: {
        bannerName: [
          { required: true, message: "请输入图片名称", trigger: "blur" }
        ],
        bannerImage: [
          { required: true, message: "请上传图片", trigger: "change" }
        ],
        enableFlag: [
          { required: true, message: "请选择是否启用", trigger: "change" }
        ],
        sortNo: [
          { required: true, message: "请输入排序", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询 Banner 列表 */
    getList() {
      this.loading = true
      listBanner(this.queryParams).then(response => {
        this.bannerList = response.rows
        this.total = response.total
        // 记录每行排序原始值，供行内改序对比
        this.sortNoSnapshot = {}
        this.bannerList.forEach(item => {
          this.sortNoSnapshot[item.bannerId] = item.sortNo
        })
        this.loading = false
      })
    },
    /** 取消弹窗并重置表单 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 重置表单为默认值 */
    reset() {
      this.form = {
        bannerId: undefined,
        bannerName: undefined,
        bannerImage: undefined,
        enableFlag: "1",
        sortNo: 0
      }
      this.resetForm("form")
    },
    /** 点击搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置检索条件 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 表格多选变化 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bannerId)
      this.multiple = !selection.length
    },
    /** 打开添加弹窗 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加 Banner"
    },
    /** 打开编辑弹窗并拉取详情 */
    handleUpdate(row) {
      this.reset()
      const bannerId = row.bannerId
      getBanner(bannerId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "编辑 Banner"
      })
    },
    /** 提交添加或编辑 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const submitFn = this.form.bannerId != undefined ? updateBanner : addBanner
        submitFn(this.form).then(response => {
          this.$modal.msgSuccess(this.form.bannerId != undefined ? "修改成功" : "新增成功")
          // 非 2:1 比例时后端可能返回 warnAspectRatio
          if (response.data && response.data.warnAspectRatio) {
            this.$modal.msgWarning("建议使用 2:1 比例，以免 C 端裁切变形")
          }
          this.open = false
          this.getList()
        })
      })
    },
    /** 行内排序失焦时尝试保存 */
    handleSortBlur(row) {
      this.handleSortSave(row)
    },
    /** 保存行内排序（仅 sortNo 变更时请求） */
    handleSortSave(row) {
      const oldSortNo = this.sortNoSnapshot[row.bannerId]
      if (oldSortNo === row.sortNo) {
        return
      }
      if (row.sortNo === undefined || row.sortNo === null || row.sortNo < 0) {
        this.$modal.msgError("排序须为非负整数")
        row.sortNo = oldSortNo
        return
      }
      updateBannerSortNo({
        bannerId: row.bannerId,
        sortNo: row.sortNo
      }).then(() => {
        this.$modal.msgSuccess("排序已保存")
        this.sortNoSnapshot[row.bannerId] = row.sortNo
      }).catch(() => {
        row.sortNo = oldSortNo
      })
    },
    /** 单独或批量删除 */
    handleDelete(row) {
      const bannerIds = row.bannerId || this.ids
      const count = row.bannerId ? 1 : this.ids.length
      this.$modal.confirm('确认删除该 Banner？删除后不可恢复' + (count > 1 ? '（共 ' + count + ' 条）' : '')).then(() => {
        return delBanner(bannerIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 10px;
}
.form-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 4px;
}
.form-tip-inline {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
</style>
