import {Component, OnInit} from '@angular/core';
import {FrameEditComponent} from '../../../../frame/core/FrameEditComponent';
import {AjaxService} from '../../../../../core/ajax/ajax.service';
import {CookieService} from 'ngx-cookie-service';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {MsgService} from '../../../../../core/msg/msg.service';
import {BsModalRef} from 'ngx-bootstrap';
import {BsModalService} from 'ngx-bootstrap';
import {DomSanitizer} from '@angular/platform-browser';
import {FramePageComponent} from '../../../../frame/core/FramePageComponent';
import {FrameService} from '../../../../../core/frame/frame.service';

@Component({
  selector: 'agent-info',
  templateUrl: './agent-info.component.html'
})

export class AgentInfoComponent extends FramePageComponent implements OnInit {
  initMap: any;
  viewStep = 'page';
  currentEntity :any;
  ResponseEntity: any;
  appTitle = "";

  // 验证表单
  valForm: FormGroup;
  passForm: FormGroup;
  pass: any;
  constructor(private cookies: CookieService, modalService: BsModalService, fb: FormBuilder, sanitizer: DomSanitizer) {
    super(cookies, modalService, sanitizer);

    this.pass =  {};
    this.valForm = fb.group({
      'school_name': [null, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(64)])],
      'school_short_name': [null, Validators.compose([Validators.required, Validators.minLength(1), Validators.maxLength(64)])]
    });
    //const password = new FormControl('', );
    //const certainPassword = new FormControl('', Validators.equalTo(password));
    this.passForm = fb.group({
        'old_pass': [null, Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(24)])],
        'new_pass': [null, Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(24)])],
        'confirmPassword': [null, Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(24)])]
    });
    this.currentEntity = {};
    this.appTitle = FrameService.getParamValue('AppTitle');
  }

  ngOnInit() {
    this.initData();
  }

  logout() {
    AjaxService.request('school/school/logout.htm', {}, () => {
      let url = './assets/login/index.html';
      if (this.cookies.get(`LoginUrl`)) {
        url = this.cookies.get('LoginUrl');
      }
      window.location.href = url;
    });
  }

  initData() {
    AjaxService.requestMap('school/school/info/init.htm', {}, (map) => {
      this.initMap = map;
    });
  }

  openUrl(value: string) {
    window.open(this.initMap.SchoolReg[value]);
  }


  goPass(){
    this.viewStep = 'pass';
    this.pass = {};
  }

  goSavePass() {
    this.valForm.markAllAsTouched();
    if (!this.validForm()) {
      return;
    }
    MsgService.confirm('确定要修改密码吗？', () => {
      AjaxService.request('school/school/info/passwd.htm', this.pass, (data) => {
        MsgService.successToaster('密码修改成功，下次登录请使用新密码！');
        this.viewStep = 'page';
      });
    });
  }

  // 判断表单是否通过了验证
  validForm(): boolean {
    this.valForm.markAllAsTouched();
    return this.valForm.valid;
  }

  /**************************************************************************************************************
   *
   * @param {string} step
   * @param entity
   * @param {string} url
   * @param {Function} callback
   */
  goViewStep(step: string, entity?: any, url?: string, callback?: Function) {
    let vEntity = Object.assign({}, entity);
    if (vEntity === undefined) {
      vEntity = {};
    }
    if (step === 'add') {
      this.currentEntity = vEntity;
      this.viewStep = step;
    } else {
      // 如果路径不为空，说明需要去服务器重新获取数据
      if (url !== undefined) {
        AjaxService.request(url, entity, (data) => {
          this.currentEntity = data.entity;
          if (callback) {
            callback.call(this, data);
          }
          this.viewStep = step;
        });
      } else {
        this.viewStep = step;
        this.currentEntity = entity;
      }
    }

    setTimeout(() => {
      if (this.elAutoFocus) {
        this.elAutoFocus.nativeElement.focus();
      }
    }, 100);
  }

  /*************
   * 提交表单前可自定义一些赋值，子类请直接覆盖此方法
   */
  beforeSubmitForm() {
    return true;
  }

  // 提交表单
  submitForm(url: string, param?: { data?: {}, successMsg?: string, confirmMsg?: string, autoClose?: boolean, RequestWithLoading?: boolean }, callback?: Function) {
    if(!this.beforeSubmitForm()){
      return;
    }
    this.valForm.markAllAsTouched();
    if (!this.validForm()) {
      return;
    }
    // 判断是否有修改
    if (this.ResponseEntity !== undefined) {
      let hasChange = false;
      for (const s in this.currentEntity) {
        if (this.currentEntity[s] !== this.ResponseEntity[s]) {
          hasChange = true;
          break;
        }
      }
      if (!hasChange) {
        MsgService.warnToaster('没有进行任何修改，无需提交服务器操作！');
        return;
      }
    }
    if (param === undefined) {
      param = {};
    }
    if (param.successMsg === undefined) {
      param.successMsg = '操作成功！';
    }
    if (param.autoClose === undefined) {
      param.autoClose = true;
    }
    if (param.RequestWithLoading === undefined) {
      param.RequestWithLoading = true;
    } else {
      param.RequestWithLoading = false;
    }

    const fn = function () {
      AjaxService.request(url, Object.assign({}, this.currentEntity, param.data), (data) => {
        MsgService.successToaster(param.successMsg);
        // 将表单设置为未触碰
        this.UntouchedForm();
        // 将当前的数据保存到历史中
        this.ResponseEntity = Object.assign({}, this.currentEntity);
        if (callback) {
          callback.apply(this, data);
        }
        if (param.autoClose === true) {
          //this.closeWindow();
        }
        this.viewStep = 'page';
        this.initData();
      }, {RequestWithLoading: param.RequestWithLoading});
    }.bind(this);
    if (param.confirmMsg) {
      MsgService.confirm(param.confirmMsg, fn);
    } else {
      fn.apply(undefined);
    }
  }

   // 将表单设置为未使用过状态
   UntouchedForm() {
    this.valForm.markAsUntouched();
  }

}
