import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { MainService } from '../../services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { FormGroup, Validators, FormBuilder, FormControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import countBy from 'lodash-es/countBy';
import { v4 as uuidv4 } from 'uuid';

@Component({
  selector: 'app-inspection-configuration-item-prompt-modal',
  templateUrl: './inspection-configuration-item-prompt-modal.component.html',
  styleUrls: ['./inspection-configuration-item-prompt-modal.component.less']
})
export class InspectionConfigurationItemPromptModalComponent implements OnInit {
  // 切换科室，切换弹窗
  hsLoading = false;
  historySpecimenList: any = [];
  historySpecimenPageIndex: number = 1;//表格当前页码
  historySpecimenPageSize: number = 9999;//表格每页展示条数
  historySpecimenListLength: number = 10;//表格总数据量

  currentHospital; //当前院区
  validateForm: FormGroup; //新增/编辑表单
  @Input() show: Boolean;
  @Input() coopData: any;

  @Output() confirmModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private fb: FormBuilder,
    private message: NzMessageService,
  ) { }

  ngOnInit() {
    this.initForm();
    this.currentHospital = this.tool.getCurrentHospital();
    this.getList();
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      // name: [null, [Validators.required]],//选项名称
      // orders: [null, [Validators.required]],//排序号
      // checkDefault: [false],//是否默认选中
      // exception: [null, [Validators.required]],//异常标记
    });
    console.log(this.validateForm.controls)
  }

  // 添加表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitForm(): void {
    console.log(this.coopData)
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    if(Object.keys(this.validateForm.value).length === 0){
      this.message.warning('请至少填写一个选择项');
      return;
    }
    console.log(this.validateForm.value);
    let postData:any = {};

    //增加
    postData = {
      itemId: this.coopData.id,
      configList: [],
    };
    for (let i = 0; i < this.historySpecimenList.length; i++) {
      postData.configList.push({
        name: this.validateForm.value['name_' + this.historySpecimenList[i].id],
        valuex: this.validateForm.value['name_' + this.historySpecimenList[i].id],
        orders: this.validateForm.value['orders_' + this.historySpecimenList[i].id],
        checkDefault: this.validateForm.value['checkDefault_' + this.historySpecimenList[i].id] ? 1 : 0,
        checkException: this.validateForm.value['exception_' + this.historySpecimenList[i].id],
        uncheckException: this.validateForm.value['exception_' + this.historySpecimenList[i].id] === 1 ? 0 : 1,
      })
    }
    // 下拉框只允许勾选一个默认选中
    if((this.coopData.type.value === '1' || this.coopData.type.value === '2') && countBy(postData.configList, 'checkDefault')[1] > 1){
      this.message.warning(`${this.coopData.type.name}只允许勾选一个默认选中`);
      return;
    }
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .inspectionPost("bindFormItem", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.hideModal();
          this.initForm();
          this.message.success('批量保存成功');
          this.confirmModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
        } else {
          this.message.error(result.msg || '批量保存失败');
        }
      });
  }

  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }

  // 添加
  addField(): void {
    let obj = {
      id: uuidv4(),
      name: null,
      orders: null,
      checkDefault: false,
      exception: null,
    };

    // 动态添加表单
    for (const key in obj) {
      console.log(key + '_' + obj.id)
      if(key === 'checkDefault'){
        this.validateForm.addControl(key + '_' + obj.id, new FormControl(false))
      }else if(key !== 'id'){
        this.validateForm.addControl(key + '_' + obj.id, new FormControl(null, [Validators.required]))
      }
    }

    this.historySpecimenList = [
      ...this.historySpecimenList,
      obj,
    ]
  }

  // 删除
  removeField(obj, i:number): void {
    console.log(i);
    this.historySpecimenList.splice(i, 1);
    this.historySpecimenList = [...this.historySpecimenList];
    // 动态删除表单
    for (const key in obj) {
      this.validateForm.removeControl(key + '_' + obj.id);
    }
  }

  // 获取列表数据
  getList(idx?) {
    if (idx) {
      this.historySpecimenPageIndex = 1;
    }
    let postData = {
      idx: this.historySpecimenPageIndex - 1,
      sum: this.historySpecimenPageSize,
      inspectionFormItemConfig: {
        itemId: this.coopData.id,
        hosId: this.currentHospital.id,
      }
    }
    this.hsLoading = true;
    this.mainService.getFetchDataList('simple/data','inspectionFormItemConfig',postData).subscribe(data => {
      this.hsLoading = false;
      let list = data.list || [];
      this.historySpecimenList = list.map(v => {
        return {
          id: uuidv4(),
          name: v.name || null,
          orders: v.orders || null,
          checkDefault: v.checkDefault || false,
          exception: v.checkException === 1 ? 1 : (v.uncheckException === 1 ? 0 : null),
        }
      });
      console.log(this.historySpecimenList);
      // 动态添加表单
      this.historySpecimenList.forEach((obj, i) => {
        for (const key in obj) {
          if(key === 'checkDefault'){
            this.validateForm.addControl(key + '_' + obj.id, new FormControl(obj[key]))
          }else if(key !== 'id'){
            this.validateForm.addControl(key + '_' + obj.id, new FormControl(obj[key], [Validators.required]))
          }
        }
      })
      this.historySpecimenListLength = data.totalNum || 0;
    })
  }
}


