local this = class("pageHomePlayerEdit", G_UIPageBase)
local _BlockTpl = L_GameTpl:getHomeBlockTpl()
local _homeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _homeBuildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
local _liftAudio = "Play_SFX_System_FB_Home_Building_Lift"
local _dropAudio = "Play_SFX_System_FB_Home_Building_Drop"
local HomeBuildPutState = CS.Lens.Gameplay.Modules.Home.HomeBuildPutState
local editMode = {
  none = -1,
  create = 0,
  set = 1,
  move = 2,
  onlyMove = 3
}

function this.bind()
  return {
    goEditNode = true,
    toggleSure = true,
    toggleGarbage = true,
    active_btnContinue = false,
    active_continueOn = false,
    txt_continueNum = "",
    moduleMovementBlock = {
      moduleName = "modulePages/moduleMovementBlock"
    },
    module_belt = {
      moduleName = "pages/home/homeBag/moduleHomeBelt"
    },
    go_keepLook = false,
    go_tipSet = false,
    txt_tipSet = "",
    txt_btnCancel = L_WordsTpl:getValue("ui_home_arrange_8"),
    txt_btnGarbage = L_WordsTpl:getValue("ui_home_arrange_5"),
    txt_btnGarbageCant = L_WordsTpl:getValue("ui_home_arrange_5"),
    txt_btnRotate = L_WordsTpl:getValue("ui_home_arrange_3"),
    txt_btnSure = L_WordsTpl:getValue("ui_home_arrange_1"),
    txt_btnSureCant = L_WordsTpl:getValue("ui_home_arrange_1")
  }
end

function this.methods()
  return {
    onClick_exit = function(self)
      self:exit()
    end,
    onClick_cancel = function(self)
      L_UI:close(self.pageName)
    end,
    onClick_look = function(self)
    end,
    onClick_continue = function(self)
    end,
    onClick_garbage = function(self)
      self:unLocateBuilding()
    end,
    onClick_rotate = function(self)
      self:onClick_rotate()
    end,
    onClick_sure = function(self)
      self:locateHomeBuilding()
    end
  }
end

function this:check(options, callback)
  local currBlockId, currGridId = L_HomeUtil:getPlayerInBlock()
  local blockTpl = _BlockTpl:getTplById(currBlockId)
  if blockTpl and _BlockTpl:getBlockType(blockTpl) == L_HomeConst.blockType.BUILD and L_HomeUtil.getIsBlockUnlock(currBlockId) then
    self._manager = AzurWorld.HomeMgr
    self._curBlock = self._manager:GetHomeBlock(currBlockId)
  end
  if self._curBlock then
    if options.buildingId then
      local buildingTpl = _homeBuildingTpl:getTplById(options.buildingId)
      local groupTpl = _homeBuildingGroupTpl:getTplById(_homeBuildingTpl:getGroupId(buildingTpl))
      local buildType = _homeBuildingGroupTpl:getType(groupTpl)
      if buildType == 16 and self._curBlock:IsBuildTypeExist(buildType) then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_pageHomePlayerEdit_01"))
        callback(false)
        return
      end
    end
    callback(true)
  else
    callback(false)
  end
end

function this:preOpen(options)
  self.modules.module_belt:setBelt(L_Const.HomeShortcutBarType.HSBT_BUILD, false, {
    onClickCell = function(buildingId)
      self:onBeltClick(buildingId)
    end
  })
  L_CameraManager:getCameraTactics():SetCameraDis(8)
  L_CameraManager:getCameraTactics():SetFreezePinch(true)
  this.super.preOpen(self, options)
  options = options or {}
  self._curBlock:RecollectBarrier()
  self._manager:SetFocusBlock(self._curBlock.blockId)
  self._checkTime = 0
  self._checkOut = false
  L_ShortCutManager:addShortKeyFlag(self, "Esc", L_Const.AnchorType.Middle, self.bindComponents.opShortKeys, L_Vector3.new(-402.9, 197.5))
  L_ShortCutManager:addShortKeyFlag(self, "R", L_Const.AnchorType.Middle, self.bindComponents.opShortKeys, L_Vector3.new(-326.3, 326.6))
  L_ShortCutManager:addShortKeyFlag(self, "Q", L_Const.AnchorType.Middle, self.bindComponents.opShortKeys, L_Vector3.new(-200.4, 394.9))
  if options.buildingId then
    self:doEditEntity(options.buildingId)
  elseif options.entity then
    self:doMoveEntity(options.entity)
  else
    errorf(L_WordsTpl:getValue("notice_pageHomePlayerEdit_02"))
  end
  self:initEditView()
end

function this:show()
  self.modules.moduleMovementBlock:showOrHideBtnRoot(false)
  self.modules.moduleMovementBlock:refreshBtnPos()
  self:registerShortCut()
end

function this:onBeltClick(buildingId)
  if self._buildMode ~= editMode.set or buildingId == 0 then
    return
  end
  local buildingTpl = _homeBuildingTpl:getTplById(buildingId)
  local groupTpl = _homeBuildingGroupTpl:getTplById(_homeBuildingTpl:getGroupId(buildingTpl))
  local buildType = _homeBuildingGroupTpl:getType(groupTpl)
  if buildType == 16 and self._curBlock:IsBuildTypeExist(buildType) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_pageHomePlayerEdit_01"))
    return
  end
  local build = L_HomeStore:getBuildingInBag(buildingId)
  local restNum = build.total_num - build.used_num
  if restNum == 0 then
    return
  end
  local editEntity = self._curBlock.defaultEditBuild
  editEntity.buildId = buildingId
end

function this:doEditEntity(buildingId)
  self._buildMode = editMode.set
  local editEntity = self._curBlock.defaultEditBuild
  editEntity.buildId = buildingId
  local _, cameraY, _ = L_CameraManager:getSceneCamera().transform:GetEulerAngles()
  editEntity:SetLocate(C_Vector2(0, 0), (math.floor((cameraY + 45) % 360 / 90) + 2) % 4)
  self:setCurSelectedEntity(editEntity)
end

function this:doMoveEntity(entity)
  if L_HomeStore:getStatusByGuid(entity.guid) == L_Const.WorldMapBuildStatusType.WMBST_NORMAL then
    self._buildMode = editMode.move
  else
    self._buildMode = editMode.onlyMove
  end
  self:setCurSelectedEntity(entity)
end

function this:exit()
  L_UI:close(self.pageName)
end

function this:close(options)
  L_CameraManager:getCameraTactics():SetCameraDis(3.5)
  L_CameraManager:getCameraTactics():SetFreezePinch(false)
  self._buildMode = nil
  self._manager:SetFocusBlock(0)
  self:setCurSelectedEntity(nil)
  self._curBlock = nil
end

function this:registerShortCut()
  L_ShortCutManager:registerShortCut(self.pageName, C_InputManager_KeyType.EHomeBuildingGarbage, function()
    local player = C_EntityManager.MainPlayer
    local mouseLock = player.data.playerMouseLock
    if mouseLock then
      return
    end
    self:unLocateBuilding()
  end)
  L_ShortCutManager:registerShortCut(self.pageName, C_InputManager_KeyType.EHomePlayerEditRotate, function()
    local player = C_EntityManager.MainPlayer
    local mouseLock = player.data.playerMouseLock
    if mouseLock then
      return
    end
    self:onClick_rotate()
  end)
  L_ShortCutManager:registerShortCut(self.pageName, C_InputManager_KeyType.EHomePlayerContinue, function()
  end)
  L_ShortCutManager:registerShortCut(self.pageName, C_InputManager_KeyType.EHomePlayerLook, function()
  end)
  L_ShortCutManager:registerShortCut(self.pageName, C_InputManager_KeyType.EHomePlayerBuilding, function()
    local player = C_EntityManager.MainPlayer
    local mouseLock = player.data.playerMouseLock
    if mouseLock then
      return
    end
    self:locateHomeBuilding()
  end)
  self.modules.module_belt:registerShortCut(self.pageName)
end

function this:resetSelection()
  self._buildMode = editMode.none
  self:setCurSelectedEntity(nil)
end

function this:setCurSelectedEntity(select)
  if self._curSelectBuild == select then
    return
  end
  self._curBlock:RecollectBarrier()
  self._curSelectBuild = select
  self._curBlock:SetEditBuild(select)
end

function this:initEditView()
  local tpl = _homeBuildingTpl:getTplById(self._curSelectBuild.buildId)
  local groupId = _homeBuildingTpl:getGroupId(tpl)
  local groupTpl = _homeBuildingGroupTpl:getTplById(groupId)
  local isCanGarbage = _homeBuildingGroupTpl:getIsStorable(groupTpl)
  self.bind.toggleGarbage = self._buildMode == editMode.move and isCanGarbage
  L_ShortCutManager:addShortKeyFlag(self, "F", L_Const.AnchorType.Middle, self.bindComponents.toggle_sure, L_Vector3.new(0, -84))
  L_AudioUtil.playSound(_liftAudio)
end

function this:getContinueInfo()
  local buildingId = self._curSelectBuild:getBuildingId()
  local buildingInfo = L_HomeStore:getBuildingInBag(buildingId)
  if buildingInfo.total_num - buildingInfo.used_num >= 1 then
    return true
  end
  return false
end

local setType2Tip = {
  [HomeBuildPutState.OVERLAP_BUILD] = "notice_home_arrange_tip_1",
  [HomeBuildPutState.OUT_OF_AREA] = "notice_home_arrange_tip_2",
  [HomeBuildPutState.OVERLAP_BARRIER] = "notice_home_arrange_tip_8"
}

function this:refreshTips()
  self.bind.go_tipSet = false
  if self._checkOut then
    self.bind.go_tipSet = true
    self.bind.txt_tipSet = L_WordsTpl:getValue("notice_home_arrange_tip_6", {
      [0] = tostring(math.floor(5 - self._checkTime))
    })
  elseif self._curSelectBuild then
    local setType = self._curSelectBuild:GetPutState()
    self.bind.toggleSure = setType == HomeBuildPutState.SUCCESS
    if setType ~= HomeBuildPutState.SUCCESS then
      self.bind.go_tipSet = true
      self.bind.txt_tipSet = L_WordsTpl:getValue(setType2Tip[setType])
    end
  end
end

function this:locateHomeBuilding()
  if self._curSelectBuild == nil then
    return
  end
  if self._curSelectBuild:GetPutState() ~= HomeBuildPutState.SUCCESS then
    return
  end
  if self._buildMode == editMode.set then
    local buildingId = self._curSelectBuild.buildId
    local blockId, gridId, rotId = self._curBlock.blockId, self._curSelectBuild.gridId, self._curSelectBuild.rotId
    self:exit()
    L_HomeStore:req_locateBuilding(nil, buildingId, blockId, gridId, rotId, function()
      L_HomeUtil.checkStartBuildingGuide(buildingId)
    end)
  elseif self._buildMode == editMode.move or self._buildMode == editMode.onlyMove then
    local targetEntity = self._curSelectBuild
    local guid, blockId, gridId, rotId = self._curSelectBuild.guid, self._curBlock.blockId, self._curSelectBuild.gridId, self._curSelectBuild.rotId
    self:exit()
    L_HomeStore:req_locateBuilding(guid, nil, blockId, gridId, rotId, function()
      targetEntity:PlaySmoke()
      L_AudioUtil.playSound(_dropAudio)
    end)
  end
end

function this:unLocateBuilding()
  if self._curSelectBuild == nil then
    return
  end
  local csServerData = self._curSelectBuild:GetStoreData()
  local serverData = L_HomeStore:getHomeBuildingByGuid(self._curSelectBuild.guid)
  if not serverData then
    return
  end
  if serverData.status == L_Const.WorldMapBuildStatusType.WMBST_PRODUCT then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_pageHomePlayerEdit_03"))
    return
  elseif csServerData:GetGroupConfig().type == L_Const.WorldMapBuildType.WMBT_FIELD_NEW and csServerData.crop.seedId ~= 0 then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_pageHomePlayerEdit_04"))
    return
  elseif csServerData:GetGroupConfig().type == L_Const.WorldMapBuildType.WMBT_FIELD_HOUSE and (csServerData.auto.plantPetGuid ~= 0 or csServerData.auto.waterPetGuid ~= 0 or csServerData.auto.harvestPetGuid ~= 0) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_pageHomePlayerEdit_05"))
    return
  else
    local buildType = L_HomeManager:getBuildTypeById(serverData.build_id)
    if buildType == L_Const.WorldMapBuildType.WMBT_PET_CANTEEN and (0 < L_SatietyManager:getBuildingSatiety(serverData.guid) or L_SatietyManager:isBuildingHasPetEating(serverData.guid)) then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_moduleHomeBagCropInfo_01"))
      return
    end
  end
  local tpl = _homeBuildingTpl:getTplById(self._curSelectBuild.buildId)
  local groupId = _homeBuildingTpl:getGroupId(tpl)
  local groupTpl = _homeBuildingGroupTpl:getTplById(groupId)
  local isCanGarbage = _homeBuildingGroupTpl:getIsStorable(groupTpl)
  if not isCanGarbage then
    return
  end
  L_HomeStore:req_BuildUnlocate(self._curSelectBuild.guid, function()
    self:exit()
  end)
  self:setCurSelectedEntity(nil)
end

function this:onClick_rotate()
  local entity = self._curSelectBuild
  local direction = entity.rotId
  direction = (direction + 1) % 4
  entity:SetLocate(entity.gridPos, direction)
  self._curBlock:OnUpdate()
end

function this:update()
  self:outCheck()
  self:refreshTips()
end

function this:outCheck()
  local playerRelativeGridPos = self._curBlock:GetPlayerRelativeGridPos()
  local isIn = self._curBlock:CheckRelativeGridPosIsInBlockArea(playerRelativeGridPos)
  self._checkOut = not isIn
  if isIn then
    self._checkTime = 0
  end
  if self._checkOut then
    self._checkTime = self._checkTime + Unity.Time.deltaTime
  end
  if self._checkTime > 0 and self._checkTime >= 5 then
    self:exit()
  end
end

return this
