<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    width="1200px"
    append-to-body
    @open="init"
    @close="handleClose"
  >
    <!-- 搜索区域 -->
    <el-form :model="query" ref="queryForm" :inline="true" label-width="68px" size="small">
      <slot name="search-form"></slot>
      <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
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @row-dblclick="handleRowDbClick"
      :highlight-current-row="!multiple"
      height="400"
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" v-if="multiple" />
      <template v-for="(column, index) in columns">
        <el-table-column
          :key="index"
          :prop="column.key"
          :label="column.label"
          :align="column.align || 'center'"
          :width="column.width"
          :min-width="column.minWidth"
          :show-overflow-tooltip="column.overflow"
        >
          <template slot-scope="scope">
            <slot :name="column.key" :row="scope.row">
              {{ scope.row[column.key] | dv }}
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>

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

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm" size="medium">确 定</el-button>
      <el-button @click="handleClose" size="medium">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "CheckDialog",
  props: {
    // 弹窗标题
    title: {
      type: String,
      default: "选择数据"
    },
    // 是否显示弹窗
    show: {
      type: Boolean,
      default: false
    },
    // 默认选中的ID列表
    selectedIds: {
      type: [String, Array],
      default: null
    },
    // 表格列配置
    columns: {
      type: Array,
      required: true
    },
    // 获取列表数据的API
    listApi: {
      type: Function,
      required: true
    },
    // 获取详情数据的API
    loadApi: {
      type: Function,
      required: true
    },
    // 选中数据对应的ID字段
    prop: {
      type: String,
      default: "id"
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 查询条件
    query: {
      type: Object,
      default: () => {
        return {
          pageNum: 1,
          pageSize: 20
        }
      }
    },
    // 自定义查询条件
    customQuery: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数据ID
      selection: [],
      // 总条数
      total: 0,
      // 表格数据
      list: [],
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", val);
      }
    }
  },
  methods: {
    // 初始化
    async init() {
      this.query.pageNum = 1;
      this.query.pageSize = 20;

      // 合并自定义查询条件
      Object.assign(this.query, this.customQuery);

      if (this.multiple && this.selectedIds != null) {
        this.selection = [...this.selectedIds];
      } else {
        this.selection = [this.selectedIds];
      }
      this.getList();
    },
    // 查询列表
    getList() {
      this.loading = true;
      this.listApi(this.query).then(res => {
        this.list = res.rows;
        this.total = res.total;
        this.loading = false;
        this.$nextTick(() => {
          // 回显数据
          this.list.forEach(row => {
            const index = this.selection.findIndex(item => item === row[this.prop]);
            if (index !== -1) {
              this.$refs.table.toggleRowSelection(this.list[index], true);
            }
          });
        });
      });
    },
    // 搜索按钮操作
    handleQuery() {
      this.query.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item[this.prop]);
    },
    // 确认按钮
    handleConfirm() {
      if (this.loadApi) {
        this.loading = true;
        this.loadApi(this.selection).then((res) => {
          this.confirm(res.data);
        }).finally(() => {
          this.loading = false;
        });
      } else {
        this.confirm(res.data);
        this.handleClose();
      }
    },
    confirm(data) {
      if (this.multiple) {
        this.$emit("confirm", data);
      } else {
        if (data.length > 0) {
          this.$emit("confirm", data[0]);
        } else {
          this.$emit("confirm", null);
        }
      }
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false;
    },
    // 处理行点击
    handleRowClick(row) {
      if (this.multiple) {
        if (this.selection.includes(row[this.prop])) {
          this.$refs.table.toggleRowSelection(row, false);
        } else {
          this.$refs.table.toggleRowSelection(row, true);
        }
      } else {
        this.selection = [row[this.prop]];
      }
    },
    // 处理行双击
    handleRowDbClick(row) {
      if (!this.multiple) {
        this.selection = [row[this.prop]];
        this.handleConfirm();
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog {
  .el-table {
    margin: 10px 0;
  }
}
</style>
