import { Component, OnInit, ViewChild, Input } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { MainService } from "../../../services/main.service";
import { Validators, FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { ToolService } from 'src/app/services/tool.service';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService } from 'ng-zorro-antd';
import { v4 as uuidv4, validate as uuidValidate } from 'uuid';
import { addDays, startOfMinute, endOfMinute, set, getYear, getMonth, getDate, format } from 'date-fns';

@Component({
  selector: "app-configuration-inspect",
  templateUrl: "./configuration-inspect.component.html",
  styleUrls: ["./configuration-inspect.component.less"],
})
export class ConfigurationInspectComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;

  ngOnInit() {
    this.activeDictionaryKey = this.dictionaryKeyList[0];
    this.getDictionaryList();
    this.initDictionaryForm();
  }

  // 数据字典key列表
  dictionaryKeyList:any[] = [
    { id: 1, name: '注意事项', key: "inspect_notes"},
    { id: 2, name: '批量建单配置', key: "", postData: {
      ibActiveStartTime1: undefined,
      ibActiveEndTime1: undefined,
      ibActiveStartTime2: undefined,
      ibActiveEndTime2: undefined,
      ibDefaultStartTime: undefined,
      ibDefaultEndTime: undefined,
      ibDefaultDayStart: [{ label:'+1天', value: 0 }],
      ibDefaultDayEnd: [{ label:'+1天', value: 0 }],
      ib2ActiveStartTime1: undefined,
      ib2ActiveEndTime1: undefined,
      ib2ActiveStartTime2: undefined,
      ib2ActiveEndTime2: undefined,
      ib2DefaultStartTime: undefined,
      ib2DefaultEndTime: undefined,
      ib2DefaultDayStart: [{ label:'+1天', value: 0 }],
      ib2DefaultDayEnd: [{ label:'+1天', value: 0 }],
    }},
    { id: 3, name: '检查项目', key: ""},
    { id: 4, name: '陪检闭环', key: "", postData: {
      batchPatientBackDept: [{ label:'是否开启批量患者回科', value: 0 }],
      batchPatientCheckType: 0,
      batchPatientDynamicKey: [{ label:'是否支持动态密钥', value: 0 }],
			pilAutoBackDept: [{ label:'是否自动标记回科', value: 0 }],
			pilAutoBackDeptHour: 1,
    }},
  ]

  // 点击数据字典key
  activeDictionaryKey:any;
  clickDictionaryKey(item){
    this.activeDictionaryKey = item;
    if(this.activeDictionaryKey.id == 1){
      this.getDictionaryList();
      this.initDictionaryForm();
    }
  }

  btnLoading: boolean = false; //提交按钮loading状态
  // ------------------------------

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getDictionaryList();
  }

  coopData: any = {}; //当前操作列

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "delDictionary") {
      //删除-数据字典
      this.mainService
        .simplePost("rmvData", "dictionary", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.mainService.clearDictionary();
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 初始化数据字典新增form表单
  validateDictionaryForm: FormGroup; //新增/编辑表单
  dictionaryList: any = [];
  initDictionaryForm() {
    this.validateDictionaryForm = this.fb.group({
      // name: [null, [Validators.required]],//键
      // value: [null, [Validators.required]],//值
      // orders: [null, [Validators.required]],//排序号
    });
    console.log(this.validateDictionaryForm.controls)
  }

  // 获取数据字典数据
  maskFlag: any = false;
  getDictionaryList() {
    let postData = {
      idx: 0,
      sum: 9999,
      dictionary: {
        key: this.activeDictionaryKey.key,
      }
    }
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService.getFetchDataList('simple/data','dictionary',postData).subscribe(data => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      let list = data.list || [];
      if(list.length){
        this.dictionaryList = list.map(v => {
          return {
            id: v.id,
            name: v.name || null,
            value: v.value || null,
            orders: v.orders || null,
            system: v.system || false,
          }
        });
      }else{
        this.dictionaryList = [
          {
            id: uuidv4(),
            name: null,
            value: null,
            orders: null,
            system: false,
          }
        ];
      }

      console.log(this.dictionaryList);
      // 动态添加表单
      this.dictionaryList.forEach((obj, i) => {
        for (const key in obj) {
          if(key !== 'id' && key !== 'system'){
            if(this.activeDictionaryKey.key === 'incident_status' || this.activeDictionaryKey.key === 'incident_degree'){
              this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl({value: obj[key], disabled: true}, [Validators.required]))
            }else{
              this.validateDictionaryForm.addControl(key + '_' + obj.id, new FormControl({value: obj[key], disabled: key === 'value' ? obj.system : false}, [Validators.required]))
            }
          }
        }
      })
      console.log(this.validateDictionaryForm.controls)
    })
  }

  // 添加数据字典
  addField(i:number): void{
    let obj = {
      id: uuidv4(),
      name: null,
      value: null,
      orders: null,
      system: false,
    };

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

    this.dictionaryList.splice(i + 1, 0, obj);
  }

  // 删除
  removeField(obj, i:number): void {
    if(uuidValidate(obj.id)){
      this.dictionaryList.splice(i, 1);
      this.dictionaryList = [...this.dictionaryList];
      // 动态删除表单
      for (const key in obj) {
        this.validateDictionaryForm.removeControl(key + '_' + obj.id);
      }
    }else{
      this.showDelModal(obj,'您确认要删除吗？','删除','delDictionary')
    }
  }

  // 保存数据字典
  saveDictionary(): void {
    console.log(this.coopData)
    for (const i in this.validateDictionaryForm.controls) {
      this.validateDictionaryForm.controls[i].markAsDirty();
      this.validateDictionaryForm.controls[i].updateValueAndValidity();
    }
    if (this.validateDictionaryForm.invalid) {
      return;
    }
    console.log(this.validateDictionaryForm.value);
    let postData:any = {};

    //增加
    postData = [];
    let rawValueObj = this.validateDictionaryForm.getRawValue();
    for (let i = 0; i < this.dictionaryList.length; i++) {
      postData.push({
        id: uuidValidate(this.dictionaryList[i].id) ? undefined : this.dictionaryList[i].id,
        name: rawValueObj['name_' + this.dictionaryList[i].id],
        value: rawValueObj['value_' + this.dictionaryList[i].id],
        orders: rawValueObj['orders_' + this.dictionaryList[i].id],
        system: uuidValidate(this.dictionaryList[i].id) ? false : this.dictionaryList[i].system,
        key: this.activeDictionaryKey.key,
      })
    }
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .simplePost("addListData", "dictionary", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        if (result.status == 200) {
          this.mainService.clearDictionary();
          this.showPromptModal('保存', true, '');
        } else {
          this.showPromptModal('保存', false, result.msg || '');
        }
      });
  }



}
