import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { MainService } from '../../../services/main.service';
import { Router } from '@angular/router';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService } from 'ng-zorro-antd';
import { ToolService } from 'src/app/services/tool.service';
import { forkJoin } from 'rxjs';
import { IncidentHandleInfoComponent } from '../incident-handle-info/incident-handle-info.component';
import { IncidentHandleInfoSimpleComponent } from '../incident-handle-info-simple/incident-handle-info-simple.component';
import cloneDeep from 'lodash-es/cloneDeep'
import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-incident-handle',
  templateUrl: './incident-handle.component.html',
  styleUrls: ['./incident-handle.component.less']
})
export class IncidentHandleComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;

  @ViewChild(IncidentHandleInfoComponent, { static: false }) incidentHandleInfoComponent: IncidentHandleInfoComponent;
  @ViewChild(IncidentHandleInfoSimpleComponent, { static: false }) incidentHandleInfoSimpleComponent: IncidentHandleInfoSimpleComponent;

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

  @Input() id: any;

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

  isLoading = false;
  hosId:any;

  tabs:any[] = [
    { name: '处理信息', value: 1 },
    // { name: '汇总单', value: 2 },
  ]

  // 点击tab
  activeTabValue:any = 1;
  clickTbab(item){
    this.activeTabValue = item.value;
  }

  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getDetail();
  }
  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }
  // 是否进入汇总单
  isInSummaryOrder(){
    return this.incidentData.duty && this.itsmSummarySheet.value == 1 && (this.incidentData.handlingPersonnelUser.id == this.tool.getCurrentUserId());
  }

  // 获取院区配置信息
  itsmSummarySheet:any = {};//是否需要填写汇总单
  itsmSimpleHandle:any = {};//是否简单处理
	itsmWriteSolution: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.itsmSummarySheet = list.find(v => v.key == 'itsmSummarySheet') || {};
        this.itsmSimpleHandle = list.find(v => v.key == 'itsmSimpleHandle') || {};
				this.itsmWriteSolution = list.find(v => v.key == 'itsmWriteSolution') || {};
        if(this.isInSummaryOrder()){
          let summary = this.tabs.some(v => v.value == 2);
          console.log(summary)
          !summary && this.tabs.push({ name: '汇总单', value: 2 });
        }
      });
  }

  // 判断工单当前状态
  compareStateValue(incidentData){
    if(incidentData.state.value !== 'handler'){
      this.message.warning('工单状态异常！请刷新页面再重试');
      this.hideModal();
    }
  }

  // 获取详情数据
  incidentData:any;
  maskFlag:any = false;
  getDetail() {
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchData("simple/data", "incident", this.id)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.incidentData = result.data || {};

        this.compareStateValue(this.incidentData);

        this.getDictionaryList();
        this.getHospitalConfig();
      });
  }

  //获取知识库状态/类型
  knowageLoading:boolean = false;
  getDictionaryList() {
    this.knowageLoading = true;
    let solutionStatus$ = this.mainService.getDictionary('list', 'solution_status', true);
    let solutionType$ = this.mainService.getDictionary('list', 'solution_type', true);
    forkJoin(solutionStatus$, solutionType$).subscribe((data:any[]) => {
      this.knowageLoading = false;
      let solutionStatusList = data[0] || [];
      let solutionTypeList = data[1] || [];

      this.solutionStatus = solutionStatusList.find(item => item.value == 3);
      	console.log('this.solutionStatus:', this.solutionStatus)
      this.solutionType = solutionTypeList.find(item => item.value == 1);
      	console.log('this.solutionType:', this.solutionType)
    })
  }
  solutionStatus;//知识库状态
  solutionType;//知识库类型
  // 修改故障现象
  changeCategoryHs(categoryId){
    this.getKnowledgeList(categoryId);
  }

  // 获取知识库
  knowageList:any[] =  [];
  getKnowledgeList(categoryId) {
    if(!(categoryId && this.solutionStatus && this.solutionType)){
      this.knowageLoading = false;
      this.knowageList = [];
      return;
    }
    this.knowageLoading = true;
    let postData:any = {
      idx: 0,
      sum: 9999,
      solution: {
        categoryId,
				status: this.solutionStatus,
				type: this.solutionType,
      },
    };

    this.mainService
      .getFetchDataList('simple/data', 'solution', postData)
      .subscribe((result) => {
        this.knowageLoading = false;
        if(result.status == 200){
          this.knowageList = result.list || [];
        }else{
          this.message.error(result.msg || '请求数据失败！');
        }
      });
  }

  // 知识库查看-知道了
  coopData:any = {};
  isShowKnowledge:boolean = false;
  showKnowledgeModal(data) {
    this.coopData = data || {};
    this.isShowKnowledge = true;
  }

  cancelKnowledgeModal(flag) {
    this.isShowKnowledge = false;
  }

  // 图片上传
  uploadImages(file, id){
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', file.name);
    const req = new HttpRequest('Post', this.mainService.returnUploadUrl('incident', id), formData, {
      reportProgress: true
    });
    return this.http.request(req).pipe(filter(e => e instanceof HttpResponse)).toPromise();
  }

  // 附件上传
  uploadFiles(file, id){
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', file.name);
    const req = new HttpRequest('Post', this.mainService.returnUploadUrl('handleAttachment', id), formData, {
      reportProgress: true
    });
    return this.http.request(req).pipe(filter(e => e instanceof HttpResponse)).toPromise();
  }

  // 引入知识库
  solutionId;//引用的知识库Id
  importKnowage(item){
    console.log(item)
    this.incidentData = {...this.incidentData, handleDescription:  `引用知识库解决，知识库编号：${item.solutionNumber}`};
    this.solutionId = item.id;
  }

  // 表单提交
  submitForm() {
    console.log(this.itsmSimpleHandle.value)
    if(this.itsmSimpleHandle.value == 0){
      // 详细处理
      console.log(this.incidentHandleInfoComponent)
      // return;
      if(!this.incidentHandleInfoComponent.incidentDataCopy.handleDescription){
        this.message.warning('请选择解决方案！');
        return;
      }
      if(!this.incidentHandleInfoComponent.incidentDataCopy.category){
        this.message.warning('请选择故障现象！');
        return;
      }
      if(!this.incidentHandleInfoComponent.incidentDataCopy.handleCategory){
        this.message.warning('请选择处理方式！');
        return;
      }
      if(!this.incidentHandleInfoComponent.incidentDataCopy.closecode){
        this.message.warning('请选择处理结果！');
        return;
      }

      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;

      let incidentDataCopy = cloneDeep(this.incidentHandleInfoComponent.incidentDataCopy);

      // 图片上传
      if(this.incidentHandleInfoComponent.fileList.length){
        console.log(this.incidentHandleInfoComponent.fileList.map(v => v.originFileObj));
        this.incidentHandleInfoComponent.fileList.map(v => v.originFileObj).forEach(async file => {
          await this.uploadImages(file, incidentDataCopy.id);
        })
      }
      // return;

      // 附件上传
      if(this.incidentHandleInfoComponent.fileList2.length){
        console.log(this.incidentHandleInfoComponent.fileList2.map(v => v.originFileObj));
        this.incidentHandleInfoComponent.fileList2.map(v => v.originFileObj).forEach(async file => {
          await this.uploadFiles(file, incidentDataCopy.id);
        })
      }
      // return;

      let postData = {
        solutionId: this.solutionId,
        incident: {
          ...incidentDataCopy,
          handleCategory: incidentDataCopy.handleCategory ? { id: incidentDataCopy.handleCategory }: undefined,
          closecode: incidentDataCopy.closecode ? { id: incidentDataCopy.closecode }: undefined,
          synergetic: incidentDataCopy.synergetic.length ? incidentDataCopy.synergetic.map(v => ({id: v})): undefined,
          category: incidentDataCopy.category ? { id: incidentDataCopy.category }: undefined,
        },
      }

      console.log(postData);
      // return;
      this.mainService
      .flowPost("incident/task/doing", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.confirmModelHs.emit();

        if (result.state == 200) {
          this.message.success('处理成功');
        } else {
          this.message.error(result.msg || '处理失败');
        }
      });
    }else if(this.itsmSimpleHandle.value == 1){
      // 简单处理
      console.log(this.incidentHandleInfoSimpleComponent)
      // return;
			if(this.itsmWriteSolution.value==1){
				if(!this.incidentHandleInfoSimpleComponent.incidentDataCopy.handleDescription){
				  this.message.warning('请选择解决方案！');
				  return;
				}
			}
			
      if(!this.incidentHandleInfoSimpleComponent.incidentDataCopy.handleCategory){
        this.message.warning('请选择处理方式！');
        return;
      }

      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;

      let incidentDataCopy = cloneDeep(this.incidentHandleInfoSimpleComponent.incidentDataCopy);

      // 图片上传
      if(this.incidentHandleInfoSimpleComponent.fileList.length){
        console.log(this.incidentHandleInfoSimpleComponent.fileList.map(v => v.originFileObj));
        this.incidentHandleInfoSimpleComponent.fileList.map(v => v.originFileObj).forEach(async file => {
          await this.uploadImages(file, incidentDataCopy.id);
        })
      }
      // return;

      let postData = {
        incident: {
          ...incidentDataCopy,
          handleCategory: incidentDataCopy.handleCategory ? { id: incidentDataCopy.handleCategory }: undefined,
          closecode: incidentDataCopy.closecode ? { id: incidentDataCopy.closecode }: undefined,
          synergetic: incidentDataCopy.synergetic.length ? incidentDataCopy.synergetic.map(v => ({id: v})): undefined,
        },
      }

      console.log(postData);

      this.mainService
      .flowPost("incident/task/doing", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.confirmModelHs.emit();

        if (result.state == 200) {
          this.message.success('处理成功');
        } else {
          this.message.error(result.msg || '处理失败');
        }
      });
    }
  }
}




