<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="goodsType">
        <el-select v-model="queryParams.goodsType" placeholder="请选择商品分类" clearable size="small">
          <el-option
            v-for="dict in goodsTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" 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-table border v-loading="loading" :data="list" @selection-change="handleSelectionChange" ref="integralGoodsTable" :row-key="'goodsId'" :reserve-selection="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="goodsName"/>
      <el-table-column label="商品分类" align="center" prop="goodsTypeName"/>
      <el-table-column label="封面图片" align="center" prop="goodsImg" width="120">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.goodsImg" width="100">
            <img :src="scope.row.goodsImg" style="max-width: 150px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="cash"/>
      <el-table-column label="所需积分" align="center" prop="integral"/>
      <el-table-column label="库存" align="center" prop="stock"/>
    </el-table>

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

    <div class="footer-button">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getChooseIntegralGoodsList } from '@/api/his/integralGoods'

export default {
  name: "ChooseIntegralGoodsComponent",
  props: {
    goodsIds: {
      type: Array,
      default: () => []
    }
  },
  activated() {
    // keep-alive 激活时恢复选中
    this.$nextTick(() => {
      this.restoreSelection()
    })
  },
  watch: {
    // goodsIds 变化时重新恢复选中
    goodsIds: {
      immediate: false,
      handler() {
        this.$nextTick(() => this.restoreSelection())
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        goodsType: null
      },
      // 商品分类字典
      goodsTypeOptions: [],
      // 总条数
      total: 0,
      // 数据
      list: [],
      selected: []
    }
  },
  created() {
    this.handleQuery();
    this.getDicts("sys_integral_goods_type").then(response => {
      this.goodsTypeOptions = response.data;
    });
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        goodsType: null
      };
      this.handleQuery();
    },
    getList() {
      this.loading = true
      getChooseIntegralGoodsList(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
        // 列表加载后，根据传入的 goodsIds 自动选中
        this.$nextTick(() => this.restoreSelection())
      })
    },
    handleSelectionChange(selection) {
      this.selected = selection
    },
    cancel() {
      this.$emit('closeChoose')
    },
    submit() {
      this.$emit('selectConfirm', this.selected)
    },
    // 恢复勾选状态
    restoreSelection() {
      const tableRef = this.$refs.integralGoodsTable
      if (!tableRef || !Array.isArray(this.list) || !Array.isArray(this.goodsIds)) return
      tableRef.clearSelection()
      if (this.goodsIds.length === 0) return
      const idsSet = new Set(this.goodsIds)
      this.list.forEach(row => {
        if (row && idsSet.has(row.goodsId)) {
          tableRef.toggleRowSelection(row, true)
        }
      })
    }
  }
}
</script>

<style scoped>
.footer-button {
  display: flex;
  justify-content: flex-end;
  margin-top: 40px;
}
</style>
