local this = class("pageHomeBag", G_UIPageBase)
local _homeSeedTpl = L_GameTpl:getHomeSeedsTpl()
local _homeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _BlockTpl = L_GameTpl:getHomeBlockTpl()
local _commonItemTpl = L_GameTpl:getCommonItemTpl()
local DragAreaType = {BELT = 1, BAG = 2}

function this.bind()
  return {
    txt_title = "",
    grid_bag = L_Const.ModuleInfo.CellIconBag,
    enabled_scrollBag = true,
    verticalNormalizedPosition = 0,
    active_empty = false,
    txt_empty = "",
    active_buildInfo = false,
    active_seedInfo = false,
    module_buildInfo = {
      moduleName = "pages/home/homeBag/moduleHomeBagBuildInfo"
    },
    module_cropInfo = {
      moduleName = "pages/home/homeBag/moduleHomeBagCropInfo"
    },
    module_belt = {
      moduleName = "pages/home/homeBag/moduleHomeBelt"
    },
    img_drag = ""
  }
end

function this.methods()
  return {
    onClick_close = function()
      L_UI:close("pageHomeBag")
    end
  }
end

local TagId2ShortBar = {
  [L_Const.commonTag.HOME_BUILDING] = L_Const.HomeShortcutBarType.HSBT_BUILD,
  [L_Const.commonTag.HOME_SEED] = L_Const.HomeShortcutBarType.HSBT_CROP
}
local BuildingTag = L_Const.commonTag.HOME_BUILDING
local SeedTag = L_Const.commonTag.HOME_SEED

function this:preOpen()
  self:endDrag()
  self._bagItems = {}
  self:configTouch("+")
  L_BagStore:listenCallFunc(L_BagStore.event.refreshBag, self.refresView, self)
  L_HomeStore:listenCallFunc(L_HomeStore.event.refreshBuildingBag, self.refresView, self)
  self.moduleTag = BuildingTag
  local buildGuid = L_HomeManager:getCurrInteractId()
  local buildingEntity = AzurWorld.HomeMgr and AzurWorld.HomeMgr:GetHomeBuild(buildGuid)
  if buildingEntity and buildingEntity:GetStoreData():GetGroupConfig().type == 15 then
    self.moduleTag = SeedTag
  else
    self.moduleTag = BuildingTag
  end
end

function this:show()
  self.modules.module_belt:registerShortCut(self.pageName)
  self:onSelectTabId(self.moduleTag)
end

function this:onSelectTabId(tabId)
  self._beltType = TagId2ShortBar[tabId]
  self._selectIndex = 0
  self:refresView()
  self.bind.verticalNormalizedPosition = 1
end

function this:close()
  self:configTouch("-")
  L_BagStore:unListenCallFunc(L_BagStore.event.refreshBag, self.refresView, self)
  L_HomeStore:unListenCallFunc(L_HomeStore.event.refreshBuildingBag, self.refresView, self)
  L_TimerManager:clearTimer(self)
end

function this:refresView()
  self.bind.txt_title = self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD and L_WordsTpl:getValue("notice_homeProduction_14") or L_WordsTpl:getValue("notice_homeProduction_15")
  self._bagItems = {}
  if self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD then
    local bagHomeItems = L_HomeStore:getAllBagBuilding()
    for _, v in pairs(bagHomeItems) do
      local num = v.total_num - v.used_num
      if 0 < num then
        local tpl = _homeBuildingTpl:getTplById(v.build_id)
        local stackNum = _homeBuildingTpl:getStackNum(tpl)
        if 0 < stackNum then
          while 0 < num do
            table.insert(self._bagItems, {
              build_id = v.build_id,
              num = math.min(stackNum, num)
            })
            num = num - stackNum
          end
        else
          table.insert(self._bagItems, {
            build_id = v.build_id,
            num = num
          })
        end
      end
    end
  elseif self._beltType == L_Const.HomeShortcutBarType.HSBT_CROP then
    local allItems = L_BagStore:getAllItem()
    for id, v in pairs(allItems) do
      if _homeSeedTpl:getIsSeed(id) then
        local batches = L_BagManager:getStackCommonItemData(id)
        for i, num in ipairs(batches) do
          if 0 < num then
            table.insert(self._bagItems, {item_id = id, num = num})
          end
        end
      end
    end
  end
  local colNum = L_DeviceTpl:getIsPc() and 9 or 8
  local bagBoxNum = math.max(math.ceil(#self._bagItems / colNum) * colNum, colNum * 6)
  if #self.modules.grid_bag ~= bagBoxNum then
    self.bind.grid_bag:clear()
    self.bind.grid_bag:insert_array(L_DataUtil.getEmptyModuleDatas(bagBoxNum))
  end
  for i, module in ipairs(self.modules.grid_bag) do
    if self._bagItems[i] then
      local img = ""
      local conf, itemid
      if self._bagItems[i].item_id then
        itemid = self._bagItems[i].item_id
        conf = L_ItemTplManager:getCommonItem(self._bagItems[i].item_id)
        img = conf.icon
      elseif self._bagItems[i].build_id then
        itemid = self._bagItems[i].build_id
        conf = L_ItemTplManager:getBuildingItem(self._bagItems[i].build_id)
        img = conf.icon
      end
      module:setDataContent(L_Const.resType.warehouse, nil, itemid, {
        itemNum = self._bagItems[i].num,
        icon = img,
        quality = conf.quality,
        callback = function()
          self:onSelectItem(i)
        end,
        noTip = true
      })
    else
      module:setGeneralContent(L_Const.resType.warehouse, nil, nil)
    end
    module:setQualityLineActive(self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD)
  end
  self.modules.module_belt:setBelt(self._beltType, false, {
    onClickCell = function(index)
      self:onBeltClick(index)
    end
  })
  self:refreshSelect()
end

function this:onBeltClick(index)
  self:endDrag()
end

function this:onSelectItem(index)
  local targetItem = self._bagItems[index]
  if not targetItem then
    return
  end
  if self._selectIndex ~= index then
    self._selectIndex = index
    self:refreshSelect(true)
  end
end

function this:refreshSelect(forceAni)
  if math.isEmpty(self._selectIndex) and #self._bagItems > 0 then
    self._selectIndex = 1
  end
  self.bind.active_empty = math.isEmpty(self._selectIndex)
  for i, module in ipairs(self.modules.grid_bag) do
    module:setSel(self._bagItems[self._selectIndex] and self._selectIndex == i or false)
  end
  local targetItem = self._bagItems[self._selectIndex]
  self.bind.txt_empty = self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD and L_WordsTpl:getValue("notice_homeProduction_16") or L_WordsTpl:getValue("notice_homeProduction_17")
  self.bind.active_buildInfo = targetItem ~= nil and self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD
  self.bind.active_seedInfo = targetItem ~= nil and self._beltType == L_Const.HomeShortcutBarType.HSBT_CROP
  if targetItem then
    if self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD then
      self.modules.module_buildInfo:setBuildId(targetItem.build_id, self._lastTarget == nil, forceAni)
    elseif self._beltType == L_Const.HomeShortcutBarType.HSBT_CROP then
      self.modules.module_cropInfo:setSeedId(targetItem.item_id, self._lastTarget == nil, forceAni)
    end
  end
  self._lastTarget = targetItem
end

function this:endDrag()
  printf("\230\139\150\230\139\189\231\187\147\230\157\159")
  self._holdType, self._holdId = nil, nil
  self.bindComponents.rect_drag.gameObject:ActiveTrans(false)
  self.bind.enabled_scrollBag = true
end

function this:getHoldInfo(go)
  for i, module in ipairs(self.modules.grid_bag) do
    if module:getRaycastGo() == go then
      return DragAreaType.BAG, i
    end
  end
  local res = self.modules.module_belt:checkRaycastGo(go)
  if res then
    return DragAreaType.BELT, res
  end
end

function this:configTouch(operator)
  self.onUITouchHandle = self.onUITouchHandle or L_CommonUtil.handle(self.onUI_touchHandle, self)
  self.onUIDragHandle = self.onUIDragHandle or L_CommonUtil.handle(self.onUI_dragHandle, self)
  self.onUIDragEndHandle = self.onUIDragEndHandle or L_CommonUtil.handle(self.onUI_dragEndHandle, self)
  self.onUIClickHandle = self.onUIClickHandle or L_CommonUtil.handle(self.onUI_clickHandle, self)
  C_ScreenTouch.OnUI_LongTapEnd(operator, self.onUIClickHandle)
  C_ScreenTouch.OnUI_Click(operator, self.onUIClickHandle)
  C_ScreenTouch.OnUI_Touch(operator, self.onUITouchHandle)
  C_ScreenTouch.OnUI_Drag(operator, self.onUIDragHandle)
  C_ScreenTouch.OnUI_DragEnd(operator, self.onUIDragEndHandle)
end

function this:onUI_clickHandle(gesture)
  self:endDrag()
end

function this:onUI_touchHandle(gesture)
  local go = gesture.go
  local holdType, holdId = self:getHoldInfo(go)
  if not holdType then
    return
  end
  if holdType == DragAreaType.BAG and not self._bagItems[holdId] then
    return
  end
  local beltIds = table.clone(L_HomeStore:getBeltItems(self._beltType))
  if holdType == DragAreaType.BELT and math.isEmpty(beltIds[holdId]) then
    return
  end
  local touchPos = L_Vector3.screenToLocalInRectangle(self.bindComponents.rect_content, gesture.position)
  if not self.isBind then
    return
  end
  printf("\229\188\128\229\167\139\230\139\150\230\139\189")
  self._holdType, self._holdId = holdType, holdId
  if holdType == DragAreaType.BAG then
    self:onSelectItem(holdId)
    local itemData = self._bagItems[holdId]
    if self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD then
      local tpl = _homeBuildingTpl:getTplById(itemData.build_id)
      self.bind.img_drag = _homeBuildingTpl:getBuildIcon(tpl)
    elseif self._beltType == L_Const.HomeShortcutBarType.HSBT_CROP then
      self.bind.img_drag = L_ItemTplManager:getCommonItem(itemData.item_id).icon
    end
  elseif holdType == DragAreaType.BELT then
    if self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD then
      local tpl = _homeBuildingTpl:getTplById(beltIds[holdId])
      self.bind.img_drag = _homeBuildingTpl:getBuildIcon(tpl)
    elseif self._beltType == L_Const.HomeShortcutBarType.HSBT_CROP then
      self.bind.img_drag = L_ItemTplManager:getCommonItem(beltIds[holdId]).icon
    end
  end
  self.bindComponents.rect_drag.gameObject:ActiveTrans(true)
  self.bind.enabled_scrollBag = false
  L_Vector3.setAnchored(self.bindComponents.rect_drag, touchPos)
end

function this:onUI_dragHandle(gesture)
  local touchPos = L_Vector3.screenToLocalInRectangle(self.bindComponents.rect_content, gesture.position)
  L_Vector3.setAnchored(self.bindComponents.rect_drag, touchPos)
end

function this:onUI_dragEndHandle(gesture)
  local go = gesture:GetCurrentFirstPickedUIElement()
  if self._holdId then
    local holdType, holdId = self:getHoldInfo(go)
    self:handleDragEffect(self._holdType, self._holdId, holdType, holdId)
  end
  self:endDrag()
end

function this:handleDragEffect(fromType, fromId, toType, toId)
  local beltIds = table.clone(L_HomeStore:getBeltItems(self._beltType))
  if fromType == DragAreaType.BELT then
    if toType == DragAreaType.BELT then
      beltIds[fromId], beltIds[toId] = beltIds[toId], beltIds[fromId]
    else
      beltIds[fromId] = 0
    end
  elseif fromType == DragAreaType.BAG and toType == DragAreaType.BELT then
    local itemData = self._bagItems[fromId]
    local tarId = 0
    if itemData then
      if self._beltType == L_Const.HomeShortcutBarType.HSBT_BUILD then
        tarId = itemData.build_id
      elseif self._beltType == L_Const.HomeShortcutBarType.HSBT_CROP then
        tarId = itemData.item_id
      end
    end
    for i, id in ipairs(beltIds) do
      if id == tarId then
        beltIds[i] = 0
      end
    end
    beltIds[toId] = tarId
  end
  L_HomeStore:req_changeBelt(self._beltType, beltIds)
end

function this:check(options, callback)
  local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.homeBag)
  local currBlockId, currGridId = L_HomeUtil:getPlayerInBlock()
  local blockTpl = _BlockTpl:getTplById(currBlockId)
  if blockTpl and _BlockTpl:getBlockType(blockTpl) == L_HomeConst.blockType.BUILD then
    callback(L_HomeUtil.getIsBlockUnlock(currBlockId) and result)
    return
  end
  callback(false)
end

return this
