import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ViewEncapsulation } from '@angular/core';
import { MainService } from '../../../services/main.service';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { ToolService } from 'src/app/services/tool.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-incident-handle-order',
  templateUrl: './incident-handle-order.component.html',
  styleUrls: ['./incident-handle-order.component.less'],
})
export class IncidentHandleOrderComponent implements OnInit {
  @Input() id: any;

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

  hosId:any;
  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'consumable'){
        this.getConsumableList(v[1]);
      }
    });
    this.hosId = this.tool.getCurrentHospital().id;
    this.getSummaryList();
    this.getHospitalConfig();
    this.getWorkHourManagementList();
  }
	
	// 工时日志列表
	listLogOfData: any[] = []; //日志数据
	pageLogIndex: number = 1; //日志当前页码
	pageLogSize: number = 10; //日志每页展示条数
	listLogLength: number = 10; //日志总数据量
	loading2:boolean = false;
	getHourLogList() {
	  let data = {
	    idx: 0,
	    sum: 99999,
	    workHourManagementLog: {
				workHourId: this.itemData.id,
				repairSummaryId: this.summaryId
	    },
	  };
	  this.loading2 = true;
	  this.mainService
	    .getFetchDataList("simple/data", "workHourManagementLog", data)
	    .subscribe((data) => {
	      this.loading2 = false;
	      if (data.status == 200) {
					this.logModal = true
	        this.listLogOfData = data.list;
	        // this.listLogLength = data.totalNum;
	      }else{
	        this.message.error(data.msg || "请求数据失败");
	      }
	    });
	}
	
	// 耗材日志列表
	getConsumableLogList() {
	  let data = {
	    idx: 0,
	    sum: 99999,
			assetConsumablesHistory: {
			  assetConsumablesId: this.itemData.consumableId,
				repairSummaryId: this.summaryId
			},
	  };
	  this.loading2 = true;
	  this.mainService
	    .getFetchDataList("simple/data", "assetConsumablesHistory", data)
	    .subscribe((data) => {
	      this.loading2 = false;
	      if (data.status == 200) {
					this.logModal = true
	        this.listLogOfData = data.list;
	        // this.listLogLength = data.totalNum;
	      }else{
	        this.message.error(data.msg || "请求数据失败");
	      }
	    });
	}
	
	// 查看日志
	itemData:any = {};
	logModal:boolean = false;
	operationType:any;
	logView(type, data){
		this.operationType = type;
		this.itemData = data;
		if(type==1){ //耗材
			this.getConsumableLogList()
		}else{ //日志
			this.getHourLogList()
		}
	}
	
	// 关闭日志
	hideModal() {
	  this.logModal = false;
	}
	
  // ============耗材start=================

  // 新增耗材/工时弹框
  modelName = ""; //模态框名称
  modalConsumable: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addConsumable() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalConsumable = true;
    this.initConsumableForm();
  }
  //关闭新增/编辑弹框
  hideConsumableModal() {
    this.modalConsumable = false;
  }

  // 编辑
  coopData: any = {}; //当前操作列
  editConsumable(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalConsumable = true;
    this.initConsumableForm();
    this.coopData = data;
    this.validateConsumableForm.controls.consumablesId.setValue(data.consumableId);
    this.validateConsumableForm.controls.consumablesNum.setValue(data.consumablesNum);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitConsumableForm(): void {
    for (const i in this.validateConsumableForm.controls) {
      this.validateConsumableForm.controls[i].markAsDirty();
      this.validateConsumableForm.controls[i].updateValueAndValidity();
    }
    if (this.validateConsumableForm.invalid) {
      return;
    }
    console.log(this.validateConsumableForm.value);
    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        "consumableList": [
          {
            "consumablesId": this.validateConsumableForm.value.consumablesId,
            "consumablesNum": this.validateConsumableForm.value.consumablesNum,
          }
        ],
        "summaryId": this.summaryId,
      };
    } else {
      //编辑
      postData = {
        "consumableList": [
          {
            "consumablesId": this.validateConsumableForm.value.consumablesId,
            "consumablesNum": this.validateConsumableForm.value.consumablesNum,
          }
        ],
        "modifyNum": "edit",
        "summaryId": this.summaryId,
      };
    }
    this.mainService
      .addSummaryDoc(postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideConsumableModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validateConsumableForm: FormGroup; //新增/编辑表单
  initConsumableForm() {
    this.validateConsumableForm = this.fb.group({
      consumablesId: [null, [Validators.required]],
      consumablesNum: [1, [Validators.required]],
    });
    console.log(this.validateConsumableForm.controls)
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([model, e]);
  }

  // 获取院区配置信息
  itsmZeroStock:any = {};//是否支持零库存
  itsmParentConsumable:any = {};//是否支持父级科室耗材
  getHospitalConfig() {
    let postData = {
      idx: 0,
      sum: 9999,
      hospitalConfig: {
        model: "itsm",
        hosId: this.hosId,
      },
    }
    this.mainService
      .getFetchDataList("simple/data", "hospitalConfig", postData)
      .subscribe((result) => {
        let list = result.list || [];
        this.itsmZeroStock = list.find(v => v.key == 'itsmZeroStock') || {};
        this.itsmParentConsumable = list.find(v => v.key == 'itsmParentConsumable') || {};
        this.getConsumableList();
      });
  }

  // 获取耗材
  consumableList: any = [];
  getConsumableList(keyword = '', isShowValue = false) {
    let postData:any = {
      consumable: {
        name: keyword,
        showZero: true,
      },
      idx: 0,
      sum: 20,
    };
    if(this.itsmParentConsumable.value == 1){
      postData.consumable.upHosId = this.hosId;
		}else{
      postData.consumable.hosId = this.hosId;
		}
    this.mainService
      .getFetchDataList("simple/data", "consumable", postData)
      .subscribe((data) => {
        this.isLoading = false;
        let consumableList = data.list || [];
        if(isShowValue && this.coopData && this.coopData.groupId){
          consumableList = consumableList.filter(v => v.id !== this.coopData.id)
          consumableList.unshift(this.coopData);
        }
        this.consumableList = consumableList;
      });
  }

  // ============耗材end=================

  // ============工时start=================

  // 新增耗材/工时弹框
  modalWorkHourManagement: boolean = false; //新增/编辑模态框
  addWorkHourManagement() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalWorkHourManagement = true;
    this.initWorkHourManagementForm();
  }
  //关闭新增/编辑弹框
  hideWorkHourManagementModal() {
    this.modalWorkHourManagement = false;
  }

  // 编辑
  editWorkHourManagement(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalWorkHourManagement = true;
    this.initWorkHourManagementForm();
    this.coopData = data;
    this.validateWorkHourManagementForm.controls.workHourId.setValue(data.id);
    this.validateWorkHourManagementForm.controls.workHourNum.setValue(data.workHourNum2);
  }

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

    if (this.add) {
      //增加
      // let workHourManagementList = this.summaryObj.workHourManagementList || [];
      // postData = {
      //   "workHourManagementList": workHourManagementList.map(v => ({workHourId: v.id, workHourNum: v.workHourNum2 || 1})),
      //   "summaryId": this.summaryId,
      // };
      // let index = postData.workHourManagementList.findIndex(v => v.workHourId == this.validateWorkHourManagementForm.value.workHourId.slice(-1)[0]);
      // if(index > -1){
      //   postData.workHourManagementList[index].workHourNum += this.validateWorkHourManagementForm.value.workHourNum;
      // }else{
      //   postData.workHourManagementList.push(
      //     {
      //       "workHourId": this.validateWorkHourManagementForm.value.workHourId.slice(-1)[0],
      //       "workHourNum": this.validateWorkHourManagementForm.value.workHourNum,
      //     }
      //   );
      // }
			postData ={
				"workHourManagementList": [
				  {
				    "workHourId": this.validateWorkHourManagementForm.value.workHourId.slice(-1)[0],
				    "workHourNum": this.validateWorkHourManagementForm.value.workHourNum,
				  }
				],
				"summaryId": this.summaryId,
			}
    } else {
      //编辑
      postData = {
        "workHourManagementList": [
          {
            "workHourId": this.coopData.id,
            "workHourNum": this.validateWorkHourManagementForm.value.workHourNum,
          }
        ],
        "modifyNum": "edit",
        "summaryId": this.summaryId,
      };
    }
    this.mainService
      .addSummaryDoc(postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideWorkHourManagementModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validateWorkHourManagementForm: FormGroup; //新增/编辑表单
  initWorkHourManagementForm() {
    this.validateWorkHourManagementForm = this.fb.group({
      workHourId: [null, [Validators.required]],
      workHourNum: [1, [Validators.required]],
    });
    console.log(this.validateWorkHourManagementForm.controls)
  }

  // 获取工时
  workHourManagementList: any = [];
  getWorkHourManagementList() {
    let postData = {
      workHourManagement: {
        hosId: this.hosId,
        showSecond: 1,
				disableType:1
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("simple/data", "workHourManagement", postData)
      .subscribe((res) => {
        this.isLoading = false;
        let workHourManagementList = res.list || [];
        workHourManagementList = workHourManagementList.map(v => ({...v, parentId: v.parent ? v.parent.id : undefined, label: v.workName, value: v.id}));
        this.workHourManagementList = this.tool.tranListToTreeDataLeaf(workHourManagementList, undefined, "parentId");
        console.log(this.workHourManagementList);
      });
  }

  // ============工时end=================

  // 获取汇总单信息
  summaryObj:any = {
    consumableList: [],//耗材列表
    workHourManagementList: [],//工时列表
  };
  summaryId = undefined;//汇总单Id
  summaryLoading:boolean = false;
  getSummaryList() {
    this.summaryLoading = true;
    let postData = {
      "incidentId": this.id,
    };
    this.mainService
      .querySummaryDocNew(postData)
      .subscribe((res:any) => {
        this.summaryLoading = false;
        if(res.status == 200){
          this.summaryObj = {...{consumableList:[], workHourManagementList: []}, ...res };
          console.log(this.summaryObj)
          this.summaryId = res.summaryId;
        }else if(res.status == 201){
          // 事件第一次绑定汇总单
          this.summaryId = res.summaryId;
        }else{
          this.message.error(res.msg || '请求数据失败！');
        }
      });
  }

  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 === "delConsumable") {
      //删除-耗材
      let postData = {
        "consumableList": [
          {
            "consumablesId": this.coopData.consumableId,
            "consumablesNum": this.coopData.consumablesNum,
          }
        ],
        "remove": "remove",
        "summaryId": this.summaryId,
      };
      this.mainService
        .addSummaryDoc(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 === "delWorkHourManagement") {
      //删除-工时
      let postData = {
        "workHourManagementList": [
          {
            "workHourId": this.coopData.id,
            "workHourNum": this.coopData.workHourNum2,
          }
        ],
        "remove": "remove",
        "summaryId": this.summaryId,
      };
      this.mainService
        .addSummaryDoc(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);
          }
        });
    }
  }

  // 展示信息提示框（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.getSummaryList();
  }
}




