import { Component, EventEmitter, Input, Output, SimpleChanges, ViewChild } from '@angular/core';
import dayjs from 'dayjs';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicDataService } from '../../../../../../services/basic.service';
import { CommonNzModule } from './../../../../../../common.nz.module';
import { ApiService } from './../../../../../../services/api.service';
import { DataEmptyComponent } from './../../../../../../shared/data-empty/data-empty.component';
import { FilterButtonGroupComponent } from './../../../../../../shared/filter-button-group/filter-button-group.component';
import { getFrequencyText, RoundState } from './../../inspection-plan.utils';
import { RoundEditFormComponent } from './round-edit-form/round-edit-form.component';
import { RoundStaticTableComponent } from './round-static-table/round-static-table.component';
import { Round, TaskRoundsComponent } from './task-rounds/task-rounds.component';

// 数组中随机取一个位置
function getRandomIndex(arr: any[]) {
  return Math.floor(Math.random() * arr.length);
}

@Component({
  selector: 'plan-detail-info',
  standalone: true,
  imports: [
    CommonNzModule,
    FilterButtonGroupComponent,
    TaskRoundsComponent,
    RoundStaticTableComponent,
    RoundEditFormComponent,
    DataEmptyComponent,
  ],
  templateUrl: './detail-info.component.html',
  styleUrl: './detail-info.component.less',
})
export class DetailInfoComponent {
  @ViewChild(RoundEditFormComponent) roundEditForm!: RoundEditFormComponent;
  @ViewChild(TaskRoundsComponent) taskRounds!: TaskRoundsComponent;
  @Input() data: Hazard.InspectionPlanDetail = {} as Hazard.InspectionPlanDetail;
  @Input() planBelongToMe = false;
  @Output() onFetchDetail = new EventEmitter<number>();

  departmentOptions: Option<number>[] = [];
  currentDepartment = -1;
  list: Hazard.InspectionPlanHandleDto[] = [];
  editing = false;

  turns: number[] = [];
  currentTurn = -1;

  rounds: Round[] = [];
  selectedRoundId = -1;
  currentRound?: Round;

  // 是否可以填报
  planFillable = false;

  constructor(
    private basic: BasicDataService,
    private api: ApiService,
    private modal: NzModalService,
    private message: NzMessageService
  ) {}

  ngOnInit() {}
  ngOnChanges(changes: SimpleChanges) {
    if (changes['data']) {
      this.departmentOptions = this.basic.departments
        .filter(d => this.data.departments.includes(d.id))
        .map(d => ({ label: d.name, value: d.id }));
      if (
        this.currentDepartment === -1 ||
        !this.departmentOptions.find(item => item.value === this.currentDepartment)
      ) {
        this.currentDepartment = this.departmentOptions[0]?.value || -1;
      }
      this.setTurn();
      this.setRounds();
      this.setFillable();
    }
  }
  setFillable() {
    // const { user, isAdmin } = this.setting;
    if (['已发布', '执行中', '已结束'].includes(this.data.status)) {
      this.planFillable = true;
    } else {
      this.planFillable = false;
    }
  }
  fetchDetail() {
    this.onFetchDetail.emit(this.data.id);
  }
  setTurn() {
    this.turns = Array.from({ length: this.data.frequencyTimes }, (_, i) => i);
    if (this.currentTurn === -1 || !this.turns.includes(this.currentTurn)) {
      this.currentTurn = this.turns[0];
    }
  }
  setRounds() {
    const rounds = this.data?.plans || [];
    if (!rounds.length) {
      this.rounds = [];
      return;
    }
    this.rounds = rounds
      .filter(r => r.departments.includes(this.currentDepartment))
      .map(item => {
        return {
          meta: item,
          state: this.getStatus(item),
          time: `${dayjs(item.startDate).format('MM/DD')} - ${dayjs(item.endDate).format('MM/DD')}`,
        };
      });
    if (this.selectedRoundId === -1 || !this.rounds.find(item => item.meta.id === this.selectedRoundId)) {
      // 如果未选择轮次，则选择当前轮次
      const firstId = this.rounds[0]?.meta.id;
      const recentId = this.rounds.find(item => item.state === 'current')?.meta.id;
      this.selectedRoundId = recentId || firstId;
    }
    const currentRound = this.rounds.find(item => item.meta.id === this.selectedRoundId);
    if (currentRound) {
      this.onRoundChange(currentRound);
    }
  }
  getStatus(d: Hazard.InspectionPlanRound): RoundState {
    const now = new Date();
    if (new Date(d.startDate) > now) {
      return RoundState.UnStart;
    }
    if (new Date(d.endDate) < now) {
      return RoundState.Expired;
    }
    return RoundState.Current;
  }
  onSelectDepartment(value: number) {
    this.currentDepartment = value;
    this.setRounds();
    // this.taskRounds.setRounds();
  }
  onTurnChange(value: number) {
    this.currentTurn = value;
    const allTasks = this.currentRound?.meta.handles || [];
    this.list = allTasks.filter(item => {
      return item.times === this.currentTurn;
    });
  }
  onRoundChange(round: Round) {
    this.currentRound = round;
    this.selectedRoundId = round.meta.id;
    const allTasks = round.meta.handles || [];
    this.list = allTasks.filter(item => {
      return item.times === this.currentTurn;
    });
  }
  onToggleEditor() {
    this.editing = !this.editing;
  }
  onAddTask() {
    this.roundEditForm.addNewItem();
  }
  onCopyToTurn(toTurnIndex: number) {
    const params: Hazard.CopyTasksToTurnParams = {
      planId: this.data.id,
      roundId: this.currentRound!.meta.id,
      fromTurnIndex: this.currentTurn,
      toTurnIndex,
    };
    let modalRef = this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '复制',
      nzContent: '确定要复制到第' + (toTurnIndex + 1) + '次吗？',
      nzOkText: '复制',
      nzCancelText: '取消',
      nzOnOk: async () => {
        modalRef.updateConfig({ nzOkLoading: true });
        await this.api.hazard.copyTasksToTurn(params).finally(() => {
          modalRef.updateConfig({ nzOkLoading: false });
        });
        this.message.success('复制成功');
        this.onFetchDetail.emit(this.data.id);
      },
    });
  }
  onCopyToRound(round: Round) {
    const params: Hazard.CopyTasksToRoundParams = {
      planId: this.data.id,
      fromRoundId: this.currentRound!.meta.id,
      toRoundId: round.meta.id,
    };
    let modalRef = this.modal.confirm({
      nzClassName: 'precaution-modal',
      nzTitle: '复制',
      nzContent: '确定要复制到 ' + round.time + ' 轮吗？',
      nzOkText: '复制',
      nzCancelText: '取消',
      nzOnOk: async () => {
        modalRef.updateConfig({ nzOkLoading: true });
        await this.api.hazard.copyTasksToRound(params).finally(() => {
          modalRef.updateConfig({ nzOkLoading: false });
        });
        this.message.success('复制成功');
        this.onFetchDetail.emit(this.data.id);
      },
    });
  }
  getFrequencyLabel(d: Hazard.InspectionPlan) {
    return getFrequencyText(d);
  }
  get positions() {
    return this.basic.positions;
  }
  get lines() {
    return this.basic.lines;
  }

  get otherRounds() {
    if (!this.currentRound) {
      return [];
    }
    return this.rounds.filter(item => this.currentRound?.meta && item.meta.id !== this.currentRound.meta.id);
  }
  get roundCopyVisible() {
    return this.rounds.length > 1;
  }
  get turnCopyVisible() {
    return this.turns.length > 1;
  }
}
