local this = class("pageHomeCropBox", G_UIPageBase)
local _homeSeedTpl = L_GameTpl:getHomeSeedsTpl()
local _homeDropTpl = L_GameTpl:getHomeDropTpl()
local DragAreaType = {BOX = 1, BAG = 2}

function this.bind()
  return {
    grid_bag = {
      moduleName = "pages/home/homeBag/cellIconHomeBag"
    },
    grid_box = {
      moduleName = "pages/home/homeBag/cellIconHomeBag"
    },
    enabled_scrollBag = true,
    enabled_scrollBox = true,
    img_drag = "",
    active_tip = false,
    offset_tip = C_Vector2.one,
    txt_time = "",
    txt_reward = "",
    txt_water = "",
    txt_rewardHave = "",
    txt_rewardName = "",
    module_num = {
      moduleName = "modulePages/moduleSelectNum"
    },
    txt_btn = L_WordsTpl:getValue("notice_homeProduction_27"),
    txt_name = L_WordsTpl:getValue("notice_homeProduction_25")
  }
end

function this.methods()
  return {
    onClick_close = function()
      L_UI:close("pageHomeCropBox")
    end,
    onClick_bg = function()
      L_UI:close("pageHomeCropBox")
    end,
    onClick_confirm = function()
      L_UI:close("pageHomeCropBox")
    end,
    onClick_set = function(self)
      if not self._selectedType then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_homeProduction_25"))
        return
      end
      local selectNum = self.modules.module_num:getNum()
      local targetItems = self._selectedType == DragAreaType.BAG and self._bagItems or self._boxItems
      local targetItem = targetItems[self._selectIndex]
      local currNum = targetItem.num
      local cb = function()
        if currNum <= selectNum then
          self._selectedType = nil
          self._selectIndex = nil
        end
        self:refreshSelect()
      end
      if self._selectedType == DragAreaType.BOX then
        self._autoData:Req_OperateSeed(L_Const.HomeOperateAutoWorkType.HOAWT_DEL, targetItem.item_id, selectNum, targetItem.guid, cb)
      else
        local guid = 0
        for i, item in ipairs(self._boxItems) do
          if item.item_id == targetItem.item_id then
            guid = item.guid
          end
        end
        self._autoData:Req_OperateSeed(L_Const.HomeOperateAutoWorkType.HOAWT_ADD, targetItem.item_id, selectNum, guid, cb)
      end
      self:onSelectItem(nil)
    end,
    onClick_auto = function(self)
      self._autoData:Req_AutoSelectSeed()
    end,
    onClick_nodeMask = function(self)
      if self.bind.active_tip then
        self.bind.active_tip = false
        for _, module in ipairs(self.modules.grid_box) do
          module:setSelect(false)
        end
        for _, module in ipairs(self.modules.grid_bag) do
          module:setSelect(false)
        end
        self._selectedType, self._selectIndex = nil, nil
        self:refreshSelect()
      end
    end
  }
end

function this:preOpen(params)
  self._buildingGuid = params.buildingGuid
  self._buildingData = C_HomeUtil.GetBuildData(self._buildingGuid)
  self._autoData = self._buildingData.auto
  self._bagItems = {}
  self._boxItems = {}
  self:endDrag()
  self:refreshBoxes()
  self:configTouch("+")
  L_BagStore:listenCallFunc(L_BagStore.event.refreshBag, self.refreshBoxes, self)
  
  function self._refreshFunc()
    self:refreshBoxes()
  end
  
  C_HomeStoreEvent.instance:Listen(C_EHomeStoreEvent.HomeBuildSync, self._refreshFunc)
end

function this:close()
  self:configTouch("-")
  L_BagStore:unListenCallFunc(L_BagStore.event.refreshBag, self.refreshBoxes, self)
  C_HomeStoreEvent.instance:Cancel(C_EHomeStoreEvent.HomeBuildSync, self._refreshFunc)
  L_TimerManager:clearTimer(self)
end

function this:refreshBoxes()
  local allItems = L_BagStore:getAllItem()
  self._bagItems = {}
  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
  local bagBoxNum = math.max(math.ceil(#self._bagItems / 4) * 4, 16)
  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
    module:refreshByItem(self._bagItems[i], function()
      self:onSelectItem(DragAreaType.BAG, i)
    end)
  end
  self._boxItems = {}
  for i = 0, self._autoData.seeds.Count - 1 do
    local seedItem = self._autoData.seeds[i]
    table.insert(self._boxItems, {
      item_id = seedItem.itemId,
      guid = seedItem.guid,
      num = seedItem.itemNum
    })
  end
  self.bindComponents.grid_boxContent.disableScroll = 0 >= self._autoData.seeds.Count
  local boxNum = math.max(math.ceil(#self._boxItems / 4) * 4, 16)
  if #self.modules.grid_box ~= boxNum then
    self.bind.grid_box:clear()
    self.bind.grid_box:insert_array(L_DataUtil.getEmptyModuleDatas(boxNum))
  end
  for i, module in ipairs(self.modules.grid_box) do
    module:refreshByItem(self._boxItems[i], function()
      self:onSelectItem(DragAreaType.BOX, i)
    end)
  end
  self:refreshSelect()
end

function this:onSelectItem(type, index)
  local targetItems = type == DragAreaType.BAG and self._bagItems or self._boxItems
  local targetItem = targetItems[index]
  if not targetItem then
    return
  end
  if self._selectedType ~= type or self._selectIndex ~= index then
    self._selectedType, self._selectIndex = type, index
  else
    self._selectedType, self._selectIndex = nil, nil
  end
  self:refreshSelect()
  self:endDrag()
end

function this:refreshSelect()
  for i, module in ipairs(self.modules.grid_bag) do
    module.bind.active_select = self._selectedType == DragAreaType.BAG and self._bagItems[i] and self._selectIndex == i or false
  end
  for i, module in ipairs(self.modules.grid_box) do
    module.bind.active_select = self._selectedType == DragAreaType.BOX and self._boxItems[i] and self._selectIndex == i or false
  end
  if not self._selectedType then
    self.bind.active_tip = false
  else
    self.bind.active_tip = true
    self.bind.offset_tip = C_Vector2(self._selectedType == DragAreaType.BOX and -218 or 232, 51)
    self.bind.txt_btn = self._selectedType == DragAreaType.BOX and L_WordsTpl:getValue("notice_homeProduction_26") or L_WordsTpl:getValue("notice_homeProduction_27")
    local targetItems = self._selectedType == DragAreaType.BAG and self._bagItems or self._boxItems
    local targetItem = targetItems[self._selectIndex]
    if targetItem then
      local seedTpl = _homeSeedTpl:getTplBySeedItemId(targetItem.item_id)
      if not seedTpl then
        return
      end
      self.bind.txt_name = L_ItemTplManager:getCommonItem(targetItem.item_id).name
      local buffCondition = L_HomeBuffManager:getCropCondition(_homeSeedTpl:getId(seedTpl))
      local growTime, preHarTime = L_HomeBuffManager:getCropGrowParam(_homeSeedTpl:getId(seedTpl), buffCondition)
      local totalTime = growTime + preHarTime
      self.bind.txt_time = L_TimeUtil.secondToString(totalTime, L_TimeUtil.secondToStringShowType.TWO_UNIT)
      self.bind.txt_reward = _homeSeedTpl:getNumShow(seedTpl)
      self.bind.txt_water = tostring(_homeSeedTpl:getNeedWater(seedTpl))
      local dropId = _homeSeedTpl:getHomeDropId(seedTpl)
      local dropTpl = _homeDropTpl:getTplById(dropId[1])
      local rewardItemId = _homeDropTpl:getItemId(dropTpl)
      local rewardItemType = _homeDropTpl:getItemType(dropTpl)
      local rewardItemConf = L_ItemTplManager:getItemConfig(rewardItemType, rewardItemId[1])
      self.bind.txt_rewardName = rewardItemConf.name
      self.bind.txt_rewardHave = tostring(L_BagStore:getItemNum(rewardItemId[1]))
    end
    self.modules.module_num:initModule(L_Const.emptyFunction, targetItem and targetItem.num or 1)
    self.modules.module_num:changeNum(targetItem and targetItem.num or 1)
  end
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
  for i, module in ipairs(self.modules.grid_box) do
    if module:getRaycastGo() == go then
      return DragAreaType.BOX, i
    end
  end
end

function this:configTouch(operator)
  self.onUITouchHandle = self.onUITouchHandle or L_CommonUtil.handle(self.onUI_touchHandle, self)
  self.onUIDragStartHandle = self.onUIDragStartHandle or L_CommonUtil.handle(self.onUI_dragStartHandle, 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)
  C_ScreenTouch.OnUI_Touch(operator, self.onUITouchHandle)
  C_ScreenTouch.OnUI_DragStart(operator, self.onUIDragStartHandle)
  C_ScreenTouch.OnUI_Drag(operator, self.onUIDragHandle)
  C_ScreenTouch.OnUI_DragEnd(operator, self.onUIDragEndHandle)
end

function this:onUI_touchHandle(gesture)
  local go = gesture.go
  local holdType, holdId = self:getHoldInfo(go)
  local targetItems = holdType == DragAreaType.BAG and self._bagItems or self._boxItems
  if not holdId or not targetItems[holdId] then
    return
  end
  local touchPos = L_Vector3.screenToLocalInRectangle(self.bindComponents.rect_content, gesture.position)
  L_FlyMsgManager:startLongPress(gesture, 0.5, function()
    if not self.isBind then
      return
    end
    self:onSelectItem(nil)
    printf("\229\188\128\229\167\139\230\139\150\230\139\189")
    self._holdType, self._holdId = holdType, holdId
    local targetItems = self._holdType == DragAreaType.BAG and self._bagItems or self._boxItems
    self.bind.img_drag = L_ItemTplManager:getCommonItem(targetItems[self._holdId].item_id).icon
    self.bindComponents.rect_drag.gameObject:ActiveTrans(true)
    self.bind.enabled_scrollBag = false
    self.bind.enabled_scrollBox = false
    L_Vector3.setAnchored(self.bindComponents.rect_drag, touchPos)
  end)
end

function this:onUI_dragStartHandle(gesture)
  if not self._holdId then
    printf("\230\139\150\230\139\189\228\184\173\230\150\173")
    L_TimerManager:stopTimer(self, "pressing")
  end
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)
  printf("\230\139\150\230\139\189\231\187\147\230\157\159")
  local go = gesture:GetCurrentFirstPickedUIElement()
  if self._holdId then
    local holdType, holdId = self:getHoldInfo(go)
    if holdId then
      self:handleDragEffect(self._holdType, self._holdId, holdType, holdId)
    end
  end
  self:endDrag()
end

function this:endDrag()
  L_TimerManager:stopTimer(self, "pressing")
  self._holdType, self._holdId = nil, nil
  self.bindComponents.rect_drag.gameObject:ActiveTrans(false)
  self.bind.enabled_scrollBag = true
  self.bind.enabled_scrollBox = true
end

function this:handleDragEffect(fromType, fromId, toType, toId)
  printf("\230\139\150\232\189\172", fromType, fromId, toType, toId)
  if fromType == DragAreaType.BAG then
    if toType == DragAreaType.BOX then
      local item = self._bagItems[fromId]
      local guid = 0
      for i, v in ipairs(self._boxItems) do
        if v.item_id == item.item_id then
          guid = v.guid
        end
      end
      local tpl = _homeSeedTpl:getSeedTplByItem(item.item_id)
      local condition = _homeSeedTpl:getCondition(tpl)
      if not L_ConditionManager:isComplete(condition) then
        L_FlyMsgManager:showNormalMsg(L_ConditionManager:getTipDesc(condition))
        return
      end
      self._autoData:Req_OperateSeed(L_Const.HomeOperateAutoWorkType.HOAWT_ADD, item.item_id, item.num, guid)
    end
  elseif toType == DragAreaType.BAG then
    local item = self._boxItems[fromId]
    self._autoData:Req_OperateSeed(L_Const.HomeOperateAutoWorkType.HOAWT_DEL, item.item_id, item.num, item.guid)
  else
    local item1 = self._boxItems[fromId]
    local item2 = self._boxItems[toId]
    if item2 and item1 then
      self._autoData:Req_ExchangeSeed(item1.guid, item2.guid)
    end
  end
end

return this
