import { Component, OnInit, Input, Output, EventEmitter, ViewChild, OnChanges, SimpleChanges } from '@angular/core';
import { MainService } from '../../../services/main.service';
import { Router } from '@angular/router';
import { ToolService } from 'src/app/services/tool.service';
import { UploadFile } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import cloneDeep from 'lodash-es/cloneDeep'
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-incident-handle-info',
  templateUrl: './incident-handle-info.component.html',
  styleUrls: ['./incident-handle-info.component.less']
})
export class IncidentHandleInfoComponent implements OnInit, OnChanges {
  @Input() incidentData:any = {};
  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() confirmModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() changeCategoryHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

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

  incidentDataCopy:any =  {};

  changeInpSubject = new Subject(); //防抖

  ngOnChanges(changes: SimpleChanges){
    console.log('changes:', changes)
    // 引入知识库
    if(changes.incidentData && !changes.incidentData.firstChange && changes.incidentData.currentValue){
      this.incidentDataCopy.handleDescription = changes.incidentData.currentValue.handleDescription;
    }
  }

  ngOnInit() {
    console.log('ngOnInit')
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'synergetic'){
        this.getSynergeticList(v[1]);
      }else if(v[0] === 'assetId'){
        this.getAssetList(v[1]);
      }else if(v[0] === 'category'){
        this.getIncidentCategoryList(v[1]);
      }
    });
    this.init();
  }

  init(){
    console.log('初始化')
    this.hosId = this.tool.getCurrentHospital().id;
    console.log('this.incidentData:', this.incidentData)
    this.incidentDataCopy = cloneDeep(this.incidentData);
    this.incidentDataCopy.synergetic = [];
    if(this.incidentDataCopy.category){
      this.incidentDataCopy.category = this.incidentDataCopy.category.id;
    }
    if(this.incidentDataCopy.transSolution === undefined){
      this.incidentDataCopy.transSolution = 0;
    }
    console.log('this.incidentDataCopy:', this.incidentDataCopy)
    this.getHospitalConfig();
    this.getHandleCategorys();
    this.getClosecodes();
    this.getSynergeticList();
    this.getAssetList();
    this.getIncidentCategoryList('', true);
  }

  // 修改故障现象
  changeCategory(id){
    this.changeCategoryHs.emit(id);
  }

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

  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }

  // 获取处理方式列表
  handleCategoryList:any[] = [];
  getHandleCategorys(){
    this.mainService.getDictionary("list", "incident_handle_type").subscribe((data) => {
      this.handleCategoryList = data || [];
      console.log(this.incidentDataCopy)
      if(!this.incidentDataCopy.handleCategory){
        let handleCategory = this.handleCategoryList.find(v => v.value == '1');
        this.incidentDataCopy.handleCategory = handleCategory ? handleCategory.id : undefined;
      }
    });
  }

  // 获取处理结果列表
  closecodeList:any[] = [];
  getClosecodes(){
    this.mainService.getDictionary("list", "incident_closecode").subscribe((data) => {
      this.closecodeList = data || [];
      console.log(this.incidentDataCopy)
      if(!this.incidentDataCopy.closecode){
        let closecode = this.closecodeList.find(v => v.value == '1');
        this.incidentDataCopy.closecode = closecode ? closecode.id : undefined;
      }
    });
  }

  // 获取协同人员
  hosId:any;
  isLoading = false;
  synergeticList: any = [];
  getSynergeticList(keyword = '') {
    let postData = {
      user: {
        hospital: { id: this.incidentDataCopy.duty.id },
        name: keyword,
        simpleQuery: true,
        roleCodes: 'first-line support',
        engineer: 1,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "user", postData)
      .subscribe((data) => {
        this.synergeticList = data.list;
        this.isLoading = false;
      });
  }

  // 获取故障现象
  incidentCategoryList:any[] = [];
  handleInfoLoading:boolean = false;
  getIncidentCategoryList(keyword = '', isInit = false){
    let { hospital, type } = this.tool.getHospitalOrDuty();
    if(type === 'hospital' || type === 'department'){
      this.incidentCategoryList = [];
      this.incidentDataCopy.category = null;
      this.isLoading = false;
      return;
    };
    let postData = {
      category: {
        category: keyword,
        selectType: 'mutlQuery',
        hierarchy: 3,
        dutyIds: type === 'duty' ? hospital.id.toString()  : undefined,
      },
    };
    if(isInit){
      this.handleInfoLoading = true;
    }else{
      this.isLoading = true;
    }
    this.mainService.incidentPost("listIncidentCategory", postData).subscribe(res => {
      this.incidentCategoryList = res.data || [];
      if(isInit){
        this.handleInfoLoading = false;
        if(this.incidentDataCopy.category){
          let obj = this.incidentCategoryList.find(v => v.id == this.incidentDataCopy.category);
          this.incidentDataCopy.category = obj ? obj.id : undefined;
          this.changeCategoryHs.emit(this.incidentDataCopy.category);
        }
      }else{
        this.isLoading = false;
      }
    })
  }

  // 获取院区配置信息
  itsmIncidentAsset: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.itsmIncidentAsset = list.find(v => v.key == 'itsmIncidentAsset') || {};
      });
  }

  // 获取资产列表
  assetList: any = [];
  getAssetList(keyword = '') {
    let postData = {
      asset: {
        hosId: this.hosId,
        name: keyword,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "asset", postData)
      .subscribe((data) => {
        this.assetList = data.list;
      });
  }

  // 图片相关
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };
  fileList = [
    // {
    //   uid: -1,
    //   name: 'xxx.png',
    //   status: '1',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    // }
  ];
  previewImage: string | undefined = '';
  previewVisible = false;

  handlePreview = (file: UploadFile) => {
  	console.log('file1:', file)
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };

  beforeUpload = (file: UploadFile): boolean => {
  	console.log('file2:', file)
    this.fileList = [...this.fileList, file];
    setTimeout(async () => {
      file.url = await this.getBase64(file);
    }, 0);
    console.log('this.fileList:', this.fileList)
    return true;
  };

  // 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!);
  //     }
  //   );
  // };

  getBase64(file: any): Promise<any> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  // 临时上传图片
  temporarilyUrl = this.mainService.returnUploadUrl('temporarily', 0);

  // 上传附件---start
  // model-取消
  maskFlag:boolean = false;
  isShow = false;
  hideExcelImport() {
    this.isShow = false;
  }
  // 触发
  excelImport() {
    this.isShow = true;
  }
  submitExcelImport({fileList}){
    this.isShow = false;
    console.log(fileList);
  }
  // 上传附件---end
  fileList2:any[] = [];

}




