import { Component, OnInit, Output, Input, ViewChild, ElementRef } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { MainService } from 'src/app/services/main.service';

@Component({
  selector: 'app-select-remark',
  templateUrl: './select-remark.component.html',
  styleUrls: ['./select-remark.component.less']
})
export class SelectRemarkComponent implements OnInit {
  @ViewChild("remarkEle", { static: false }) remarkEle: ElementRef;
  @Input() inspect:any = {};
  @Output() submitFormHand = new EventEmitter();
  @Output() cancelFlagHand = new EventEmitter();

  validateForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
  ) { }

  ngOnInit() {
    this.initForm();
  }

  initForm(){
    this.validateForm = this.fb.group({
      remark: [this.inspect.remark || '', [Validators.required, Validators.pattern(/\S/)]],
    });
  }

  // 注意事项获取焦点
  isShowNoteList:boolean = false;
  focusNote(){
    this.isShowNoteList = true;
    this.getNoteList();
  }

  // 选择注意事项
  selectNote(name){
    this.validateForm.controls.remark.setValue(name);
    this.isShowNoteList = false;
    // this.remarkEle.nativeElement.focus();
  }

  // 获取注意事项列表
  noteList:any[] = [];
  noteLoading:boolean = false;
  getNoteList() {
    this.noteLoading = true;
    this.mainService.getDictionary('list', 'inspect_notes',).subscribe(result=>{
      this.noteLoading = false;
      this.noteList = result || [];
    });
  }

  // 点击其他位置
  clickExtra(e){
    if(document.documentElement.contains(document.querySelector('#noteList')) && e.target !== document.querySelector('#noteFocus')){
      this.isShowNoteList = false;
    }
  }

  // 隐藏模态框
  hideModal() {
    this.cancelFlagHand.emit(false)
  }

  // 表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    this.submitFormHand.emit(this.validateForm.value.remark);
  }
}

