const _ = require('lodash');
export default {
  //执行查询
  async search({ skip = 0, limit = this.limit || 10, ...others } = {}) {
    let query = { skip, limit, ...others };
    if (this.searchInfo && Object.keys(this.searchInfo).length > 0) query = { ...query, ...this.searchInfo };
    if (this.defaultSearch && Object.keys(this.defaultSearch).length > 0) query = { ...query, ...this.defaultSearch };
    const res = await this.query(query);
    if (this.$checkRes(res)) {
      this.$set(this, `list`, res.data);
      this.$set(this, `total`, res.total);
    }
  },
  // 去添加
  async toAdd() {
    this.form = {};
    this.initAddData();
    this.view = 'info';
  },
  // 初始化添加数据,重写用
  initAddData() {},
  // 去编辑
  async toEdit({ data }) {
    const res = await this.fetch(data._id);
    if (this.$checkRes(res)) {
      this.$set(this, `form`, res.data);
      this.view = 'info';
    } else {
      this.$message.error('未找到指定数据');
    }
  },
  // 执行删除
  async toDelete({ data }) {
    const res = await this.delete(data._id);
    if (this.$checkRes(res, '操作成功', '操作失败')) this.toResearch();
  },
  // 执行返回
  toBack() {
    this.form = {};
    this.view = 'list';
  },
  //执行保存
  async toSave({ data }) {
    const id = _.get(data, 'id', _.get(data, '_id'));
    let res;
    if (id) res = await this.update(data);
    else res = await this.create(data);
    if (this.$checkRes(res, '操作成功', '操作失败')) {
      this.view = 'list';
      this.toResearch();
    }
  },
  //执行再查询
  toResearch() {
    if (this.search) this.search();
  },
};
