import { Component } from '@angular/core';
import { horizontalInOutReverse300ms } from '../../../../common.animation';
import { CommonNzModule } from '../../../../common.nz.module';
import { DataEmptyComponent } from '../../../../shared/data-empty/data-empty.component';
import { hazardLevelColor } from '../hazard.utils';
import { ApiService } from './../../../../services/api.service';
import { SettingService } from './../../../../services/setting.service';
import { CustomDrawerComponent } from './../../../../shared/custom-drawer/custom-drawer.component';
import { InspectionPlanDetailComponent } from './detail/detail.component';
import { hazardPlanTypeOptions, PlanType } from './inspection-plan.utils';
import { PlanCardComponent } from './plan-card/plan-card.component';
import { PlanFormComponent, PlanFormComponentProps } from './plan-form/plan-form.component';

export interface InspectionPlanDetailConfig {
  visible: boolean;
  data: Hazard.InspectionPlanDetail;
}

type SemiAnnual = { label: string; start: Date; end: Date; key: number };

const notificationConfig = [
  { type: 1, text: '通知', color: '#165DFF', backgroundColor: '#E8F3FF' },
  { type: 2, text: '消息', color: '#0FC6C2', backgroundColor: '#E8FFFB' },
];

@Component({
  selector: 'app-inspection-plan',
  standalone: true,
  imports: [
    CommonNzModule,
    PlanCardComponent,
    InspectionPlanDetailComponent,
    CustomDrawerComponent,
    PlanFormComponent,
    DataEmptyComponent,
  ],
  templateUrl: './inspection-plan.component.html',
  styleUrl: './inspection-plan.component.less',
  animations: [horizontalInOutReverse300ms],
})
export class InspectionPlanComponent {
  detailConfig: InspectionPlanDetailConfig = {
    visible: false,
    data: {} as Hazard.InspectionPlanDetail,
  };
  formConfig: PlanFormComponentProps = {
    visible: false,
    data: undefined,
    isEdit: false,
  };

  hazardLevelColor = hazardLevelColor;

  semiAnnualOptions: SemiAnnual[] = [];

  // firstSection = [
  //   { label: '日常隐患排查计划', value: 3, key: 1 },
  //   { label: '专项隐患排查计划', value: 6, key: 2 },
  //   { label: '其他隐患排查计划', value: 9, key: 3 },
  // ];
  types = hazardPlanTypeOptions.map(t => ({ label: t.label, key: t.value as PlanType, count: 0 }));
  // secondSection = [
  //   { label: '计划站点排查覆盖', value: 65 },
  //   { label: '其他场所排查覆盖', value: 100 },
  //   { label: '计划人员排查占比', value: 95 },
  // ];
  discoveryList = [
    {
      level: '重大',
      count: 0,
      color: hazardLevelColor['重大'],
    },
    {
      level: 'A级',
      count: 0,
      color: hazardLevelColor['A'],
    },
    {
      level: 'B级',
      count: 0,
      color: hazardLevelColor['B'],
    },
    {
      level: 'C级',
      count: 0,
      color: hazardLevelColor['C'],
    },
  ];
  notifications = [
    {
      type: 1,
      title:
        '当前产品试用期即将截止，在这段宝贵的试用时光里，您想必已经充分领略到了它的独特魅力与卓越性能。它犹如一位得力助手，在您的工作与生活中默默耕耘，助力您轻松跨越一道道难关，高效完成各项任务。无论是处理复杂的文档、分析海量的数据，还是畅享流畅的娱乐体验，它都表现得游刃有余',
      createDate: '2024-06-16T00:00:00',
    },
    {
      type: 1,
      title:
        '1月新系统升级计划通知,为了给您提供更优质、高效、稳定的服务体验，提升系统性能与功能，我们计划于 1 月进行系统升级。现将相关事宜详细通知如下：',
      createDate: '2024-10-16T00:00:00',
    },
    {
      type: 2,
      title:
        '新增内容已经通过审核，详情如下：此次审核涵盖了文本、图像、音频等多方面元素，确保了新增内容在质量与合规性上均达到了既定标准。文本部分，语言表达流畅自然，逻辑严谨清晰，无论是专业术语的运用还是普通语句的叙述，都经过了仔细的斟酌与校对，避免了歧义与错误信息的出现。',
      createDate: '2024-11-04T00:00:00',
    },
    {
      type: 1,
      title:
        '1月新系统升级计划通知为了给您提供更优质、高效、稳定的服务体验，提升系统性能与功能，我们计划于 1 月进行系统升级。现将相关事宜详细通知如下：',
      createDate: '2024-11-16T00:00:00',
    },
  ];
  currentType?: PlanType;
  semiAnnual?: SemiAnnual;

  plans: Hazard.InspectionPlan[] = [];
  fetching = false;
  fetchingDetail = false;
  pageConfig: IPageConfig = {
    total: 0,
    page: 0,
    size: 12,
  };
  constructor(
    private api: ApiService,
    private setting: SettingService
  ) {
    setting.getUsersOfCurrentCompany();
    this.setSemiAnnualOptions();
  }

  ngOnInit() {
    this.fetchPlans();
  }
  setSemiAnnualOptions() {
    const upperHalf = '上半年度';
    const lowerHalf = '下半年度';
    const upperHalfRange = ['-01-01T00:00:00', '-06-30T23:59:59'];
    const lowerHalfRange = ['-07-01T00:00:00', '-12-31T23:59:59'];

    // 从 2024/12/27 开始，每半年一个周期
    const start = new Date('2024-12-27T00:00:00');
    const now = new Date();
    let semiAnnualOptions = [
      {
        label: '2024下半年度',
        start: new Date(2024 + lowerHalfRange[0]),
        end: new Date(2024 + lowerHalfRange[1]),
        key: 202407,
      },
    ];
    const fullYears = now.getFullYear() - start.getFullYear() - 1;

    function pushSemiAnnualOptions(year: number, half: string) {
      const range = half === upperHalf ? upperHalfRange : lowerHalfRange;
      semiAnnualOptions.push({
        label: `${year}${half}`,
        start: new Date(year + range[0]),
        end: new Date(year + range[1]),
        key: year,
      });
    }
    for (let i = 0; i < fullYears; i++) {
      pushSemiAnnualOptions(start.getFullYear() + i + 1, upperHalf);
      pushSemiAnnualOptions(start.getFullYear() + i + 1, lowerHalf);
    }

    const isWhole = now.getMonth() > 6;

    pushSemiAnnualOptions(now.getFullYear(), upperHalf);
    if (isWhole) {
      pushSemiAnnualOptions(now.getFullYear(), lowerHalf);
    }
    this.semiAnnualOptions = semiAnnualOptions;
    this.semiAnnual = this.semiAnnualOptions[this.semiAnnualOptions.length - 1];
  }
  getParams() {
    const params: Hazard.GetPlansParams = {
      startDate: this.semiAnnual?.start.toISOString(),
      endDate: this.semiAnnual?.end.toISOString(),
      page: this.pageConfig.page,
      size: this.pageConfig.size,
    };
    if (this.currentType) {
      params.type = this.currentType;
    }
    return params;
  }

  fetchPlans() {
    this.fetching = true;
    this.api.hazard
      .getPlans(this.getParams())
      .then(res => {
        this.plans = res.items;
        this.pageConfig.total = res.total;
        this.setTypesCount(res);
        this.setDiscoveryCount(res);
      })
      .finally(() => {
        this.fetching = false;
      });
  }
  setTypesCount(res: Hazard.PlanListResponse) {
    this.types.find(t => t.key === PlanType.COMPREHENSIVE)!.count = res.troubleshootTypeNumber.typeSpecial;
    this.types.find(t => t.key === PlanType.DAILY)!.count = res.troubleshootTypeNumber.typeCommon;
    this.types.find(t => t.key === PlanType.OTHER)!.count = res.troubleshootTypeNumber.typeOther;
  }
  setDiscoveryCount(res: Hazard.PlanListResponse) {
    this.discoveryList.find(d => d.level === '重大')!.count = res.troubleLevelNumber.levelImportantTotal;
    this.discoveryList.find(d => d.level === 'A级')!.count = res.troubleLevelNumber.levelATotal;
    this.discoveryList.find(d => d.level === 'B级')!.count = res.troubleLevelNumber.levelBTotal;
    this.discoveryList.find(d => d.level === 'C级')!.count = res.troubleLevelNumber.levelCTotal;
  }
  onCurrentPageChange(page: number) {
    this.pageConfig.page = page;
    this.fetchPlans();
  }
  handleRefreshList() {
    this.pageConfig.page = 0;
    this.fetchPlans();
  }

  handlePlanTypeChange(type: PlanType) {
    if (this.currentType === type) {
      this.currentType = undefined;
    } else {
      this.currentType = type;
    }
    this.handleRefreshList();
  }
  handleSemiAnnualChange(direction: 'left' | 'right') {
    const index = this.currentSemiAnnualOptionIndex;
    if (direction === 'left') {
      if (!this.leftArrowVisible) return;
    }
    if (direction === 'right') {
      if (!this.rightArrowVisible) return;
    }
    this.semiAnnual = this.semiAnnualOptions[index + (direction === 'left' ? -1 : 1)];
    this.handleRefreshList();
  }

  getNotificationTypeText(t: number) {
    return notificationConfig.find(n => n.type === t)?.text || '未知';
  }
  getNotificationTypeColor(t: number) {
    return notificationConfig.find(n => n.type === t)?.color || '';
  }
  getNotificationTypeBgColor(t: number) {
    return notificationConfig.find(n => n.type === t)?.backgroundColor || '';
  }
  handleCloseDetail() {
    this.detailConfig.visible = false;
    this.fetchPlans();
  }
  handleViewDetail(data: Hazard.InspectionPlan) {
    this.handleFetchDetail(data.id);
    this.detailConfig = {
      ...this.detailConfig,
      visible: true,
      data: {
        ...data,
        plans: [],
      },
    };
  }

  handleAddPlan() {
    this.formConfig.visible = true;
    this.formConfig.isEdit = false;
  }
  handleEditPlan(data: Hazard.InspectionPlan) {
    this.formConfig.visible = true;
    this.formConfig.data = data;
    this.formConfig.isEdit = true;
  }
  closeFormDrawer() {
    this.formConfig.visible = false;
  }
  async handleFetchDetail(id: number) {
    this.fetchingDetail = true;
    await this.api.hazard
      .getPlanDetail(id)
      .then(res => {
        this.detailConfig = {
          ...this.detailConfig,
          visible: true,
          data: res,
        };
      })
      .finally(() => {
        this.fetchingDetail = false;
      });
  }
  get currentSemiAnnualOptionIndex() {
    return this.semiAnnualOptions.findIndex(se => se.key === this.semiAnnual?.key);
  }
  get semiAnnualText() {
    return this.semiAnnualOptions.find(se => se.key === this.semiAnnual?.key)?.label || '';
  }
  get leftArrowVisible() {
    const index = this.currentSemiAnnualOptionIndex;
    if (index === -1) return false;
    return !!this.semiAnnualOptions[index - 1];
  }
  get rightArrowVisible() {
    const index = this.currentSemiAnnualOptionIndex;
    if (index === -1) return false;
    return !!this.semiAnnualOptions[index + 1];
  }
}
