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 { IncidentSubstitutionRedeployComponent } from '../incident-substitutio-redeploy/incident-substitution-redeploy.component';
import { IncidentSubstitutionAssignComponent } from '../incident-substitutio-assign/incident-substitution-assign.component';
import { IncidentSubstitutionUpgradeComponent } from '../incident-substitutio-upgrade/incident-substitution-upgrade.component';
import { IncidentSubstitutionReassignComponent } from '../incident-substitutio-reassign/incident-substitution-reassign.component';

@Component({
  selector: 'app-incident-substitution',
  templateUrl: './incident-substitution.component.html',
  styleUrls: ['./incident-substitution.component.less']
})
export class IncidentSubstitutionComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild(IncidentSubstitutionRedeployComponent, { static: false }) redeploy!: IncidentSubstitutionRedeployComponent;
  @ViewChild(IncidentSubstitutionAssignComponent, { static: false }) assign!: IncidentSubstitutionAssignComponent;
  @ViewChild(IncidentSubstitutionUpgradeComponent, { static: false }) upgrade!: IncidentSubstitutionUpgradeComponent;
  @ViewChild(IncidentSubstitutionReassignComponent, { static: false }) reassign!: IncidentSubstitutionReassignComponent;
  @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,
  ) { }

  isLoading = false;

  // 初始化增删改按钮
  coopBtns: any = {};

  tabs:any[] = [
    // {id: 1, name: '转派', value: 'redeploy', num: ''},
    // {id: 2, name: '指派', value: 'assign', num: ''},
    // {id: 3, name: '升级', value: 'upgrade', num: ''},
    // {id: 4, name: '退回', value: 'reassign', num: ''},
  ]

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    console.log(this.coopBtns)
    this.operationAuthority();
  }

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

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

  // 操作权限
  incidentData:any = {};
  maskFlag:any = false;
  operationAuthority(){
    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);

        // 转派
        if(this.incidentData.state.value == 'handler' && this.incidentData.handlingPersonnelUser && this.incidentData.handlingPersonnelUser.id == this.tool.getCurrentUserId() && !this.coopBtns.assign && this.coopBtns.transfer){
          this.tabs.splice(0, 0, {id: 1, name: '转派', value: 'redeploy', num: ''});
        }else if(this.incidentData.state.value == 'pending'){
          let inUser = this.incidentData.currentLog && this.incidentData.currentLog.workerId == this.tool.getCurrentUserId();
          let inGroup = false;
          let groupList = this.tool.getCurrentGroupList();
          groupList.forEach(item => {
              if(this.incidentData.currentLog){
                  if (item.id == this.incidentData.currentLog.groupId) {
                      inGroup = true;
                  }
              }
          })
          if((inUser || inGroup)){
            this.tabs.splice(0, 0, {id: 1, name: '转派', value: 'redeploy', num: ''});
          }
        }

        // 指派
        if((this.incidentData.state.value == 'pending' || this.incidentData.state.value == 'handler' || this.incidentData.state.value == 'reassign') && this.coopBtns.assign){
          let index = this.tabs.findIndex(v => v.value === 'reassign');
          if(index < 0){
            this.tabs = [{id: 2, name: '指派', value: 'assign', num: ''}];
          }else{
            this.tabs.splice(index, 0, {id: 2, name: '指派', value: 'assign', num: ''});
          }
        }

        // 退回
        if(this.incidentData.state.value == 'pending' || this.incidentData.state.value == 'handler'){
          if(this.tabs.length){
            this.tabs.splice(this.tabs.length, 0, {id: 4, name: '退回', value: 'reassign', num: ''});
          }else{
            this.tabs = [{id: 4, name: '退回', value: 'reassign', num: ''}];
          }
        }

        this.clickTbab(this.tabs[0]);
      });
  }

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

  // 表单提交
  submitForm(): void {
    if(this.activeTabValue === 'redeploy'){
      // 转派
      for (const i in this.redeploy.validateForm.controls) {
        this.redeploy.validateForm.controls[i].markAsDirty();
        this.redeploy.validateForm.controls[i].updateValueAndValidity();
      }
      if (this.redeploy.validateForm.invalid) {
        return;
      }

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

      let postData = {
        incident: this.incidentData,
      }

      postData.incident.redeployRemark = this.redeploy.validateForm.value.redeployRemark;

      if(this.redeploy.validateForm.value.userId){
        // 派人
        postData.incident.assignee = this.redeploy.validateForm.value.userId;
      } else {
        // 派组
        postData.incident.candidateGroups = this.redeploy.validateForm.value.groupId;
        delete postData.incident.assignee;
      }

      postData.incident.candidateGroupId = this.redeploy.validateForm.value.groupId;

      this.mainService
      .flowPost("incident/task/redeploy", 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.activeTabValue === 'assign'){
      // 指派
      for (const i in this.assign.validateForm.controls) {
        this.assign.validateForm.controls[i].markAsDirty();
        this.assign.validateForm.controls[i].updateValueAndValidity();
      }
      if (this.assign.validateForm.invalid) {
        return;
      }

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

      let postData = {
        incident: this.incidentData,
      }

      if(this.assign.validateForm.value.userId){
        // 派人
        postData.incident.assignee = this.assign.validateForm.value.userId;
      } else {
        // 派组
        postData.incident.candidateGroups = this.assign.validateForm.value.groupId;
        delete postData.incident.assignee;
      }

      postData.incident.candidateGroupId = this.assign.validateForm.value.groupId;
      postData.incident.duty = { id: this.assign.validateForm.value.dutyId };

      this.mainService
      .flowPost("incident/task/assign", 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.activeTabValue === 'reassign'){
      // 退回
      for (const i in this.reassign.validateForm.controls) {
        this.reassign.validateForm.controls[i].markAsDirty();
        this.reassign.validateForm.controls[i].updateValueAndValidity();
      }
      if (this.reassign.validateForm.invalid) {
        return;
      }

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

      let postData = {
        incident: this.incidentData,
      }

      postData.incident.reassignRemark = this.reassign.validateForm.value.reassignRemark;

      this.mainService
      .flowPost("incident/task/reassign", 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 || '退回失败');
        }
      });
    }
  }
}




