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

@Component({
  selector: 'app-incident-detail',
  templateUrl: './incident-detail.component.html',
  styleUrls: ['./incident-detail.component.less']
})
export class IncidentDetailComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @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 route: ActivatedRoute,
    private message: NzMessageService,
    private tool: ToolService,
    private fb: FormBuilder,
  ) { }

  isLoading = false;
  hosId:any;

  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getDetail();
    this.getIncidentLogList();
  }

  tabs:any[] = [
    { name: '报修信息', value: 1 },
    { name: '处理信息', value: 2 },
    // { name: '质控', value: 3 },
    // { name: '汇总单', value: 4 },
    { name: '评价信息', value: 5 },
  ]

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

    if(this.activeTabValue == 1){
      this.incidentData.callID && this.getCallLog();
      this.incidentData.reqRecord && this.getAudioRequireSrc();
      this.incidentData.reqAttachment && this.getRepairImgs();
    }else if(this.activeTabValue == 2){
      this.getHandleImgs();
      this.getHandleAttachments();
    }else if(this.activeTabValue == 3){

    }else if(this.activeTabValue == 4){

    }else if(this.activeTabValue == 5){

    }
  }

  // 事件详情
  incidentData:any = {};//事件详情
  resolveLogs:any = {};//评价信息
  callbackLogs:any = {};//回访信息
  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 || {};
				if(this.incidentData.wxdegree){
					this.incidentData.wxdegree.value = Number(this.incidentData.wxdegree.value)
				}
        this.clickTbab(this.tabs[0]);

        let logs = this.incidentData.logs || [];
        this.resolveLogs = logs.filter(v => v.logType.value == 'resolve').slice(0, 1);
				this.callbackLogs = logs.filter(v => v.logType.value == 'callback').slice(0, 1);

        this.getHospitalConfig();
      });
  }

  // 获取报修图片
  repairImgs:any[] = [];//报修图片
  getRepairImgs() {
    this.mainService
      .getPreviewImage('wechatRequesterIncident', this.incidentData.id)
      .subscribe((res:any) => {
        res.data = res.data || [];
        res.data.forEach(v => {
          v.previewUrl = location.origin + "/file" + v.relativeFilePath;
          v.thumbFilePath = location.origin + "/file" + v.thumbFilePath;
        })
        this.repairImgs = res.data;
      });
  }

  // 获取处理图片
  handleImgs:any[] = [];//处理图片
  getHandleImgs() {
    this.mainService
      .getPreviewImage('incident', this.incidentData.id)
      .subscribe((res:any) => {
        res.data = res.data || [];
        res.data.forEach(v => {
          v.previewUrl = location.origin + "/file" + v.relativeFilePath;
          v.thumbFilePath = location.origin + "/file" + v.thumbFilePath;
        })
        this.handleImgs = res.data;
      });
  }

  // 获取处理附件
  handleAttachments:any[] = [];//处理图片
  getHandleAttachments() {
    this.mainService
      .getPreviewImage('handleAttachment', this.incidentData.id)
      .subscribe((res:any) => {
        this.handleAttachments = res.data || [];
      });
  }

  // 下载
  download(filename, token) {
    //附件下载
    let downUrl = this.mainService.downloadAttachment(token);
    console.log(downUrl);
    var a = document.createElement("a");
    a.href = downUrl;
    a.target = "_blank";
    a.download = filename;
    document.body.appendChild(a);
    a.click();
  };

  // 预览图片
  imgs = [];
  isPreview = false;
  initialViewIndex:number = 0;
  previewImageHandler(data = [], index = 0) {
    this.initialViewIndex = index;
    console.log(index)
    this.isPreview = false;
    data = data || [];
    this.imgs = data.map((v) => location.origin + '/file' + v.relativeFilePath);
    setTimeout(() => {
      this.isPreview = true;
    }, 0)
  }

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

  // 获取通话音频
  audioSrc =  '';//音频
  getCallLog() {
    let postData = {
      idx: 0,
      sum: 1,
      callLog: {callAccept: this.incidentData.callID},
    };
    this.mainService
      .getFetchDataList('simple/data', 'callLog', postData)
      .subscribe((result) => {
        if(result.status == 200){
          result.list = result.list || [];
          if(result.list.length){
            if(result.list[0].path){
              this.mainService.getCallLogPath({ path: result.list[0].path, hosId: result.list[0].hosId }).subscribe((result) => {
                if (result["state"] == 200) {
                  this.audioSrc = location.origin + result["relativePath"];
                }else{
                  this.audioSrc = '';
                }
              });
            }else{
              this.audioSrc = '';
            }
          }else{
            this.audioSrc = '';
          }
        }else{
          this.message.error(result.msg || '请求数据失败！');
        }
      });
  }

  // 获取报修录音
  audioRequireSrc =  '';//音频
  getAudioRequireSrc() {
    this.mainService
      .getPreviewImage('wechatIncidentRecord', this.incidentData.id)
      .subscribe((res:any) => {
        res.data = res.data || [];
        if(res.data.length){
          res.data.forEach(v => {
            v.previewUrl = location.origin + "/file" + v.relativeFilePath;
          })
          this.audioRequireSrc = res.data[0].previewUrl;
        }else{
          this.audioRequireSrc = '';
        }
      });
  }

  maskFlag:any = false;
  // 获取处理流程
  incidentLogList:any[] = [];
  getIncidentLogList(){
    let postData = {
      "idx": 0,
      "sum": 9999,
      "incidentLog": {
          "incidentId": this.id,
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "incidentLog", postData)
      .subscribe((result) => {
        this.incidentLogList = result.list || {};
      });
  }

  // 处理人
  get computedHandlerUser(){
    if(this.incidentData.state.value == 'pending' && this.incidentData.currentLog){
      return this.incidentData.currentLog.workerName;
    }
    if(this.incidentData.state.value != 'pending' && this.incidentData.handlingPersonnelUser){
      return this.incidentData.handlingPersonnelUser.name;
    }
  }

  // 协同人
  get computedSynergeticUser(){
    return this.incidentData.synergetic && this.incidentData.synergetic.length ? this.incidentData.synergetic.map(v => v.name).join('，') : '';
  }

  // 获取院区配置信息
  itsmSummarySheet: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') || {};
        console.log(this.itsmSummarySheet)
        // 维修汇总单
        if(this.incidentData.state.value == 'close' && this.itsmSummarySheet.value == 1 && this.incidentData.summaryId){
          let flag = this.tabs.some(v => v.value === 4);
          !flag && this.tabs.splice(2, 0, {name: '汇总单', value: 4});
        }
      });
  }
}




