import {Component, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import {DomSanitizer} from '@angular/platform-browser';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { FrameService } from '../../../../../core/service/frame.service';
import { AjaxService } from '../../../../../core/service/ajax.service';
import { FrameDetailComponent } from '../../../../frame/core/detail/frame.detail';

@Component({
  selector: 'app-conf-rule-detail',
  templateUrl: './conf-rule-detail.component.html',
  styleUrls: ['./conf-rule-detail.component.scss']
})
export class ConfRuleDetailComponent extends FrameDetailComponent implements OnInit {

  matchArray = [];

  constructor(bsModalRef: BsModalRef, fb: FormBuilder, sanitizer: DomSanitizer) {
    super(bsModalRef, sanitizer);
    this.detailForm = fb.group({
      'attr_name': [null, Validators.compose([Validators.required])],
      'rule_name': [null, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(128)])],
      'rule_type': [null, Validators.compose([Validators.required])],
      'attr_value': [null, Validators.compose([Validators.required])],
      'match_type': [null, Validators.compose([Validators.required])],
      'match_value': [null, Validators.compose([Validators.required])],
      'rule_order': [null, Validators.compose([Validators.required])],
      'match_fail_msg': [null, Validators.compose([Validators.required, Validators.maxLength(2000)])]
    });
  }


  ngOnInit() {
  }

  changeRuleType() {
    this.matchArray = [];
    this.currentEntity.match_value = undefined;
    this.currentEntity.match_value_alias = undefined;
    if (this.currentEntity.rule_type === undefined || this.currentEntity.rule_type === null || this.currentEntity.rule_type.length === 0) {
      return;
    }
    AjaxService.requestArray(`conf/${this.currentEntity.rule_type}/all.htm`, {}, (array) => {
      for (const s of array) {
        this.matchArray.push({match_id: s[this.currentEntity.rule_type + '_id'], match_name: s[this.currentEntity.rule_type + '_name']});
      }
    });

  }

  beforeSubmitForm() {
    this.currentEntity.attr_alias = FrameService.getFrameDictText('ConfEnrolRuleAttr', this.currentEntity.attr_name);
    for (const s of this.matchArray) {
      if ((this.currentEntity.match_value + '') === (s.match_id + '')) {
        this.currentEntity.match_value_alias = s.match_name;
      }
    }
    return true;
  }

}
