<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="套餐包名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐包名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐包别名" prop="secondName">
        <el-input
          v-model="queryParams.secondName"
          placeholder="套餐包别名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐类型" prop="packageType">
        <el-select v-model="queryParams.packageType" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in packageTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="子类型" prop="packageSubType">
        <el-select v-model="queryParams.packageSubType" placeholder="请选择子类型" clearable size="small">
          <el-option
            v-for="dict in packageSubTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </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-table border v-loading="loading" :data="list" @selection-change="handleSelectionChange" ref="packageTable" :row-key="'packageId'" :reserve-selection="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="封面图片" width="120" align="center">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.packageImg" width="100">
            <img :src="scope.row.packageImg" style="max-width: 150px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="套餐包名称" align="center" prop="packageName"/>
      <el-table-column label="套餐包别名" align="center" prop="secondName"/>
      <el-table-column label="套餐类型" align="center" prop="packageTypeName"/>
      <el-table-column label="子类型" align="center" prop="packageSubTypeName"/>
    </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 { getChoosePackageList } from '@/api/his/package'

export default {
  name: "ChoosePackageComponent",
  props: {
    packageIds: {
      type: Array,
      default: () => []
    }
  },
  activated() {
    // keep-alive 激活时恢复选中
    this.$nextTick(() => {
      this.restoreSelection()
    })
  },
  watch: {
    // packageIds 变化时重新恢复选中
    packageIds: {
      immediate: false,
      handler() {
        this.$nextTick(() => this.restoreSelection())
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 列表参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        secondName: null,
        packageType: null,
        packageSubType: null,
      },
      // 套餐类型字典
      packageTypeOptions: [],
      // 子类型字典
      packageSubTypeOptions: [],
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      selected: [],
    }
  },
  created() {
    this.getDicts("sys_package_type").then(response => {
      this.packageTypeOptions = response.data;
    });
    this.getDicts("sys_package_sub_type").then(response => {
      this.packageSubTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        secondName: null,
        packageType: null,
        packageSubType: null,
      };
      this.handleQuery();
    },
    getList() {
      this.loading = true;
      getChoosePackageList(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
        // 列表加载后，根据传入的 packageIds 自动选中
        this.$nextTick(() => this.restoreSelection())
      })
    },
    handleSelectionChange(selection) {
      this.selected = selection
    },
    cancel() {
      this.$emit('closeChoose')
    },
    submit() {
      this.$emit('selectConfirm', this.selected)
    },
    // 恢复勾选状态
    restoreSelection() {
      const tableRef = this.$refs.packageTable
      if (!tableRef || !Array.isArray(this.list) || !Array.isArray(this.packageIds)) return
      tableRef.clearSelection()
      if (this.packageIds.length === 0) return
      const idsSet = new Set(this.packageIds)
      this.list.forEach(row => {
        if (row && idsSet.has(row.packageId)) {
          tableRef.toggleRowSelection(row, true)
        }
      })
    }
  }
}
</script>

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