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 { NzMessageService, UploadFile } from 'ng-zorro-antd';
import cloneDeep from 'lodash-es/cloneDeep'
import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { HttpClient, HttpEvent, HttpResponse, HttpEventType, HttpRequest } from '@angular/common/http';

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

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

  incidentDataCopy:any =  {};

  changeInpSubject = new Subject(); //防抖

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

  init(){
    console.log('初始化', this.incidentData)
    this.hosId = this.tool.getCurrentHospital().id;
    this.incidentDataCopy = cloneDeep(this.incidentData);
    this.incidentDataCopy.synergetic = [];
    this.getHospitalConfig();
    this.getHandleCategorys();
    this.getClosecodes();
    this.getSynergeticList();
    this.getAssetList('load', '');
  }

  // 边输边搜节流阀
  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;
      });
  }

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

  // 获取资产列表
  assetList: any = [];
  getAssetList(type, keyword = '') {
    let postData = {
      asset: {
        downHosId: this.hosId,
        name: keyword,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "asset", postData)
      .subscribe((data) => {
				this.isLoading = false;
        this.assetList = data.list;
				if(this.incidentDataCopy.assetDTO && type=='load'){
					this.incidentDataCopy.assetId = Number(this.incidentDataCopy.assetId)
				}
      });
  }

  // 图片相关
  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);
}




