import {Component, OnInit, ViewChild} from '@angular/core';
import {BsModalRef} from 'ngx-bootstrap';
import {FormBuilder, Validators} from '@angular/forms';
import {FrameEditComponent} from '../../core/FrameEditComponent';
import {MsgService} from '../../../../core/msg/msg.service';
import {AjaxService} from '../../../../core/ajax/ajax.service';
import {PagerComponent} from '../../../../core/pager/pager.component';

@Component({
  selector: 'app-farme-dict-detail',
  templateUrl: './farme-dict-detail.component.html',
  styleUrls: ['./farme-dict-detail.component.scss']
})
export class FarmeDictDetailComponent extends FrameEditComponent implements OnInit {

  showDetail = false;
  dictMode: any;
  currentDict =  {};
  @ViewChild('pager', {static: false}) pager: PagerComponent;

  constructor(bsModalRef: BsModalRef, fb: FormBuilder) {
    super(bsModalRef);
    this.valForm = fb.group({
      'dict_value': [null, Validators.compose([Validators.required, Validators.maxLength(32)])],
      'dict_text': [null, Validators.compose([Validators.required, Validators.maxLength(32)])],
      'dict_order': [null, Validators.required]
    });
  }

  ngOnInit() {

  }

  saveDict() {
    if (!this.validForm()) {
      return;
    }
    this.currentDict['dict_name'] = this.ResponseEntity.dict_name;

    let url = 'frame/dict/add.htm';
    let msg = '确定要增加此字典项吗？';
    if (this.dictMode === 'edit') {
      url = 'frame/dict/edit.htm';
      msg = '确定要修改字典项吗？';
    }

    MsgService.confirm(msg, () => {
      AjaxService.request(url, this.currentDict, () => {
        MsgService.successToaster('字典保存成功！如需生效，请重新加载字典信息！');
        this.pager.reload();
        this.dictMode = undefined;
        this.showDetail = false;
        this.currentDict = {};
        this.valForm.markAsUntouched();
      }, {RequestWithLoading: true});
    });

  }

}
