import { Component, EventEmitter, Input, Output, SimpleChanges, TemplateRef, ViewChild } from '@angular/core';
import dayjs from 'dayjs';
import { NzCheckBoxOptionInterface } from 'ng-zorro-antd/checkbox';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { NzPopoverDirective } from 'ng-zorro-antd/popover';
import { KnowledgeService } from '../../../../../../services/knowledge.service';
import { RiskItemPickerModalComponent } from '../../../../../../shared/risk-item-picker/modal/modal.component';
import { getFrequencyText, getHazardPlanTypeText, PlanLevel } from '../../inspection-plan.utils';
import { CommonNzModule } from './../../../../../../common.nz.module';
import { ApiService } from './../../../../../../services/api.service';
import { BasicDataService } from './../../../../../../services/basic.service';
import { SettingService } from './../../../../../../services/setting.service';
import { PlanDetailProgressComponent } from './progress/progress.component';

@Component({
  selector: 'plan-basic-info',
  standalone: true,
  imports: [CommonNzModule, PlanDetailProgressComponent],
  templateUrl: './basic-info.component.html',
  styleUrl: './basic-info.component.less',
})
export class BasicInfoComponent {
  @ViewChild('departmentsTpl') departmentsTpl!: TemplateRef<any>;
  @ViewChild(NzPopoverDirective)
  pointPopover!: NzPopoverDirective;
  @Input({ required: true }) data!: Hazard.InspectionPlanDetail;
  @Output() onFetchDetail = new EventEmitter<number>();
  pointsEditModal?: NzModalRef<RiskItemPickerModalComponent>;
  seasonVisible = false;
  points: number[] = [];
  cachePoints: number[] = [];
  pointsDetailVisible = false;
  springSpecifics = [
    {
      title: '气温变化大',
      content: '春季气温逐渐回升，但早晚温差较大，可能出现寒潮、倒春寒等天气现象。',
    },
    {
      title: '降水增多',
      content: '春季是雨季的开始，降水量逐渐增加，可能出现雷雨、暴雨等极端天气。',
    },
    {
      title: '风力增强',
      content: '春季风力较大，尤其是北方地区，可能出现沙尘暴等恶劣天气。',
    },
    {
      title: '植物生长',
      content: '春季植物开始生长，绿化带、树木等可能对地铁设施造成影响。',
    },
    {
      title: '动物活动',
      content: '春季是动物繁殖和活动的季节，可能会有动物进入地铁区域，影响运营安全。',
    },
    {
      title: '对地铁隐患排查的影响',
      content:
        '春季的特点对地铁隐患排查，需要地铁运营单位在设备检查、排水系统、防风措施、绿化管理、动物防护和应急预案等方面加强管理和维护，确保地铁运营的安全和稳定。',
    },
  ];
  temporaryDepartmentOptions: NzCheckBoxOptionInterface[] = [];
  constructor(
    private basic: BasicDataService,
    private api: ApiService,
    private setting: SettingService,
    private modal: NzModalService,
    private message: NzMessageService,
    private knowledge: KnowledgeService
  ) {}

  ngOnInit() {
    this.setProperties();
  }
  setProperties() {
    this.points = this.data.targets.slice();
    this.cachePoints = this.points.slice();
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes['data']) {
      this.setProperties();
    }
  }
  openPointsDetail() {
    this.pointsDetailVisible = true;
  }
  closePointsDetail() {
    this.pointsDetailVisible = false;
  }
  getTypeText(v: string) {
    return getHazardPlanTypeText(v);
  }
  getFrequencyText(d: Hazard.InspectionPlan) {
    return getFrequencyText(d);
  }
  getDepartmentsName(ids: number[]) {
    return ids.map(id => this.basic.getDepartmentName(id)).join(', ');
  }
  createPointsEditModal() {
    const updateCallback = new EventEmitter();
    updateCallback.subscribe(async () => {
      const targets = this.cachePoints.slice();
      await this.api.hazard.updatePlan({
        ...this.data,
        targets,
      });
      this.closePointsEditModal();
      this.onFetchDetail.emit(this.data.id);
      this.message.success('编辑成功');
    });

    this.pointsEditModal = this.modal.create({
      nzMaskClosable: false,
      nzClassName: 'picker-modal precaution-modal',
      nzContent: RiskItemPickerModalComponent,
      nzOkText: '保存',

      nzData: {
        types: this.knowledge.types(),
        categories: this.knowledge.categories(),
        items: this.knowledge.riskItems(),
        checkItemIds: this.cachePoints.slice(),
        onChange: this.onCacheChange.bind(this),
      },
      // nzAfterClose: updateCallback,
      nzOnOk: updateCallback,
      nzWidth: '1140px',
    });
  }
  closePointsEditModal() {
    this.pointsEditModal?.close();
  }
  confirmToPublish() {
    const modalRef = this.modal.warning({
      nzClassName: 'precaution-modal',
      nzTitle: '确认下发',
      nzContent: '确定要下发该计划吗？',
      nzOkText: '下发',
      nzOnOk: async () => {
        modalRef.updateConfig({
          nzOkLoading: true,
        });
        await this.api.hazard.publishPlan(this.data.id).finally(() => {
          modalRef.destroy();
        });
        this.message.success('下发成功');
        this.onFetchDetail.emit(this.data.id);
      },
    });
  }
  onCacheChange(ids: number[]) {
    this.cachePoints = ids;
  }
  openDepartmentsEditModal() {
    function getDisabled(depId: number, level: PlanLevel, user: Auth.User) {
      if (level === PlanLevel.COMPANY) {
        return false;
      }
      if (level === PlanLevel.DEPARTMENT) {
        return user.department !== depId;
      }
      return true;
    }
    const { user, isAdmin } = this.setting;
    this.temporaryDepartmentOptions = this.basic.departments
      .filter(d => d.name !== '所有部门')
      .map(d => ({
        label: d.name,
        value: d.id.toString(),
        disabled: isAdmin ? false : getDisabled(d.id, this.data.level as PlanLevel, user!),
        checked: this.data.departments.includes(d.id),
      }));

    const selectModal = this.modal.create({
      nzTitle: '选择部门 - ' + this.data.level,
      nzContent: this.departmentsTpl,
      nzClassName: 'precaution-modal',
      nzOnOk: async () => {
        const departments = this.temporaryDepartmentOptions.filter(o => o.checked).map(o => Number(o.value));

        const onSubmit = () => {
          return new Promise(async (resolve, reject) => {
            await this.api.hazard
              .updatePlan({
                ...this.data,
                departments,
              })
              .then(() => {
                this.onFetchDetail.emit(this.data.id);
                this.message.success('编辑成功');
                selectModal && selectModal.destroy();
                return resolve(0);
              })
              .catch(e => reject(e));
          });
        };

        if (departments.length < 1) {
          this.message.error('请选择部门');
          return Promise.reject();
        }
        if (this.data.level === PlanLevel.DEPARTMENT && departments.length > 1) {
          this.message.error(PlanLevel.DEPARTMENT + '计划只能选择一个部门');
          return Promise.reject();
        }

        if (this.data.departments && this.data.departments.length) {
          if (departments.slice().sort().join(',') === this.data.departments.slice().sort().join(',')) {
            this.message.error('部门未发生变化');
            return Promise.reject();
          } else {
            this.modal.warning({
              nzClassName: 'precaution-modal',
              nzTitle: '修改部门',
              nzContent: `被移除的部门中已有的任务会被移除!
              确定要修改部门吗？`,
              nzOkText: '修改',
              nzOnOk: onSubmit,
            });
            return Promise.reject();
          }
        }
        return onSubmit();
      },
    });
  }
  get diffDays() {
    return dayjs(this.data.endDate).diff(this.data.startDate, 'day') + 1;
  }
  get riskItems() {
    return this.points.map(pId => this.knowledge.riskItems().find(p => p.id === pId)!);
  }
  get departmentOptions() {
    return this.basic.departments.slice().map(d => ({ label: d.name, value: d.id }));
  }

  get authToModifyPlanBase() {
    return this.setting.isAdmin || this.setting.user?.id === this.data.createUserId;
  }

  get planBaseModifyAble() {
    switch (this.data.status) {
      case '未执行':
      case '制定中':
      case '已制定':
        return this.authToModifyPlanBase;
      default:
        return false;
    }
  }
}
