import { Component, OnInit, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import { MainService } from '../../../services/main.service';
import { Router, ActivatedRoute } from '@angular/router';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { ToolService } from 'src/app/services/tool.service';
import { format } from 'date-fns';
import { Subject, forkJoin } from 'rxjs';
import { debounceTime, filter } from 'rxjs/operators';
import cloneDeep from 'lodash-es/cloneDeep'
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-incident-create',
  templateUrl: './incident-create.component.html',
  styleUrls: ['./incident-create.component.less']
})
export class IncidentCreateComponent implements OnInit {
  @ViewChild("tab", { static: false }) elementView: ElementRef;
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() confirmModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

  @Input() id: any;

  currentTabIndex = ""; //获取任务类型的key
  // 运维相关
  incidentModel:any = {};
  incidentMsg:any = {};
  //防抖
  changeInpSubject = new Subject();
  changeCommonInpSubject = new Subject();

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

  isLoading = false;

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchApplicationDepartment(v[0], v[1]);
    });
    this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'requester'){
        this.searchApplicationRequester(v[1]);
      }else if(v[0] === 'category'){
        this.searchApplicationCategory(v[1]);
      }else if(v[0] === 'group'){
        this.searchApplicationGroup(v[1]);
      }else if(v[0] === 'user'){
        this.searchApplicationUser(v[1]);
      }
    });
    if(this.id){
      // 编辑
      this.getDetail();
    }else{

    }
  }

  disX = 0; //移动的距离
  disStep = 0; //移动的步长
  // tab任务类型向左移动
  toLeft() {
    let maxStep = this.workTypesArrange.length - 5;
    this.disStep = Math.max(-maxStep, --this.disStep);
    this.disX = (this.disStep * this.elementView.nativeElement.offsetWidth) / 5;
  }
  // tab任务类型向右移动
  toRight() {
    this.disStep = Math.min(0, ++this.disStep);
    this.disX = (this.disStep * this.elementView.nativeElement.offsetWidth) / 5;
  }

  // 编辑-弹窗
  edit(data){
    this.editOrder = cloneDeep(data);
    let incidentModel = cloneDeep(data);
    let incidentMsg:any = {};
    console.log('data:', data)
    incidentModel.department && (incidentMsg.deptManyPhone = incidentModel.department.manyPhone);
    incidentModel.department && (incidentMsg.deptName = incidentModel.department.dept);
    incidentModel.department && (incidentModel.department = incidentModel.department.id);
    incidentModel.requester && (this.applicationRequesterList = [cloneDeep(incidentModel.requester)]);
    incidentModel.requester && (incidentMsg.requesterPhone = incidentModel.requester.phone);
    incidentModel.requester && (incidentMsg.requesterName = incidentModel.requester.name);
    incidentModel.requester && (incidentModel.requester = incidentModel.requester.id);
    incidentModel.repairIncidentType && (incidentModel.repairIncidentType = incidentModel.repairIncidentType.value);
    incidentModel.source && (incidentModel.source = incidentModel.source.id);
    incidentModel.area && (incidentModel.area = incidentModel.area.id);
    incidentModel.place && (incidentModel.place = incidentModel.place.id);
    incidentModel.category && (this.applicationCategoryList = [cloneDeep(incidentModel.category)]);
    incidentModel.category && (incidentModel.category = incidentModel.category.id);

    this.incidentModel = incidentModel;
    this.incidentMsg = incidentMsg;
    console.log('this.applicationRequesterList:', this.applicationRequesterList)
    console.log('this.applicationDeptList:', this.applicationDeptList)
    console.log('incidentModel:', incidentModel)
    this.showNewOrder('', '', true, '编辑事件');

    // 查询报修图片
    this.getRepairImgs(data.id);
  }

  // 获取报修图片
  repairImgs:any[] = [];//报修图片
  getRepairImgs(incidentId) {
    this.mainService
      .getPreviewImage('wechatRequesterIncident', incidentId)
      .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;
      });
  }

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

  // 事件详情
  incidentData:any = {};
  getDetail(){
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchData("simple/data", "incident", this.id)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;
        this.incidentData = result.data || {};
        this.compareStateValue(this.incidentData);
        this.edit(this.incidentData);
      });
  }

  // 边输边搜节流阀
  WSNum = 0;
  changeInp(type, e) {
    this.changeInpSubject.next([type, e]);
  }
  changeCommonInp(type, e) {
    this.changeCommonInpSubject.next([type, e]);
  }

  // 院区列表
  applicationHospitalList:any[] = [];
  searchApplicationHospital() {
    let dataObj = {
      idx: 0,
      sum: 9999,
      hospital: {
        selectType:'level1',
      },
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "hospital", dataObj)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationHospitalList = data.list;
        }
      });
  }
  // 选择院区
  changeApplyHospital(e){
    console.log(e);

    this.incidentModel.department = undefined;
    this.searchApplicationDepartment('itsm');

    if(this.buildType !== '报修转事件'){
      this.incidentModel.requester = undefined;
      this.searchApplicationRequester();
    }
    this.applicationRequesterList = [];

    this.incidentModel.area = undefined;
    this.searchApplicationBuilding();

    this.incidentModel.place = undefined;
    this.applicationFloorList = [];

    this.incidentModel.houseNumber = undefined;
    this.incidentModel.duty = undefined;

    // 根据院区和故障现象带出责任部门，优先级，维修人/组
    if(this.incidentModel.category && e && this.buildType !== '编辑事件'){
      let postData = {
        idx: 0,
        sum: 9999,
        incidentCategoryConfig: {
          categoryId: this.incidentModel.category,
          hosId: e,
        },
      };
      console.log(postData);
      // return;
      this.isLoading = true;
      this.mainService
        .getFetchDataList("simple/data", "incidentCategoryConfig", postData)
        .subscribe((data) => {
          this.isLoading = false;
          if (data.status == 200) {
            let list = data.list || [];
            if(list.length > 0){
              console.log(list[0]);
              this.incidentCategoryConfig = list[0];
            }else{
              this.incidentCategoryConfig = {};
            }

            // 根据院区和故障现象带出责任部门，优先级，维修人/组
            this.incidentModel.duty = this.incidentCategoryConfig.dutyDTO;
            this.incidentModel.priorityId = this.incidentCategoryConfig.priority;

            // 回显维修人/组
            this.showGroupOrUser();
          }
        });
    }else{
      this.incidentModel.group = undefined;
      this.applicationGroupList = [];
      this.incidentModel.user = undefined;
      this.applicationUserList = [];
    }
  }
  // 申请人列表（搜索）
  applicationRequesterList:any[] = [];
  isRelatedDepartment:boolean = true;
  searchApplicationRequester(keyWord?) {
    // 关联查询，且没选择申请科室
    if(this.isRelatedDepartment && !this.incidentModel.department){
      this.applicationRequesterList = [];
      return;
    }
    // 不关联查询，且没选择院区
    if(!this.isRelatedDepartment && !this.incidentModel.hosId){
      this.applicationRequesterList = [];
      return;
    }
    let postData = {
      idx: 0,
      sum: 20,
      user: {
        hospital: this.isRelatedDepartment ? undefined : { id: this.incidentModel.hosId },
        dept: this.isRelatedDepartment ? { id: this.incidentModel.department } : undefined,
        name: keyWord,
        // simpleQuery: true,
      },
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationRequesterList = data.list;
        }
      });
  }
  // 修改申请人
  changeApplyRequester(e){
    console.log(e)
    let userObj = this.applicationRequesterList.find(v => v.id == e);
    // 选择申请人回显申请人电话
    if(userObj){
      this.incidentMsg.requesterPhone = userObj.phone;
    }
  }
  // 故障现象列表
  applicationCategoryList:any[] = [];
  searchApplicationCategory(keyWord?) {
    let dutyIds;
    if(this.buildType === '编辑事件'){
      dutyIds = this.incidentModel.duty.id.toString();
    }

    let postData = {
      category: {
        category: keyWord,
        selectType: 'mutlQuery',
        hierarchy: 3,//只差有三级的故障现象列表
        dutyIds,
      },
    };
    console.log(postData);
    // return;
    this.isLoading = true;
    this.mainService
      .incidentPost("listIncidentCategory", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationCategoryList = data.data;
        }
      });
  }
  // 修改故障现象
  incidentCategoryConfig:any = {};//当前匹配的故障现象规则
  changeApplyCategory(e){
    console.log(e)
    // 知识库
    this.getKnowageList();
    if(e){
      // 根据故障现象带出故障描述
      if(this.incidentModel.description){
        this.incidentModel.description = this.incidentModel.description + '；' + this.applicationCategoryList.find(v => v.id == e).mutiCategory;
      }else{
        this.incidentModel.description = this.applicationCategoryList.find(v => v.id == e).mutiCategory;
      }
    }
    // 根据院区和故障现象带出责任部门，优先级，维修人/组
    if(this.incidentModel.hosId && e && this.buildType !== '编辑事件'){
      let postData = {
        idx: 0,
        sum: 9999,
        incidentCategoryConfig: {
          categoryId: e,
          hosId: this.incidentModel.hosId,
        },
      };
      console.log(postData);
      // return;
      this.isLoading = true;
      this.mainService
        .getFetchDataList("simple/data", "incidentCategoryConfig", postData)
        .subscribe((data) => {
          this.isLoading = false;
          if (data.status == 200) {
            let list = data.list || [];
            if(list.length > 0){
              console.log(list[0]);
              this.incidentCategoryConfig = list[0];
            }else{
              this.incidentCategoryConfig = {};
            }

            // 根据院区和故障现象带出责任部门，优先级，维修人/组
            this.incidentModel.duty = this.incidentCategoryConfig.dutyDTO;
            this.incidentModel.priorityId = this.incidentCategoryConfig.priority;

            // 回显维修人/组
            this.showGroupOrUser();
          }
        });
    }else{
      this.incidentModel.group = undefined;
      this.applicationGroupList = [];
      this.incidentModel.user = undefined;
      this.applicationUserList = [];
    }
  }

  // 回显维修人/组
  showGroupOrUser(){
    // 先判断科室绑定人/组
    if(this.incidentModel.department && this.incidentModel.category && this.incidentModel.duty){
      let postData = {
        idx: 0,
        sum: 10,
        incidentAssignManager: {
          deptId: this.incidentModel.department,
          categoryId: this.incidentModel.category,
          hosId: this.incidentModel.duty.id,
          operationType: 'queryConfig',
        },
      };

      this.mainService
        .getFetchDataList("simple/data", "incidentAssignManager", postData)
        .subscribe((result) => {
          if (result.status == 200) {
            var deptBinduserConfig = result.list.length ? result.list[0] : null;//获取第一条配置
            if(deptBinduserConfig){
              console.log('deptBinduserConfig:', deptBinduserConfig)
              // 如果有科室绑定人员的配置
              if(deptBinduserConfig.handleGroupDTO){
                this.incidentModel.group = deptBinduserConfig.handleGroupDTO.id;
                this.applicationGroupList = [deptBinduserConfig.handleGroupDTO];
              }else{
                this.incidentModel.group = undefined;
                this.applicationGroupList = [];
              }

              if(deptBinduserConfig.handleUserDTO){
                this.incidentModel.user = deptBinduserConfig.handleUserDTO.id;
                this.applicationUserList = [deptBinduserConfig.handleUserDTO];
              }else{
                this.incidentModel.user = undefined;
                this.applicationUserList = [];
              }
            }else{
              if(this.incidentModel.category){
                // 选择了故障现象
                if(this.incidentCategoryConfig.groupId && this.incidentCategoryConfig.groupDTO){
                  this.incidentModel.group = this.incidentCategoryConfig.groupId;
                  this.applicationGroupList = [this.incidentCategoryConfig.groupDTO];
                }else{
                  this.incidentModel.group = undefined;
                  this.applicationGroupList = [];
                }

                if(this.incidentCategoryConfig.userId && this.incidentCategoryConfig.userDTO){
                  this.incidentModel.user = this.incidentCategoryConfig.userId;
                  this.applicationUserList = [this.incidentCategoryConfig.userDTO];
                }else{
                  this.incidentModel.user = undefined;
                  this.applicationUserList = [];
                }
              }
            }
          }
        });
    }else{
      if(this.incidentModel.category){
        // 选择了故障现象
        if(this.incidentCategoryConfig.groupId && this.incidentCategoryConfig.groupDTO){
          this.incidentModel.group = this.incidentCategoryConfig.groupId;
          this.applicationGroupList = [this.incidentCategoryConfig.groupDTO];
        }else{
          this.incidentModel.group = undefined;
          this.applicationGroupList = [];
        }

        if(this.incidentCategoryConfig.userId && this.incidentCategoryConfig.userDTO){
          this.incidentModel.user = this.incidentCategoryConfig.userId;
          this.applicationUserList = [this.incidentCategoryConfig.userDTO];
        }else{
          this.incidentModel.user = undefined;
          this.applicationUserList = [];
        }
      }
    }
  }

  // 预览图片
  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)
  }

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

  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);
  // 处理组列表
  applicationGroupList:any[] = [];
  searchApplicationGroup(keyWord?) {
    if(!this.incidentModel.duty){
      this.incidentModel.group = undefined;
      this.applicationGroupList = [];
      this.incidentModel.user = undefined;
      this.applicationUserList = [];
      return;
    }
    let postData = {
      idx: 0,
      sum: 20,
      group2: {
        groupName: keyWord,
        hospitals: this.incidentModel.duty ? this.incidentModel.duty.id.toString() : undefined,
        type: 3,
      },
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "group2", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationGroupList = data.list;
        }
      });
  }
  // 修改处理组
  changeApplyGroup(e){
    console.log(e);
    this.incidentModel.user = undefined;
    this.searchApplicationUser();
  }
  // 处理人列表
  applicationUserList:any[] = [];
  searchApplicationUser(keyWord?) {
    let postData = {
      idx: 0,
      sum: 20,
      user: {
        name:keyWord,
				groupdata: this.incidentModel.group ? { id: this.incidentModel.group } : undefined,
        roleCodes: 'first-line support',
        engineer: 1,
        simpleQuery: true,
      },
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationUserList = data.list;
        }
      });
  }
  // 优先级列表
  applicationPriorityList:any[] = [];
  searchApplicationPriority(keyWord?) {
    let postData = {
      idx: 0,
      sum: 9999,
      priority: {},
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "priority", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationPriorityList = data.list;
          // 回显报修来源
          let source = this.applicationSourceList.find(v => v.value === 'phone');
          if(!this.incidentModel.source && source){
            this.incidentModel.source = source.id;
          }
        }
      });
  }
  // 报修来源列表
  applicationSourceList:any[] = [];
  searchApplicationSource(keyWord?) {
    this.mainService.getDictionary("list", "incident_source").subscribe((data) => {
      this.applicationSourceList = data || [];
    });
  }
  // 报修类型列表
  repairIncidentTypeList:any[] = [];
  getRepairIncidentType() {
    this.mainService.getDictionary("list", "repair_incident_type").subscribe((data) => {
      this.repairIncidentTypeList = data || [];
    });
  }
  // 选择报修类型
  changeRepairIncidentType(value){
    this.incidentModel.department = undefined;
    this.isRelatedDepartment = false;
    this.changeApplyRelatedDepartment(this.isRelatedDepartment);
  }
  // 楼栋列表
  applicationBuildingList:any[] = [];
  searchApplicationBuilding(keyWord?, buildingId?) {
    let postData = {
      idx: 0,
      sum: 9999,
      building: {
        cascadeHosId: this.incidentModel.hosId,
      },
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "building", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationBuildingList = data.list;
          if(buildingId){
            let hasBuildingId = this.applicationBuildingList.some(v => v.id == buildingId);
            if(hasBuildingId){
              this.incidentModel.area = buildingId;
            }else{
              this.incidentModel.area = undefined;
            }
          }
        }
      });
  }
  // 修改楼栋
  changeApplyBuilding(e){
    console.log(e)
    this.incidentModel.place = undefined;
    this.searchApplicationFloor();
  }
  // 楼层列表
  applicationFloorList:any[] = [];
  searchApplicationFloor(keyWord?, floorId?, buildingId?) {
    let postData = {
      idx: 0,
      sum: 9999,
      floor: {
        buildId: buildingId || this.incidentModel.area || undefined,
        hosId: this.incidentModel.hosId,
      },
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "floor", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.applicationFloorList = data.list;
          if(floorId){
            let hasFloorId = this.applicationFloorList.some(v => v.id == floorId);
            if(hasFloorId){
              this.incidentModel.place = floorId;
            }else{
              this.incidentModel.place = undefined;
            }
          }
        }
      });
  }
  // 修改关联查
  changeApplyRelatedDepartment(e){
    if(this.buildType !== '报修转事件'){
      this.incidentModel.requester = undefined;
    }
    this.searchApplicationRequester();
  }
  // 申请科室列表（搜索）
  isLoadingApply: boolean = false;
  applicationDeptList:any[] = [];
  searchApplicationDepartment(type, e?, phone?, deptId?, isInit?) {
    let keyWord = "";
    if (e && e !== "&ks&" && e !== "&go&") {
      keyWord = e;
    }
    let cascadeHosId;
    if(type == 'itsm'){
      cascadeHosId = this.incidentModel.hosId || undefined;
    }
    let dataObj = {
      idx: 0,
      sum: 20,
      department: {
        searchType: type == 'itsm' ? undefined : 1,// 简单查询
        cascadeHosId,
        keyWord: keyWord,
        flag: 1,
      },
    };
    this.WSNum++;
    this.isLoadingApply = true;
    this.mainService
      .getFetchDataList("data", "department", dataObj)
      .subscribe((data) => {
        this.WSNum--;
        if (this.WSNum === 0) {
          this.isLoadingApply = false;
        }
        if (data.status == 200) {
          if(type == 'itsm'){
            this.applicationDeptList = data.list;
            let ids = this.applicationDeptList.map(v => v.id);
            isInit && !ids.includes(this.incidentModel.department) && (this.applicationDeptList.unshift({id: this.incidentModel.department, dept: this.incidentMsg.deptName}))
            console.log(this.applicationDeptList);
            console.log(this.incidentModel);
            console.log(this.incidentMsg);
            deptId && this.changeApplyDept(deptId);
          }
        }
      });
  }
  openChangeApplyDept(flag){
    flag && this.searchApplicationDepartment('itsm');
  }
  openChangeApplyRequester(flag){
    flag && this.searchApplicationRequester();
  }
  openChangeApplyCategory(flag){
    flag && this.searchApplicationCategory();
  }
  openChangeApplyGroup(flag){
    flag && this.searchApplicationGroup()
  }
  openChangeApplyUser(flag){
    flag && this.searchApplicationUser()
  }

  // 运维-选择科室
  changeApplyDept(e) {
    console.log(e, this.applicationDeptList);

    if(this.incidentModel.department && this.currentTabIndex === '故障报修'){
      this.rightTitle_tab = [
        { id: 2, name: '近期维修' },
        { id: 3, name: '知识库' },
      ]
      this.rightTitleHandler(this.rightTitle_tab[0].id);
    }

    let deptObj = this.applicationDeptList.find(v => v.id == e);

    // 选择科室回显一级院区
    if(!this.incidentModel.hosId){
      if(deptObj){
        this.incidentModel.hosId = deptObj.hospital.parent ? deptObj.hospital.parent.id : deptObj.hospital.id;
      }

      this.incidentModel.area = undefined;
      this.searchApplicationBuilding();

      this.incidentModel.place = undefined;
      this.applicationFloorList = [];
    }

    // 选择科室回显科室电话，楼栋，楼层，地址
    if(deptObj){
      console.log('deptObj:', deptObj)
      this.incidentMsg.deptManyPhone = deptObj.manyPhone;
      let buildingId = deptObj.building ? deptObj.building.id : undefined;
      buildingId && this.searchApplicationBuilding('', buildingId);
      let floorId = deptObj.floor ? deptObj.floor.id : undefined;
      buildingId && floorId && this.searchApplicationFloor('', floorId, buildingId);
      this.incidentModel.houseNumber = deptObj.address;
    }

    // 刷新申请人列表
    if(this.buildType !== '报修转事件'){
      this.incidentModel.requester = undefined;
    }
    this.searchApplicationRequester();

    // 根据院区和故障现象带出责任部门，优先级，维修人/组
    if(this.incidentModel.category && this.incidentModel.hosId && this.buildType !== '编辑事件'){
      let postData = {
        idx: 0,
        sum: 9999,
        incidentCategoryConfig: {
          categoryId: this.incidentModel.category,
          hosId: this.incidentModel.hosId,
        },
      };
      console.log(postData);
      // return;
      this.isLoading = true;
      this.mainService
        .getFetchDataList("simple/data", "incidentCategoryConfig", postData)
        .subscribe((data) => {
          this.isLoading = false;
          if (data.status == 200) {
            let list = data.list || [];
            if(list.length > 0){
              console.log(list[0]);
              this.incidentCategoryConfig = list[0];
            }else{
              this.incidentCategoryConfig = {};
            }

            // 根据院区和故障现象带出责任部门，优先级，维修人/组
            this.incidentModel.duty = this.incidentCategoryConfig.dutyDTO;
            this.incidentModel.priorityId = this.incidentCategoryConfig.priority;

            // 回显维修人/组
            this.showGroupOrUser();
          }
        });
    }else{
      // 回显维修人/组
      this.showGroupOrUser();
    }
  }

  // 是否连续建单
  isBuildOrderAgagin:boolean = false;
  maskFlag:any = false;
  // 运维-直接解决
  directOrder(){
    if(this.incidentModel.repairIncidentType === 'public' && !this.incidentModel.requester){
      this.msg.warning('请选择申请人!');
      return;
    }

    if(!this.incidentModel.category){
      this.msg.warning('请选择故障现象!');
      return;
    }

    let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
    if(!this.incidentModel.duty){
      this.msg.warning(`故障现象【${category.mutiCategory}】没有设置责任部门!`);
      return;
    }

    if(this.incidentModel.repairIncidentType === 'dept' && !this.incidentModel.department){
      this.msg.warning('请选择申请科室!');
      return;
    }

    if(!this.incidentModel.contactsInformation){
      this.msg.warning('请填写联系电话!');
      return;
    }

    if(!this.incidentModel.priorityId){
      this.msg.warning('请选择优先级!');
      return;
    }

    if(!this.incidentModel.description){
      this.msg.warning('请选择故障描述!');
      return;
    }

    this.showDirectOrder();
  }
  // 直接解决-弹窗
  directOrderModalShow = false; //弹窗开关
  showDirectOrder() {
    this.directOrderModalShow = true;
  }
  // 关闭弹窗
  closeDirectOrderModelOrder(e) {
    this.directOrderModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmDirectOrderModelOrder(incidentModel){
    console.log(incidentModel);
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.incidentModel = {...this.incidentModel, ...incidentModel};

    let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
    let postData:any = {
      solutionId: this.solutionId,
      "incident": {
        "id": this.incidentModel.id || undefined,
        "deleteFlag": 0,
        "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
        "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
        "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
        "alarmType": false,
        "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
        "contactsInformation": this.incidentModel.contactsInformation,
        "contacts": this.incidentModel.contacts,
        "hosId": this.incidentModel.hosId || undefined,
        "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
        "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
        "houseNumber": this.incidentModel.houseNumber,
        "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
        "priorityId": this.incidentModel.priorityId || undefined,
        "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
        // "title": category.mutiCategory,
        "description": this.incidentModel.description,
        "directProcess": 1,
        "handleDescription": this.incidentModel.handleDescription,
        "handlingPersonnelUser": {id: this.tool.getCurrentUserId()},
        "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
        "closecode": this.incidentModel.closecode ? { id: this.incidentModel.closecode } : undefined,
        "acceptUser": { id: this.tool.getCurrentUserId() },
        "callID": this.incidentModel.callID || undefined,
        "incomingPhone": this.incidentModel.incomingPhone || undefined,
        "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
      },
    };

    if(this.buildType){
      if(this.buildType === '报修转事件'){
        postData.incident.fromWx = true;
      }
      if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
        postData.incident = Object.assign({}, postData.incident);
      }else{
        postData.incident = Object.assign({}, this.editOrder, postData.incident);
      }
    }

    this.mainService
      .flowPost("incident/task/accept", postData)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;

        if (result.state == 200) {
          // 图片上传
          if(this.fileList.length){
            console.log(this.fileList.map(v => v.originFileObj));
            this.fileList.map(v => v.originFileObj).forEach(async file => {
              await this.uploadImages(file, result.data.id);
            })
          }
          this.directOrderModalShow = false;
          // this.msg.success('直接解决成功');
          this.isBuildOrderAgaginFn();
        } else {
          this.msg.error(result.msg || '直接解决失败');
        }
      });
  }
  // 图片上传
  uploadImages(file, id){
    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', file.name);
    const req = new HttpRequest('Post', this.mainService.returnUploadUrl('wechatRequesterIncident', id), formData, {
      reportProgress: true
    });
    return this.http.request(req).pipe(filter(e => e instanceof HttpResponse)).toPromise();
  }
  // 运维-建单并派单
  assignOrder(){
    if(this.incidentModel.repairIncidentType === 'public' && !this.incidentModel.requester){
      this.msg.warning('请选择申请人!');
      return;
    }

    if(!this.incidentModel.category){
      this.msg.warning('请选择故障现象!');
      return;
    }

    let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
    if(!this.incidentModel.duty){
      this.msg.warning(`故障现象【${category.mutiCategory}】没有设置责任部门!`);
      return;
    }

    if(this.incidentModel.repairIncidentType === 'dept' && !this.incidentModel.department){
      this.msg.warning('请选择申请科室!');
      return;
    }

    if(!this.incidentModel.contactsInformation){
      this.msg.warning('请填写联系电话!');
      return;
    }

    if(!this.incidentModel.priorityId){
      this.msg.warning('请选择优先级!');
      return;
    }

    if(!this.incidentModel.description){
      this.msg.warning('请选择故障描述!');
      return;
    }

    if(!this.incidentModel.group && this.buildType !== '编辑事件'){
      this.msg.warning('请选择处理组!');
      return;
    }

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

    let postData:any = {
      solutionId: this.solutionId,
      "incident": {
        "id": this.incidentModel.id || undefined,
        "deleteFlag": 0,
        "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
        "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
        "contactsInformation": this.incidentModel.contactsInformation,
        "contacts": this.incidentModel.contacts,
        "hosId": this.incidentModel.hosId || undefined,
        "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
        "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
        "houseNumber": this.incidentModel.houseNumber,
        "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
        "priorityId": this.incidentModel.priorityId || undefined,
        "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
        // "title": category.mutiCategory,
        "description": this.incidentModel.description,
        "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
        "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
        "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
        "acceptUser": { id: this.tool.getCurrentUserId() },
        "callID": this.incidentModel.callID || undefined,
        "incomingPhone": this.incidentModel.incomingPhone || undefined,
        "candidateGroups": this.incidentModel.group || undefined,
        "assignee": this.incidentModel.user || undefined,
        "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
      }
    };
    if(this.buildType){
      if(this.buildType === '报修转事件'){
        postData.incident.fromWx = true;
      }
      if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
        postData.incident = Object.assign({}, postData.incident);
      }else{
        postData.incident = Object.assign({}, this.editOrder, postData.incident);
      }
    }
    console.log(postData);
    // return;

    this.mainService
      .flowPost("incident/task/accept", postData)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;

        if (result.state == 200) {
          // 图片上传
          if(this.fileList.length){
            console.log(this.fileList.map(v => v.originFileObj));
            this.fileList.map(v => v.originFileObj).forEach(async file => {
              await this.uploadImages(file, result.data.id);
            })
          }
          // this.msg.success('建单并派单成功');
          this.isBuildOrderAgaginFn();
        } else {
          this.msg.error(result.msg || '建单并派单失败');
        }
      });
  }

  // 运维-暂存
  temporaryStorage(){
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;

    let category;
    if(this.incidentModel.category){
      category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
    }

    let postData:any = {
      solutionId: this.solutionId,
      "incident": {
        "id": this.incidentModel.id || undefined,
        "deleteFlag": 0,
        "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
        "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
        "contactsInformation": this.incidentModel.contactsInformation,
        "contacts": this.incidentModel.contacts,
        "hosId": this.incidentModel.hosId || undefined,
        "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
        "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
        "houseNumber": this.incidentModel.houseNumber,
        "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
        "priorityId": this.incidentModel.priorityId || undefined,
        "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
        // "title": category ? category.mutiCategory : '',
        "description": this.incidentModel.description,
        "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
        "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
        "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
        "acceptUser": { id: this.tool.getCurrentUserId() },
        "callID": this.incidentModel.callID || undefined,
        "incomingPhone": this.incidentModel.incomingPhone || undefined,
        "candidateGroups": this.incidentModel.group || undefined,
        "assignee": this.incidentModel.user || undefined,
        "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
      }
    };
    if(this.buildType){
      if(this.buildType === '报修转事件'){
        postData.incident.fromWx = true;
      }
      if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
        postData.incident = Object.assign({}, postData.incident);
      }else{
        postData.incident = Object.assign({}, this.editOrder, postData.incident);
      }
    }
    console.log(postData);
    // return;

    this.mainService
      .flowPost("incident/task/storage", postData)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;

        if (result.state == 200) {
          // 图片上传
          if(this.fileList.length){
            console.log(this.fileList.map(v => v.originFileObj));
            this.fileList.map(v => v.originFileObj).forEach(async file => {
              await this.uploadImages(file, result.data.id);
            })
          }
          // this.msg.success('暂存成功');
          this.isBuildOrderAgaginFn();
        } else {
          this.msg.error(result.msg || '暂存失败');
        }
      });
  }

  // 运维-保存
  buildType;
  editOrder;
  saveOrder(){
    if(this.incidentModel.repairIncidentType === 'public' && !this.incidentModel.requester){
      this.msg.warning('请选择申请人!');
      return;
    }

    if(!this.incidentModel.category){
      this.msg.warning('请选择故障现象!');
      return;
    }

    let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
    if(!this.incidentModel.duty){
      this.msg.warning(`故障现象【${category.mutiCategory}】没有设置责任部门!`);
      return;
    }

    if(this.incidentModel.repairIncidentType === 'dept' && !this.incidentModel.department){
      this.msg.warning('请选择申请科室!');
      return;
    }

    if(!this.incidentModel.contactsInformation){
      this.msg.warning('请填写联系电话!');
      return;
    }

    if(!this.incidentModel.priorityId){
      this.msg.warning('请选择优先级!');
      return;
    }

    if(!this.incidentModel.description){
      this.msg.warning('请选择故障描述!');
      return;
    }

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

    let postData:any = {
      solutionId: this.solutionId,
      "incident": {
        "id": this.incidentModel.id || undefined,
        "deleteFlag": 0,
        "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
        "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
        "contactsInformation": this.incidentModel.contactsInformation,
        "contacts": this.incidentModel.contacts,
        "hosId": this.incidentModel.hosId || undefined,
        "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
        "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
        "houseNumber": this.incidentModel.houseNumber,
        "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
        "priorityId": this.incidentModel.priorityId || undefined,
        "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
        // "title": category ? category.mutiCategory : '',
        "description": this.incidentModel.description,
        "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
        "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
        "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
        "acceptUser": { id: this.tool.getCurrentUserId() },
        "callID": this.incidentModel.callID || undefined,
        "incomingPhone": this.incidentModel.incomingPhone || undefined,
        "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
      }
    };
    if(this.buildType){
      postData.incident = Object.assign({}, this.editOrder, postData.incident);
    }
    console.log(postData);
    // return;

    this.mainService
      .flowPost("incident/task/edit", postData)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;

        if (result.state == 200) {
          // 图片上传
          if(this.fileList.length){
            console.log(this.fileList.map(v => v.originFileObj));
            this.fileList.map(v => v.originFileObj).forEach(async file => {
              await this.uploadImages(file, result.data.id);
            })
          }
          // this.msg.success('编辑成功');
          this.isBuildOrderAgaginFn();
        } else {
          this.msg.error(result.msg || '编辑失败');
        }
      });
  }

  // 是否连续建单
  isBuildOrderAgaginFn(){
    if(this.isBuildOrderAgagin){
      // 清除故障现象，维修人/组
      this.incidentModel.category = undefined;
      this.incidentModel.user = undefined;
      this.incidentModel.group = undefined;
      this.showPromptModal("操作", true, "", "");
    }else{
      this.confirmModelHs.emit();
      this.showPromptModal("操作", true, "", "");
    }
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框
  back = ""; //标识符
  showPromptModal(con, success, promptInfo?, back?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    this.back = back || "";
    setTimeout(() => {
      this.confirmModelHs.emit();
      this.promptModalShow = true;
    }, 100);
  }

  // 服务台新建工单—知识库
  solutionStatus;//知识库状态
  solutionType;//知识库类型
  loading7 = false;
  knowageList:any[] = [];
  getKnowageList() {
    if(!(this.incidentModel.category && this.solutionStatus && this.solutionType)){
      this.loading7 = false;
      this.knowageList = [];
      return;
    }
    this.loading7 = true;
    let postData:any = {
      idx: 0,
      sum: 9999,
      solution: {
        categoryId: this.incidentModel.category,
				status: this.solutionStatus,
				type: this.solutionType,
      },
    };

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

  // 引入知识库
  solutionId;//引用的知识库Id
  importKnowage(item){
    console.log(item)
    this.incidentModel = {...this.incidentModel, description:  `引用知识库解决，知识库编号：${item.solutionNumber}`};
    this.solutionId = item.id;
  }
  // 知识库查看-知道了
  coopData:any = {};
  isShowKnowledge:boolean = false;
  showKnowledgeModal(data) {
    this.coopData = data || {};
    this.isShowKnowledge = true;
  }

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

  // 引入电话号码
  importPhone(phone, isTransform){
    if(isTransform){
      this.incidentModel.contactsInformation = phone.split(',')[0];
    }else{
      this.incidentModel.contactsInformation = phone;
    }
  }

  // 重置新建工单数据
  resetOrderData(){
    this.applicationRequesterList = [];
    this.fileList = [];
    this.repairImgs = [];
    this.isRelatedDepartment = true;
    this.solutionId = undefined;
  }

  // 重置新建工单数据-继续建单-编辑-报修转事件
  resetOrderData2(){
    this.fileList = [];
    this.repairImgs = [];
    if(this.incidentModel.repairIncidentType === 'public'){
      this.isRelatedDepartment = false;
    }else{
      this.isRelatedDepartment = true;
    }
  }

  // 打开新建工单
  async showNewOrder(des = '', phone = '', isInit = false, buildType = '') {
    this.buildType = buildType;
    if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
      this.resetOrderData();
    }else{
      this.resetOrderData2();
    }
    this.searchApplicationHospital();
    this.searchApplicationCategory();
    this.searchApplicationPriority();
    this.searchApplicationSource();
    this.getRepairIncidentType();
    isInit ? this.searchApplicationDepartment('itsm', undefined, undefined, undefined, true) : this.searchApplicationDepartment('itsm');
    isInit && ((this.isRelatedDepartment && this.incidentModel.department) || (!this.isRelatedDepartment && this.incidentModel.hosId) || this.buildType === '报修转事件' ) && this.incidentModel.hosId && this.searchApplicationBuilding();
    isInit && this.incidentModel.area && this.searchApplicationFloor();

    this.currentRTab = 0;
    this.rightTitle_tab = [];
    this.incidentModel = isInit ? this.incidentModel : { repairIncidentType: 'dept' };
    this.incidentMsg = isInit ? this.incidentMsg : {};
    this.isBuildOrderAgagin = false;
    this.incidentModel.department = isInit ? this.incidentModel.department : null;
    console.log(des);
    //正常初始化
    this.getAutoWorkTypes(false, isInit);
  }

  // 新建工单->获取新建类型
  workTypesArrange = []; //整理后的任务类型
  workTypesFlag = false; //任务类型是否显示操作项
  getAutoWorkTypes(isFirst, isInit) {
    this.workTypesArrange = [];
    // 运维
    this.workTypesArrange = [{key:'故障报修', value: []}];
    console.log('workTypesArrange', this.workTypesArrange);
    // 是否显示操作项
    this.workTypesFlag = this.workTypesArrange.length >= 5;
    // 默认选中第一项
    if (this.workTypesArrange.length > 0) {
      this.tabClick(this.workTypesArrange[0].key, isInit);
    }
  }

  // 点击tab切换
  tabClick(key, isInit = false) {
    this.currentTabIndex = key;

    if(this.currentTabIndex === '故障报修'){
      if(this.incidentModel.department){
        this.rightTitle_tab = [
          { id: 2, name: '近期维修' },
          { id: 3, name: '知识库' },
        ]
        this.rightTitleHandler(this.rightTitle_tab[0].id);
      }
    }
  }

  // 来电咨询右侧的tab页
  // 服务台新建工单
  rightTitle_tab:any[] = [
    // { id: 2, name: '近期维修' },
    // { id: 3, name: '知识库' },
  ]
  currentRTab:any; //当前选中的
  rightTitleHandler(i) {
    this.currentRTab = i;
    if (i === 2) {
      this.getItsmOrders(this.incidentModel.department);
    } else if (i === 3) {
      this.getDictionaryList();
    }
  }

  // 服务台新建工单—根据申请科室id来查询
  loading6 = false;
  itsmOrders:any[] = [];
  getItsmOrders(id) {
    if (id == -1 || id === null || id === undefined) {
      this.itsmOrders = [];
      return;
    }

    let postData = {
      incident: {
        "deleteFlag": 0,
        queryTask: 'all',
        department: {
          id,
        },
      },
      idx: 0,
      sum: 6,
    };
    this.loading6 = true;
    this.mainService
      .getFetchDataList("simple/data", "incident", postData)
      .subscribe((data) => {
        this.loading6 = false;
        if (data.status == 200) {
          this.itsmOrders = data.list;
        }
      });
  }
  //获取知识库状态/类型
  getDictionaryList() {
    let solutionStatus$ = this.mainService.getDictionary('list', 'solution_status', true);
    let solutionType$ = this.mainService.getDictionary('list', 'solution_type', true);
    forkJoin(solutionStatus$, solutionType$).subscribe((data:any[]) => {
      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)

      this.getKnowageList();
    })
  }

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

  // 详细地址获取焦点
  isShowAddressList:boolean = false;
  focusAddress(){
    this.isShowAddressList = true;
    this.getAddressList();
  }

  // 点击其他位置
  clickExtra(e){
    if(document.documentElement.contains(document.querySelector('.addressList')) && e.target !== document.querySelector('.addressFocus')){
      this.isShowAddressList = false;
    }
  }

  // 选择地址
  selectAddress(name){
    this.incidentModel.houseNumber = name;
    this.isShowAddressList = false;
  }

  // 获取科室地点列表
  addressList:any[] = [];
  addressLoading:boolean = false;
  getAddressList() {
    if(!this.incidentModel.department){
      this.addressList = [];
      return;
    }
    let postData = {
      idx: 0,
      sum: 99999,
      qrCode: {
        deptId: this.incidentModel.department,
      }
    };
    this.addressLoading = true;
    this.mainService.getFetchDataList("simple/data", "qrCode", postData).subscribe(result=>{
      this.addressLoading = false;
      if(result.status == 200){
        this.addressList = result.list || [];
      }else{
        this.addressList = [];
      }
    });
  }
}
