import request from '../request';
export default class QuestionaireViewModel {
  constructor() {
    this._rate = null;
    this._nps = null;
    this.feedback = '';
    this.contact = '';
  }

  set rate(value) {
    this._rate = Math.min(Math.max(value, 0), 5);
  }

  get rate() {
    return this._rate;
  }

  set nps(value) {
    this._nps = Math.min(Math.max(value, 0), 10);
  }

  get nps() {
    return this._nps;
  }

  get canSubmit() {
    return this.rate !== null && this.rate >= 0 && this.nps !== null && this.nps >= 0;
  }

  getInfo(position) {
    return request.get('/api/deliveries', {
      params: {
        position
      },
      timeout: 2 * 1000
    }).then(res => {
      const data = res.data;

      if (data.length) {
        this.metaData = data[0];
        return true;
      }

      return false;
    });
  }

  async submit() {
    if (!this.metaData) throw new Error('缺少问卷数据信息');
    return request.post('/api/feedbacks', {
      satisfy_grade: this.rate,
      grade: this.nps,
      contact: this.contact,
      content: this.feedback,
      delivery_id: this.metaData.id,
      survey_id: this.metaData.survey.id
    });
  }

}