import { Component, EventEmitter, Input, Output, SimpleChanges, TemplateRef, ViewChild } from '@angular/core';
import dayjs from 'dayjs';
import { StationD3Model } from '../../../../../classes/d3/station.class';
import { horizontalInOut } from '../../../../../common.animation';
import { CommonNzModule } from './../../../../../common.nz.module';
import { ApiService } from './../../../../../services/api.service';
import { BasicDataService } from './../../../../../services/basic.service';
import { KnowledgeService } from './../../../../../services/knowledge.service';
import { getPositionLikeDtoText } from './../../../../../shared/compose-position-pick-modal/compose-position-pick-modal.component';
import { HazardProgressComponent } from './hazard-progress/hazard-progress.component';

interface Field {
  label: string;
  value: string;
  separator?: boolean;
  template?: TemplateRef<any>;
}

@Component({
  selector: 'datav-info-panel',
  standalone: true,
  imports: [CommonNzModule, HazardProgressComponent],
  templateUrl: './info-panel.component.html',
  styleUrl: './info-panel.component.less',
  animations: [horizontalInOut],
})
export class InfoPanelComponent {
  @ViewChild('riskMeasureTemplate') riskMeasureTemplate!: TemplateRef<any>;
  @ViewChild('resolveTemplate') resolveTemplate!: TemplateRef<any>;
  @ViewChild('planTemplate') planTemplate!: TemplateRef<any>;
  @ViewChild('hazardProgressTemplate') hazardProgressTemplate!: TemplateRef<any>;
  @ViewChild('planDetailTemplate') planDetailTemplate!: TemplateRef<any>;
  @Input() activeType!: string;
  @Input() visible = false;
  @Output() close = new EventEmitter<void>();

  @Input() currentStation?: StationD3Model;
  @Input() currentRiskItems: Knowledge.RiskItem[] = [];
  @Input() currentHazardItems: Hazard.HazardDto[] = [];

  fields: Field[] = [];

  currRiskItem?: Knowledge.RiskItem;
  currHazardItem?: Hazard.HazardDto;
  index = 0;

  detail: {
    visible: boolean;
    key: string;
    title: string;
    width: number;
    fields: Field[];
    template?: TemplateRef<any>;
  } = {
    visible: false,
    key: '',
    title: '',
    width: 240,
    fields: [],
  };
  constructor(
    private knowledge: KnowledgeService,
    private basic: BasicDataService,
    private api: ApiService
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['activeType']) {
      this.reset();
    }
    if (changes['visible']) {
      if (this.visible) {
        setTimeout(() => {
          this.reset();
        }, 100);
      }
    }
    if (changes['currentRiskItems'] || changes['currentHazardItems']) {
      this.reset();
    }
  }
  reset() {
    this.index = 0;
    this.detail.visible = false;
    this.detail.template = undefined;
    this.load();
  }
  ngAfterViewInit(): void {
    setTimeout(() => {
      this.load();
    }, 2000);
  }
  load() {
    if (this.isRiskActive) {
      this.currHazardItem = undefined;
      this.setRiskFields();
    } else {
      this.currRiskItem = undefined;
      this.setHazardFields();
    }
    if (this.detail.visible) {
      this.updateDetail();
    }
  }
  setRiskFields() {
    this.currRiskItem = this.currentRiskItems[this.index];
    this.interpolateFieldsWithRiskItem();
  }
  setHazardFields() {
    this.currHazardItem = this.currentHazardItems[this.index];
    this.interpolateFieldsWithHazardItem();
  }

  setRiskItemId(riskItemId: number) {
    this.index = this.currentRiskItems.findIndex(item => item.id === riskItemId);
    this.load();
  }

  next() {
    if (this.nextDisabled) {
      return;
    }
    this.index++;
    this.load();
  }

  prev() {
    if (this.prevDisabled) {
      return;
    }
    this.index--;
    this.load();
  }

  get nextDisabled() {
    return this.index >= (this.isRiskActive ? this.currentRiskItems.length : this.currentHazardItems.length) - 1;
  }

  get prevDisabled() {
    return this.index <= 0;
  }

  onClose() {
    this.closeDetail();
    this.close.emit();
  }

  interpolateFieldsWithRiskItem() {
    if (!this.currRiskItem) {
      this.fields = [];
      return;
    }
    this.fields = [
      { label: '风险类别', value: this.knowledge.getTypeName(this.currRiskItem.type) || '' },
      {
        label: '风险项',
        value: this.knowledge.getCategoryName(this.currRiskItem.category, this.currRiskItem.type) || '',
      },
      {
        label: '风险等级',
        value: this.currRiskItem.level,
      },
      { label: '风险条目', value: this.currRiskItem.title },
      {
        label: '可能带来的影响',
        value: this.currRiskItem.consequences.map(c => this.basic.getConsequenceName(c)).join('\n'),
      },
      {
        label: '管控措施',
        value: '',
        template: this.riskMeasureTemplate,
      },
      {
        label: '责任人',
        value: this.currRiskItem.responsiblePerson,
      },
      // {
      //   label: '备注信息',
      //   value: this.currRiskItem.
      // },
    ];
  }
  interpolateFieldsWithHazardItem() {
    if (!this.currHazardItem) {
      this.fields = [];
      return;
    }
    const resolveValue = this.getHazardResolveValue(this.currHazardItem);
    const planText = this.getHazardPlanText(this.currHazardItem);
    this.fields = [
      // 隐患名：
      { label: '隐患名称', value: this.currHazardItem.title },
      // 隐患描述：
      { label: '隐患描述', value: this.currHazardItem.content },
      // 隐患级别：
      { label: '隐患级别', value: this.currHazardItem.level },
      // 隐患状态：
      { label: '隐患状态', value: this.currHazardItem.finalStatus },
      // 负责人：如当前状态有处理人，则显示，如没有则无需显示
      { label: '负责人', value: this.currHazardItem.toUserName },
      // 负责部门：
      { label: '负责部门', value: this.basic.getDepartmentName(this.currHazardItem.toDepartment) },
      // 具体地点：
      {
        label: '具体地点',
        value: getPositionLikeDtoText(
          this.currHazardItem,
          this.basic.lines,
          this.basic.positions,
          this.basic.positionCategories
        ),
      },
      // 整治方案：如未进入方案制定，显示“未开始”，已开始显示“方案制定中”，方案提交显示“方案待审批”，方案驳回显示“驳回重新制定中”，方案通过显示“方案通过，模板”
      { label: '整治方案', value: planText, template: planText ? this.planTemplate : undefined },
      // 整治记录：如未进入整治，显示“未开始”，存在整治记录给与“查看记录”按钮
      { label: '整治记录', value: resolveValue, template: !resolveValue ? this.resolveTemplate : undefined },
      // 整治负责人：
      { label: '整治负责人', value: this.currHazardItem.plan.userName },
      // 提交时间：
      { label: '提交时间', value: dayjs(this.currHazardItem.createdDate).format('YYYY/MM/DD HH:mm'), separator: true },
      // 分割线分开，下方显示隐患的归属风险
      // 归属风险类别：
      { label: '归属风险类别', value: this.knowledge.getTypeName(this.currHazardItem.riskType) || '' },
      // 归属风险条目：
      {
        label: '归属风险条目',
        value: this.knowledge.getCategoryName(this.currHazardItem.riskCategory, this.currHazardItem.riskType) || '',
      },
    ];
  }
  getHazardPlanText(hazard: Hazard.HazardDto): string {
    const { finalStatus } = hazard;
    // “未开始”，已开始显示“方案制定中”，方案提交显示“方案待审批”，方案驳回显示“驳回重新制定中”，方案通过显示“方案通过”
    switch (finalStatus) {
      case '未审核':
      case '已拒绝':
        return '未开始';
      case '已审核':
        return '方案制定中';
      case '方案待审核':
        return '方案待审批';
      case '方案驳回':
        return '驳回重新制定中';

      case '方案通过':
      case '治理中':
      case '治理结束':
      case '验收不合格':
      case '验收合格':
      default:
        return '方案通过';
    }
  }
  getHazardResolveValue(hazard: Hazard.HazardDto) {
    const { resolves } = hazard;
    if (!resolves.length) {
      return '未开始';
    }
    return '';
  }
  showMeasureDetail(type: 'requirement' | 'otherMeasure') {
    this.detail.visible = true;
    this.detail.key = type;
    this.detail.title = '管控措施';
    this.detail.width = 240;
    this.updateDetail();
  }

  showResolveDetail() {
    this.detail.visible = true;
    this.detail.key = 'resolve';
    this.detail.title = '整治记录';
    this.detail.width = 360;
    this.updateDetail();
  }

  showPlanDetail() {
    this.detail.visible = true;
    this.detail.key = 'plan';
    this.detail.title = '整治方案';
    this.detail.width = 240;
    this.updateDetail();
  }

  updateDetail() {
    if (this.detail.key === 'resolve') {
      this.detail.template = this.hazardProgressTemplate;
      return;
    }
    this.detail.template = undefined;
    if (this.detail.key === 'requirement') {
      this.updateRequirementDetail();
    } else if (this.detail.key === 'plan') {
      this.updatePlanDetail();
    } else {
      this.updateOtherMeasureDetail();
    }
  }
  closeDetail() {
    this.detail.visible = false;
  }
  updateRequirementDetail() {
    this.detail.fields = [{ label: '主要作业要求', value: this.currRiskItem!.requirement }];
  }
  updateOtherMeasureDetail() {
    this.detail.fields = [{ label: '其他措施', value: this.currRiskItem!.otherMeasure }];
  }
  updatePlanDetail() {
    this.detail.fields = [
      { label: '措施', value: this.currHazardItem!.plan.measure },
      { label: '治理目标', value: this.currHazardItem!.plan.target },
      { label: '治理人', value: this.currHazardItem!.plan.userName },
      { label: '截止日期', value: dayjs(this.currHazardItem!.plan.endDate).format('YYYY/MM/DD') },
    ];
  }
  get isRiskActive() {
    return this.activeType === 'risk';
  }

  get isHazardActive() {
    return this.activeType === 'hazard';
  }
}
