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

@Component({
  selector: 'app-wish-province-column',
  templateUrl: './wish-province-column.component.html',
  styleUrls: ['./wish-province-column.component.scss']
})
export class WishProvinceColumnComponent extends FrameDetailComponent implements OnInit {

  fieldArray = [];

  constructor(bsModalRef: BsModalRef, fb: FormBuilder) {
    super(bsModalRef);
    AjaxService.requestArray('wish/province/field/list.htm', {}, (array) => {
      array.splice(0, 0, {
        filed_name: '',
        field_text: '   '
      });
      for (let s of array) {
        if (s.field_value) {
          s.fields = s.field_value.split(',');
        }
      }
      this.fieldArray = array;
    });
  }

  initDefautEntity() {
    for (const col of this.ResponseArray) {
      if (col.column_type === undefined) {
        // 默认匹配
        for (let s of this.fieldArray) {
          if (s.fields && s.fields.length > 0) {
            for (let name of s.fields) {
              if (name.length > 0) {
                if (name === col.column_name) {
                  col.column_type = s.field_name;
                  col.column_param = s.field_value_param;
                }
              }
            }
          }
        }
      }
    }
  }

  ngOnInit() {
  }

  saveColumn() {
    for (const s of this.fieldArray) {
      if (s.field_require === 'Active') {
        // 必须对应上
        let flag = false;
        for (const f of this.ResponseArray) {
          if (f.column_type === s.field_name) {
            flag = true;
            break;
          }
        }
        if (flag === false) {
          MsgService.errorToastr(`字段【${s.field_name}】必须有对应字段！`);
          return;
        }
      }
    }

    MsgService.confirmAlert('确定要进行字段匹配吗？字段匹配后系统将自动整理考生志愿信息！', () => {
      AjaxService.request('wish/province/column/save.htm', {column_json: JSON.stringify(this.ResponseArray)}, () => {
        MsgService.successAlert('已完成字段匹配，并根据匹配字段进行了志愿整理！');
        this.closeWindow();
      }, {RequestWithLoading: true});
    });
  }
}
