import { Component, OnInit, ViewChild } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { MainService } from "../../services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { Observable, Observer } from 'rxjs';
import { NzMessageService, UploadFile, UploadXHRArgs } from 'ng-zorro-antd';
import { HttpRequest, HttpEventType, HttpEvent, HttpResponse, HttpClient } from '@angular/common/http';

@Component({
  selector: "app-sys-config",
  templateUrl: "./sys-config.component.html",
  styleUrls: ["./sys-config.component.less"],
})
export class SysConfigComponent implements OnInit {
  validateForm: FormGroup;
  loading1 = false; //查询信息的loading
  loading2 = false; //保存信息的loading
  loading3 = false; //刷新字典缓存信息的loading
  loading4 = false; //护士默认角色
  initConfig = []; //接口配置列表
  config = []; //配置列表[key,value,id]
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  coopBtns = {};
	checkOptionsOne = [
		{ label: '科内报修', value: 'deptRepair', checked:false},
		{ label: '公共报修', value: 'publicRepair', checked:false },
	];
  formatterSecond = (value: number) => `${value} 秒`;
  parserSecond = (value: string) => value.replace(' 秒', '');
  menu = JSON.parse(localStorage.getItem("menu")) || []; //菜单

  sysLogoUrl:string =  this.mainService.returnUploadUrl('sysLogo', 777);
  faviconLogoUrl:string =  this.mainService.returnUploadUrl('faviconLogo', 777);
  constructor(
    private mainService: MainService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private tool: ToolService,
    private msg: NzMessageService,
    private http: HttpClient
  ) {}
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  ngOnInit() {
    this.validateForm = this.fb.group({
      defaultPwd: [null, [Validators.required]],
      itsmIP: [null, [Validators.required]],
      effectiveDuration: [null, [Validators.required]],
      specimenButton: [null, [Validators.required]],
      deptDisplay: [null, [Validators.required]],
      orderClearUserSwitch: [null, [Validators.required]],
      itsmIncident: [null, [Validators.required]],
      workOrderSettings: [5, [Validators.required]],
      nurseDeptSwitchTip: [0, [Validators.required]],
      refreshNurseWorkOrderTime: [60, [Validators.required]],
      updateTipsForNurses: [""],
      systemName: [""],
      largeScreenName: [""],
      logo: [""],
      favicon: [""],
      defaultRoleOfNurse: [null, [Validators.required]],
      formUrl: [{ value: null, disabled: true }, [Validators.required]],
      serviceUrl: [{ value: null, disabled: true }, [Validators.required]],
      cachePath: [{ value: null, disabled: true }, [Validators.required]],
      cachePort: [{ value: null, disabled: true }, [Validators.required]],
      busiViewDeptId: [null, [Validators.required]],
			repairs: [null, [Validators.required]],
			cmdbRepair: [null, [Validators.required]],
			supportAppVersion: [null, [Validators.required]],
			autoIncidentDegree: [null, [Validators.required]],
			autoWechatDegree: [null, [Validators.required]],
			workorderEvaluation: [null, [Validators.required]]
    });
    this.getDeptType();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getRoleList();
    this.getLogoOrFavicon();
    this.avatarUrl = this.tool.logoUrl;
    this.avatarUrl1 = this.tool.logoUrl;
  }

  getLogoOrFavicon(){
    this.tool.getSysNameAndLogoAsync().subscribe(result => {
      this.avatarUrl = location.origin + '/file' + result.logo || '';
      this.avatarUrl1 = location.origin + '/file' + result.favicon || '';
    })
  }

  // 角色列表
  roleList = [];
  getRoleList() {
    let postData = {
      idx: 0,
      sum: 10,
    };
    this.loading4 = true;
    this.mainService
      .getFetchDataList("user/data", "role", postData)
      .subscribe((result) => {
        this.loading4 = false;
        this.roleList = result.list;
      });
  }
  // 刷新字典缓存
  refresh() {
    this.loading3 = true;
    this.mainService.refreshDic().subscribe(
      (result) => {
        this.loading3 = false;
        if (result.status == 200) {
          this.mainService.clearDictionary();
          this.showPromptModal("刷新", true, "");
        } else {
          this.showPromptModal("刷新", false, "");
        }
      },
      (error) => {
        this.loading3 = false;
        this.showPromptModal("刷新", 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;
    }
    let filterData = this.initConfig.filter(
      (item) =>
        item.keyconfig === "pwd" ||
        item.keyconfig === "itsmIP" ||
        item.keyconfig === "conversationSeconds" ||
        item.keyconfig === "specimenButton" ||
        item.keyconfig === "deptDisplay" ||
        item.keyconfig === "orderClearUserSwitch" ||
        item.keyconfig === "itsmIncident" ||
        item.keyconfig === "workOrderSettings" ||
        item.keyconfig === "nurseDeptSwitchTip" ||
        item.keyconfig === "refreshNurseWorkOrderTime" ||
        item.keyconfig === "updateTipsForNurses" ||
        item.keyconfig === "systemName" ||
        item.keyconfig === "largeScreenName" ||
        item.keyconfig === "defaultRoleOfNurse" ||
        item.keyconfig === "busiViewDeptId" ||
				item.keyconfig === "deptRepair" ||
				item.keyconfig === "publicRepair" ||
				item.keyconfig === "cmdbRepair" ||
				item.keyconfig === "supportAppVersion" ||
				item.keyconfig === "autoIncidentDegree" ||
				item.keyconfig === "autoWechatDegree" ||
				item.keyconfig === "workorderEvaluation"
    );
		console.log(7777,this.validateForm.controls.repairs.value)
    filterData.forEach((item) => {
      if (item.keyconfig === "pwd") {
        item.valueconfig = this.validateForm.controls.defaultPwd.value;
      }else if (item.keyconfig === "itsmIP") {
        item.valueconfig = this.validateForm.controls.itsmIP.value;
      } else if (item.keyconfig === "conversationSeconds") {
        item.valueconfig = this.validateForm.controls.effectiveDuration.value;
      } else if (item.keyconfig === "specimenButton") {
        item.valueconfig = this.validateForm.controls.specimenButton.value;
      } else if (item.keyconfig === "deptDisplay") {
        item.valueconfig = this.validateForm.controls.deptDisplay.value;
      } else if (item.keyconfig === "orderClearUserSwitch") {
        item.valueconfig =
          this.validateForm.controls.orderClearUserSwitch.value;
      } else if (item.keyconfig === "itsmIncident") {
        item.valueconfig =
          this.validateForm.controls.itsmIncident.value;
      } else if (item.keyconfig === "workOrderSettings") {
        item.valueconfig = this.validateForm.controls.workOrderSettings.value;
      } else if (item.keyconfig === "nurseDeptSwitchTip") {
        item.valueconfig = this.validateForm.controls.nurseDeptSwitchTip.value;
      } else if (item.keyconfig === "refreshNurseWorkOrderTime") {
        item.valueconfig = this.validateForm.controls.refreshNurseWorkOrderTime.value;
      } else if (item.keyconfig === "updateTipsForNurses") {
        item.valueconfig = this.validateForm.controls.updateTipsForNurses.value;
      } else if (item.keyconfig === "systemName") {
        item.valueconfig = this.validateForm.controls.systemName.value;
      } else if (item.keyconfig === "largeScreenName") {
        item.valueconfig = this.validateForm.controls.largeScreenName.value;
      } else if (item.keyconfig === "defaultRoleOfNurse") {
        item.valueconfig = this.validateForm.controls.defaultRoleOfNurse.value;
      } else if (item.keyconfig === "busiViewDeptId") {
        item.valueconfig = this.validateForm.controls.busiViewDeptId.value;
      } else if (item.keyconfig === "deptRepair") {
				let value = null
				if(this.validateForm.controls.repairs.value[0].checked){
					value = '1'
				}else{
					value = '0'
				}
        item.valueconfig = value;
      } else if (item.keyconfig === "publicRepair") {
			  let value = null
			  if(this.validateForm.controls.repairs.value[1].checked){
			  	value = '1'
			  }else{
			  	value = '0'
			  }
			  item.valueconfig = value;
			}else if (item.keyconfig === "cmdbRepair") {
        item.valueconfig = this.validateForm.controls.cmdbRepair.value;
      }else if (item.keyconfig === "supportAppVersion") {
        item.valueconfig = this.validateForm.controls.supportAppVersion.value;
      }else if (item.keyconfig === "autoIncidentDegree") {
        item.valueconfig = this.validateForm.controls.autoIncidentDegree.value;
      }else if (item.keyconfig === "autoWechatDegree") {
        item.valueconfig = this.validateForm.controls.autoWechatDegree.value;
      }else if (item.keyconfig === "workorderEvaluation") {
        item.valueconfig = this.validateForm.controls.workorderEvaluation.value;
      }
    });
    const postData = filterData;
    this.loading2 = true;
    this.mainService.changeSysConfig(postData).subscribe(
      (result) => {
        this.loading2 = false;
        if (result["status"] == 200) {
          this.showPromptModal("保存", true, "");
        } else {
          this.showPromptModal("保存", false, "");
        }
      },
      (error) => {
        this.loading2 = false;
        this.showPromptModal("保存", false, "");
      }
    );
  }
  // 获取科室类型
  deptTypes: any = [];
	evaluateData: any = [];
	workorderEvaluation: any = [];
  getDeptType() {
    this.loading1 = true;
    this.mainService.getDictionary("list", "dept_type").subscribe((result) => {
      this.deptTypes = result;
    });
		this.mainService.getDictionary("list", "incident_degree").subscribe((result) => {
		  this.evaluateData = result;
		});
		this.mainService.getDictionary("list", "workorderEvaluation").subscribe((result) => {
		  this.workorderEvaluation = result;
		  this.getSysConfig();
		});
  }
  // 格式化自动关闭工单设置的数字选择框
  formatterPercent = (value: number) => `${value}小时`;
  parserPercent = (value: string) => value.replace("小时", "");
  // 获取系统配置
  getSysConfig() {
    const postData = { idx: 0, sum: 99 };
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        this.loading1 = false;
        if (result.status == 200) {
          if (result.list && Array.isArray(result.list)) {
            this.initConfig = JSON.parse(JSON.stringify(result.list));
            this.config = result.list.map((item) => {
              return [item.keyconfig, item.valueconfig, item.id, item.label];
            });
            this.config.forEach((c) => {
              switch (c[0]) {
                case "pwd":
                  this.validateForm.controls.defaultPwd.setValue(c[1]);
                  break;
                case "itsmIP":
                  this.validateForm.controls.itsmIP.setValue(c[1]);
                  break;
                case "conversationSeconds":
                  this.validateForm.controls.effectiveDuration.setValue(c[1]);
                  break;
                case "specimenButton":
                  this.validateForm.controls.specimenButton.setValue(c[1]);
                  break;
                case "deptDisplay":
                  this.validateForm.controls.deptDisplay.setValue(c[1]);
                  break;
                case "orderClearUserSwitch":
                  this.validateForm.controls.orderClearUserSwitch.setValue(
                    c[1]
                  );
                  break;
                case "itsmIncident":
                  this.validateForm.controls.itsmIncident.setValue(
                    c[1]
                  );
                  break;
                case "workOrderSettings":
                  this.validateForm.controls.workOrderSettings.setValue(c[1]);
                  break;
                case "nurseDeptSwitchTip":
                  this.validateForm.controls.nurseDeptSwitchTip.setValue(c[1]);
                  break;
                case "refreshNurseWorkOrderTime":
                  this.validateForm.controls.refreshNurseWorkOrderTime.setValue(c[1]);
                  break;
                case "updateTipsForNurses":
                  this.validateForm.controls.updateTipsForNurses.setValue(c[1]);
                  break;
                case "systemName":
                  this.validateForm.controls.systemName.setValue(c[1]);
                  break;
                case "largeScreenName":
                  this.validateForm.controls.largeScreenName.setValue(c[1]);
                  break;
                case "defaultRoleOfNurse":
                  this.validateForm.controls.defaultRoleOfNurse.setValue(
                    c[1] - 0
                  );
                  break;
                case "formUri":
                  this.validateForm.controls.formUrl.setValue(c[1]);
                  break;
                case "serviceUrl":
                  this.validateForm.controls.serviceUrl.setValue(c[1]);
                  break;
                case "userRedisIp":
                  this.validateForm.controls.cachePath.setValue(c[1]);
                  break;
                case "userRedisPort":
                  this.validateForm.controls.cachePort.setValue(c[1]);
                  break;
                case "busiViewDeptId":
                  this.validateForm.controls.busiViewDeptId.setValue(c[1] + "");
                  break;
								case "deptRepair":
									if(c[1]=='1'){
										this.checkOptionsOne[0].checked = true
									}else{
										this.checkOptionsOne[0].checked = false
									}
								  this.validateForm.controls.repairs.setValue(this.checkOptionsOne + "");
								  break;
								case "publicRepair":
									if(c[1]=='1'){
										this.checkOptionsOne[1].checked = true
									}else{
										this.checkOptionsOne[1].checked = false
									}
								  this.validateForm.controls.repairs.setValue(this.checkOptionsOne + "");
								  break;	
								case "cmdbRepair":
								  this.validateForm.controls.cmdbRepair.setValue(c[1] + "");
								  break;
								case "supportAppVersion":
								  this.validateForm.controls.supportAppVersion.setValue(c[1]);
								  break;
								case "autoIncidentDegree":
								  this.validateForm.controls.autoIncidentDegree.setValue(c[1] + "");
								  break;
								case "autoWechatDegree":
								  this.validateForm.controls.autoWechatDegree.setValue(c[1] + "");
								  break;
								case "workorderEvaluation":
								  this.validateForm.controls.workorderEvaluation.setValue(c[1] + "");
								  break;
              }
            });
          } else {
            this.initConfig = [];
            this.config = [];
          }
        }
      });
  }
  // 展示信息提示框（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.getDeptType();
  }

  avatarLoading = false;
  avatarUrl: string;
  avatarUrl1: string;
  beforeUpload = (file: File) => {
    return new Observable((observer: Observer<boolean>) => {
      const isPic = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg');
      if (!isPic) {
        this.msg.error('只能上传jpg|jpeg|png图片!');
        observer.complete();
        return;
      }
      const isLt4M = file.size / 1024 / 1024 < 4;
      if (!isLt4M) {
        this.msg.error('图片大小不能大于4MB!');
        observer.complete();
        return;
      }
      observer.next(isPic && isLt4M);
      observer.complete();
    });
  };

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: UploadFile }, avatarUrl): void {
    switch (info.file.status) {
      case 'uploading':
        this.avatarLoading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          this.avatarLoading = false;
          this[avatarUrl] = img;
        });
        break;
      case 'error':
        this.msg.error('Network error');
        this.avatarLoading = false;
        break;
    }
  }

  customReq = (item: UploadXHRArgs) => {
    console.log(item);
    // Create a FormData here to store files and other parameters.
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', item.file as any);
    formData.append('filename', item.file.name);
    const req = new HttpRequest('POST', item.action!, formData, {
      reportProgress: true,
      withCredentials: true
    });
    // Always returns a `Subscription` object. nz-upload would automatically unsubscribe it at correct time.
    return this.http.request(req).subscribe(
      // tslint:disable-next-line no-any
      (event: HttpEvent<any>) => {
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total! > 0) {
            // tslint:disable-next-line:no-any
            (event as any).percent = (event.loaded / event.total!) * 100;
          }
          item.onProgress!(event, item.file!);
        } else if (event instanceof HttpResponse) {
          item.onSuccess!(event.body, item.file!, event);
        }
      },
      err => {
        item.onError!(err, item.file!);
      }
    );
  };
}
