import { config } from "../../constants/config"
import { respath } from "../../constants/respath"
import { MONTH_LIST } from "../../models/DCManager"
import { EVENT_TYPES, EventManager } from "../../models/EventManager"
import { ResourceManager } from "../../models/ResourceManager"
import { StorageManager } from "../../models/StorageManager"
import { UIManager } from "../../models/UIManager"
import { Utility_ConvertSecondToString } from "../../utils/utility"
import { CalendarUnit } from "./CalendarUnit"

const { regClass, property } = Laya
@regClass()
export class DailyChallenge extends Laya.Script {
  declare owner: Laya.Box

  @property(Laya.Sprite)
  public sprite_bottom: Laya.Sprite

  @property(Laya.Button)
  public btn_back: Laya.Button

  @property(Laya.Image)
  public btn_trophy: Laya.Image

  @property(Laya.Sprite)
  public btn_trophy_red: Laya.Sprite

  @property(Laya.Image)
  public trophy_light: Laya.Image

  @property(Laya.Image)
  public trophy_icon: Laya.Image

  @property(Laya.Box)
  public btn_left: Laya.Box

  @property(Laya.Box)
  public btn_right: Laya.Box

  @property(Laya.Box)
  public btn_left2: Laya.Box

  @property(Laya.Box)
  public btn_right2: Laya.Box

  @property(Laya.Image)
  public bg_dc: Laya.Image

  @property(Laya.Label)
  public label_year: Laya.Label

  @property(Laya.Label)
  public label_month: Laya.Label

  @property(Laya.Label)
  public label_star: Laya.Label

  @property(Laya.Box)
  public btn_play: Laya.Box

  @property(Laya.Label)
  public label_play: Laya.Label

  @property(Laya.Box)
  public obj_summary: Laya.Box

  @property(Laya.Label)
  public label_date: Laya.Label

  @property(Laya.Label)
  public label_diffucuty: Laya.Label

  @property(Laya.Label)
  public label_score: Laya.Label

  @property(Laya.Label)
  public label_time: Laya.Label

  @property(Laya.Box)
  public obj_items: Laya.Box

  private units: Array<CalendarUnit> = []

  private selectedUnit: CalendarUnit
  private currentIndex: number
  private indexMax: number

  private static _instance: DailyChallenge
  onAwake(): void {
    DailyChallenge._instance = this

    if (!config.H_SCREEN) {
      const parent = this.sprite_bottom.parent as Laya.Box
      this.sprite_bottom.graphics.clear()
      this.sprite_bottom.graphics.drawRoundRect(0, 0, parent.width, parent.height, 72, 72, 0, 0, "#ffffff")
    }

    if (this.btn_back) {
      this.btn_back.on(Laya.Event.CLICK, this, () => {
        UIManager.getInstance().loadHomeUI()
        UIManager.getInstance().closeDCUI()
      })
    }

    const user = StorageManager.getInstance().getUser()
    this.btn_trophy_red.visible = user.get_trophyHasUnread()
    this.btn_trophy.on(Laya.Event.CLICK, this, () => {
      user.set_trophyAllread()
      this.btn_trophy_red.visible = false
      UIManager.getInstance().loadTrophyUI()
    })

    this.btn_play.on(Laya.Event.CLICK, this, () => {
      const year = this.selectedUnit.year
      const month = this.selectedUnit.month
      const dayNow = this.selectedUnit.day
      const stageID = `${year}-${month}-${dayNow}`
      const doStage = StorageManager.getInstance().getStage(stageID)
      console.log("play >>>>>>>>>>>>>>>>>>>>>>>", stageID, doStage)
      if (!doStage || doStage.get_mistake() >= config.MISTAKE_MAX) {
        const stageName = `${config.MONTH_ABBRS[month - 1]} ${dayNow}`
        StorageManager.getInstance().newStage(stageID, config.STAGE_TYPE.DC, stageName)
      }
      UIManager.getInstance().loadStageUI(stageID)
      this.owner.destroy()
    })

    for (let i = 0; i < this.obj_items.numChildren; i++) {
      const hbox = this.obj_items.getChildAt(i)
      for (let j = 0; j < hbox.numChildren; j++) {
        const unit = hbox.getChildAt(j).getComponent(CalendarUnit)
        this.units.push(unit)
      }
    }

    this.indexMax = MONTH_LIST.length - 1
    const now = new Date()
    const nowYear = now.getFullYear()
    const nowMonth = now.getMonth() + 1
    for (let i = 0; i < MONTH_LIST.length; i++) {
      const obj = MONTH_LIST[i]
      if (nowYear === obj.year && nowMonth === obj.month) {
        this.indexMax = i
        break
      }
    }

    this.btn_left.on(Laya.Event.CLICK, this, this.onClickLeft)
    this.btn_right.on(Laya.Event.CLICK, this, this.onClickRight)
    this.btn_left2.on(Laya.Event.CLICK, this, this.onClickLeft)
    this.btn_right2.on(Laya.Event.CLICK, this, this.onClickRight)

    EventManager.getInstance().RegisterEvent(EVENT_TYPES.NOT_SET_TROPHY_BUTTON, DailyChallenge.EventUpdateTrophyButton)
  }

  onDestroy(): void {
    EventManager.getInstance().UnregisterEvent(EVENT_TYPES.NOT_SET_TROPHY_BUTTON, DailyChallenge.EventUpdateTrophyButton)
  }

  public static EventUpdateTrophyButton(arg: any): void {
    if (DailyChallenge._instance) {
      DailyChallenge._instance.owner.visible = arg
    }
  }

  loadWithMonth(nowYear: number, nowMonth: number): void {
    this.currentIndex = 0
    for (let i = 0; i < MONTH_LIST.length; i++) {
      const obj = MONTH_LIST[i]
      if (nowYear === obj.year && nowMonth === obj.month) {
        this.currentIndex = i
        break
      }
    }
    this.loadWithIndex(this.currentIndex)
  }

  public loadWithIndex(index: number): void {
    this.btn_left.visible = this.currentIndex > 0
    this.btn_right.visible = this.currentIndex < this.indexMax
    this.btn_left2.visible = this.currentIndex > 0
    this.btn_right2.visible = this.currentIndex < this.indexMax
    const info = MONTH_LIST[index]
    UIManager.getInstance().setCurrentDCMonth(info.year, info.month)
    console.log("DailyChallenge loadWithIndex >>>>>>>>>>>>>>>", info.year, info.month)
    const user = StorageManager.getInstance().getUser()
    const now = new Date()
    const nowYear = now.getFullYear()
    const nowMonth = now.getMonth() + 1
    const nowDay = new Date().getDate()

    ResourceManager.getInstance().loadTexture(info.icon_res, this.trophy_icon)
    // 设置背景
    if (user.get_trophyRecord(info.year, info.month)) {
      ResourceManager.getInstance().loadTexture(respath.dc_top_bg_finish, this.bg_dc)
      this.trophy_light.visible = true
      this.trophy_icon.gray = false
    } else {
      ResourceManager.getInstance().loadTexture(respath.dc_top_bg_normal, this.bg_dc)
      this.trophy_light.visible = false
      this.trophy_icon.gray = true
    }
    const starCount = user.get_doneCountByDate(info.year, info.month)
    this.label_year.text = info.year.toString()
    this.label_month.text = config.MONTH_FULLNAMES[info.month - 1]
    this.label_star.text = `${starCount}/${info.dayCount}`

    let todayUnit = null
    let lastUnfinishUnit = null
    let day = 1
    for (let i = 0; i < this.units.length; i++) {
      const unit = this.units[i]
      if (i >= info.begin && i < info.begin + info.dayCount) {
        unit.owner.visible = true
        unit.label_show.visible = true
        let open = true
        if (info.year > nowYear) {
          open = false
        } else if (info.year === nowYear) {
          if (info.month > nowMonth) {
            open = false
          } else if (info.month === nowMonth) {
            if (day > nowDay) {
              open = false
            }
          }
        }
        const stageID = `${info.year}-${info.month}-${day}`
        let progress = user.get_done(stageID)
        if (open && progress < 1) { // 检查失败的关卡，如果失败了就重置
          const doStage = StorageManager.getInstance().getStage(stageID)
          if (doStage) { // 有关卡数据
            if (doStage.get_mistake() >= config.MISTAKE_MAX) {
              progress = 0
              user.update_stage_done(stageID, 0)
              StorageManager.getInstance().cleanStage(stageID)
            }
          }
        }
        unit.setCalendarUnit(info.year, info.month, day, open, progress, this, this.onClickUnit)
        if (info.year === nowYear && info.month === nowMonth && day === nowDay) {
          todayUnit = unit
        }
        if (progress < 1) {
          lastUnfinishUnit = unit
        }
        day++
      } else {
        unit.owner.visible = false
        unit.label_show.visible = false
      }
    }
    if (todayUnit) {
      this.selectedUnit = todayUnit
    } else {
      this.selectedUnit = lastUnfinishUnit
    }
    if (!this.selectedUnit) {
      this.selectedUnit = this.units[info.begin + info.dayCount - 1]
    }
    this.onApplyUnit(this.selectedUnit)
  }

  public onApplyUnit(unit: CalendarUnit): void {
    this.selectedUnit.setSelected(false)
    this.selectedUnit = unit
    this.selectedUnit.setSelected(true)

    const stageID = `${unit.year}-${unit.month}-${unit.day}`
    this.label_date.text = `${config.MONTH_ABBRS[unit.month - 1]} ${unit.day}, ${unit.year}`
    const user = StorageManager.getInstance().getUser()
    const progress = user.get_done(stageID)
    // console.log("onApplyUnit >>>>>", stageID, progress)
    if (progress >= 1) {
      this.btn_play.visible = false
      this.obj_summary.visible = true
      const doStage = StorageManager.getInstance().getStage(stageID)
      this.label_diffucuty.text = doStage.get_difficulty()
      this.label_score.text = doStage.get_score().toString()
      this.label_time.text = Utility_ConvertSecondToString(doStage.get_duration())
    } else {
      this.btn_play.visible = true
      this.obj_summary.visible = false
      const doStage = StorageManager.getInstance().getStage(stageID)
      if (doStage) {
        this.label_play.text = "Continue"
      } else {
        this.label_play.text = "Play"
      }
    }
  }

  public onClickUnit(evt: Laya.Event): void {
    const unit = evt.target.getComponent(CalendarUnit)
    this.onApplyUnit(unit)
  }

  onClickLeft(): void {
    if (this.currentIndex > 0) {
      this.currentIndex--
      this.loadWithIndex(this.currentIndex)
    }
  }

  onClickRight(): void {
    if (this.currentIndex < this.indexMax) {
      this.currentIndex++
      this.loadWithIndex(this.currentIndex)
    }
  }

  onStart(): void {
    const user = StorageManager.getInstance().getUser()
    const find = user.get_trophyHasNew()
    if (find) {
      UIManager.getInstance().loadTrophyClaimUI(find)
      user.set_trophyNew(find, false)
    }
  }
}
