import { Component, OnInit, ViewChild, AfterViewInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import difference from 'lodash-es/difference'
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: "app-inspection-configuration-item",
  templateUrl: "./inspection-configuration-item.component.html",
  styleUrls: ["./inspection-configuration-item.component.less"],
})
export class InspectionConfigurationItemComponent implements OnInit, AfterViewInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any = {}; //当前操作列
  currentHospital; //当前院区

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

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  nextSchemeName = ""; //下一个开启的方案名称
  modelName = ""; //模态框名称
  tableHeight:number = 0;
  pageHeight:number = 0;

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getInspectionConfigurationDetail(+this.route.snapshot.paramMap.get("id"))
  }

  ngAfterViewInit(){
    setTimeout(() => {
      this.pageHeight = document.querySelector('.list-template__bottom').clientHeight - document.querySelector('.list-template__top').clientHeight - 8;
      this.tableHeight = this.pageHeight - document.querySelector('.thead').clientHeight;
    }, 0)
  }

  // 初始化增删改按钮
  coopBtns: any = {};

  // 获取巡检单详情
  inspectionConfigurationDetail:any = {};
  getInspectionConfigurationDetail(id){
    this.mainService.getFetchData('simple/data','inspectionForm', id).subscribe(result => {
      console.log(result);
      this.inspectionConfigurationDetail = result.data || {};
      this.initForm();
      this.initPageForm();
      this.getDispatchMethods();
      this.getPageList();
    })
  }

  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: 0,
      sum: 9999,
      inspectionFormItem: {
        hosId: this.currentHospital.id,
        pageId: this.pageActiveId,
        formId: +this.route.snapshot.paramMap.get("id"),
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspectionFormItem", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          let list = data.list || [];
          this.listOfData = list.map(v => ({...v, defaultValue: v.defaultValue || ((v.formItemConfigList || []).map(vv => vv.valuex).toString())}));
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 页码数据
  maskFlag: any = false;
  pageList:any[] = [];
  getPageList() {
    let postData = {
      idx: 0,
      sum: 9999,
      inspectionFormPage: {
        hosId: this.currentHospital.id,
        formId: +this.route.snapshot.paramMap.get("id"),
      },
    };
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchDataList("simple/data", "inspectionFormPage", postData)
      .subscribe((data) => {
        this.message.remove(this.maskFlag);
          this.maskFlag = false;
        if (data.status == 200) {
          this.pageList = data.list || [];
          if(!this.pageActiveId && this.pageList.length){
            this.pageActiveId = this.pageList[0].id;
            this.getList();
          }
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }

  // 新增弹框
  pageModal:boolean = false;
  addPageModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.pageModal = true;
    this.initPageForm();
  }
  //关闭新增/编辑弹框
  hideAddPageModal() {
    this.pageModal = false;
    this.initPageForm();
  }

  // 初始化新增form表单
  validatePageForm: FormGroup; //新增/编辑表单
  initPageForm() {
    this.validatePageForm = this.fb.group({
      name: [null, [Validators.required, Validators.pattern(/\S/)]],//标题
      orders: [null, [Validators.required]],//页码
    });
  }

  // 返回
  goBack(){
    this.router.navigateByUrl(`/main/inspectionConfiguration`);
  }

  // 初始化新增form表单
  formArray:string[] = [];
  initForm() {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],//巡检项名称
      orders: [null, [Validators.required]],//排序号
      type: [null, [Validators.required]],//填写方式
      valuex: [null],//数值-标准正负值-标准值
      valueGap: [null],//数值-标准正负值-正负范围值
      valueLow: [null],//数值-范围值-最小值
      valueUp: [null],//数值-范围值-最大值
      defaultValueNumber: [null],//数值-默认值
      defaultValueString: [null],//单行/多行-默认值
      required: [null],//是否必填
      checkType: [null],//判断形式
      showError: [null],//异常显示
    });
    console.log(this.validateForm.controls)
    this.formArray = Object.keys(this.validateForm.controls).filter(v => v != 'name' && v != 'orders' && v != 'type');
  }

  // 动态表单验证
  requiredChange(formItemNames: string[] = []): void {
    // 必填项
    formItemNames.forEach(v => {
      this.validateForm.get(v)!.setValidators(Validators.required);
      this.validateForm.get(v)!.markAsDirty();
      this.validateForm.get(v)!.updateValueAndValidity();
      if(this.validateForm.value.type !== '4'){
        // 除了数值，都要清空
        this.validateForm.controls[v].setValue(null);
      }
    })

    // 不必填项
    let arr = difference(this.formArray, formItemNames);
    arr.forEach(v => {
      this.validateForm.get(v)!.clearValidators();
      this.validateForm.get(v)!.markAsPristine();
      this.validateForm.get(v)!.updateValueAndValidity();
      this.validateForm.controls[v].setValue(null);
    })

    console.log(this.validateForm);
  }

  // 修改填写方式
  changeType(value){
    switch(value){
      case '1':
        this.requiredChange(['required']);
        break;
      case '2':
        this.requiredChange(['required']);
        break;
      case '3':
        this.requiredChange(['required']);
        break;
      case '4':
        this.requiredChange(['required', 'checkType', 'defaultValueNumber']);
        break;
      case '5':
        this.requiredChange(['required', 'defaultValueString', 'showError']);
        break;
      case '6':
        this.requiredChange(['required', 'defaultValueString', 'showError']);
        break;
      case '7':
        this.requiredChange(['required', 'showError']);
        break;
      case '8':
        this.requiredChange();
        break;
    }
  }

  // 修改判断形式
  changeCheckType(value){
    this.validateForm.controls.defaultValueNumber.setValue(null);
    switch(value){
      case 1:
        // this.requiredChange(['required', 'checkType', 'defaultValueNumber', 'valuex', 'valueGap']);
        this.requiredChange(['required', 'checkType', 'defaultValueNumber']);
        break;
      case 0:
        this.requiredChange(['required', 'checkType', 'defaultValueNumber', 'valueLow', 'valueUp']);
        break;
    }
  }

  // 选择项配置
  inspectionConfigurationItemPromptModalShow = false;
  showModelInspectionConfigurationItem(data) {
    this.coopData = data;
    this.inspectionConfigurationItemPromptModalShow = true;
  }
  // 确认选择项配置
  confirmModelInspectionConfigurationItem(e) {
    this.inspectionConfigurationItemPromptModalShow = JSON.parse(e).show;
    this.getList();
  }
  // 关闭选择项配置
  closeModelInspectionConfigurationItem(e) {
    this.inspectionConfigurationItemPromptModalShow = JSON.parse(e).show;
  }

  //获取填写方式
  isLoading:boolean = false;
  dispatchMethods:any[] = [];
  getDispatchMethods() {
    this.isLoading = true;
    this.mainService.getDictionary("list", "inspection_form_item").subscribe((data) => {
      this.isLoading = false;
      this.dispatchMethods = data || [];
    });
  }

  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    console.log(this.validateForm.value);
    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        inspectionFormItem: {
          name: this.validateForm.value.name,
          valuex: this.validateForm.value.valuex,
          valueGap: this.validateForm.value.valueGap,
          valueLow: this.validateForm.value.valueLow,
          valueUp: this.validateForm.value.valueUp,
          orders: this.validateForm.value.orders,
          defaultValue: this.validateForm.value.defaultValueString || this.validateForm.value.defaultValueNumber,
          required: this.validateForm.value.required,
          checkType: this.validateForm.value.checkType,
          showError: this.validateForm.value.showError,
          type: this.dispatchMethods.find(v => v.value == this.validateForm.value.type),
          hosId: this.currentHospital.id,
          formId: +this.route.snapshot.paramMap.get("id"),
          pageId: this.pageActiveId,
          display: 1,
        }
      };
    } else {
      //编辑
      postData = {
        inspectionFormItem: {
          ...this.coopData,
          ...{
            name: this.validateForm.value.name,
            valuex: this.validateForm.value.valuex,
            valueGap: this.validateForm.value.valueGap,
            valueLow: this.validateForm.value.valueLow,
            valueUp: this.validateForm.value.valueUp,
            orders: this.validateForm.value.orders,
            defaultValue: this.validateForm.value.defaultValueString || this.validateForm.value.defaultValueNumber,
            required: this.validateForm.value.required,
            checkType: this.validateForm.value.checkType,
            showError: this.validateForm.value.showError,
            type: this.dispatchMethods.find(v => v.value == this.validateForm.value.type),
          }
        }
      };
    }
    this.mainService
      .coopData("addData", "inspectionFormItem", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.valuex.setValue(data.valuex);
    this.validateForm.controls.valueGap.setValue(data.valueGap);
    this.validateForm.controls.valueLow.setValue(data.valueLow);
    this.validateForm.controls.valueUp.setValue(data.valueUp);
    this.validateForm.controls.orders.setValue(data.orders);
    this.validateForm.controls.required.setValue(data.required);
    this.validateForm.controls.checkType.setValue(data.checkType);
    this.validateForm.controls.showError.setValue(data.showError);
    this.validateForm.controls.type.setValue(data.type.value);
    if(data.type.value === '5' || data.type.value === '6'){
      this.validateForm.controls.defaultValueString.setValue(data.defaultValue);
    }
    if(data.type.value === '4'){
      this.validateForm.controls.defaultValueNumber.setValue(data.defaultValue);
    }
  }

  // 新增/编辑表单提交-页码
  submitPageForm(): void {
    for (const i in this.validatePageForm.controls) {
      this.validatePageForm.controls[i].markAsDirty();
      this.validatePageForm.controls[i].updateValueAndValidity();
    }
    if (this.validatePageForm.invalid) {
      return;
    }

    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        name: this.validatePageForm.value.name,
        orders: this.validatePageForm.value.orders,
        hosId: this.currentHospital.id,
        formId: +this.route.snapshot.paramMap.get("id"),
      };
    } else {
      //编辑
      postData = {
        ...this.coopData,
        ...{
          name: this.validatePageForm.value.name,
          orders: this.validatePageForm.value.orders,
        }
      };
    }
    this.mainService
      .simplePost("addData", "inspectionFormPage", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddPageModal();
        this.initPageForm();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          if(this.add){
            this.pageActiveId = result.data.id;
          }
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 编辑
  editPage(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.pageModal = true;
    this.coopData = data;
    this.validatePageForm.controls.name.setValue(data.name); //名称
    this.validatePageForm.controls.orders.setValue(data.orders); //页码
  }

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

  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 === "del") {
      //删除-巡检项
      this.mainService
        .simplePost("rmvData", "inspectionFormItem", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    } else if (this.confirmDelType === "show") {
      //显示-巡检项
      let postData = {
        inspectionFormItem: {
          ...this.coopData,
          ...{
            display: 1,
          }
        }
      }
      this.mainService
        .coopData("addData", "inspectionFormItem", postData)
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    } else if (this.confirmDelType === "hidden") {
      //隐藏-巡检项
      let postData = {
        inspectionFormItem: {
          ...this.coopData,
          ...{
            display: 0,
          }
        }
      }
      this.mainService
        .coopData("addData", "inspectionFormItem", postData)
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    } else if (this.confirmDelType === "delPage") {
      //删除-页码
      this.mainService
        .simplePost("rmvData", "inspectionFormPage", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 点击页码
  pageActiveId;
  clickPage(data) {
    this.pageActiveId = data.id;
    this.getList();
  }
}
