local IChatItemPost = require("UI.UIChatNewV2.Component.ChatItem.IChatItemPost")
local ChatItemPost_AllianceNotice = BaseClass("ChatItemPost_AllianceNotice", IChatItemPost)
local base = IChatItemPost
local ChatUploadPhoto = require("UI.UIChatNew.Component.UploadPhoto.ChatUploadPhoto")
local rapidjson = require("rapidjson")
local base64 = require("Framework.Common.base64")
local Localization = CS.GameEntry.Localization
local ExecuteEvents = CS.UnityEngine.EventSystems.ExecuteEvents
local ShareDecode = require("Chat.Other.ShareDecode")
local uploadImgDefaultSize = 96
local uploadImgHeightMax = 140

function ChatItemPost_AllianceNotice:OnCreate()
  base.OnCreate(self)
  self:ComponentDefine()
end

function ChatItemPost_AllianceNotice:ComponentDefine()
  self.bar = self:AddComponent(UIImage, "bar")
  self.txt_title = self:AddComponent(UITextMeshProUGUIEx, "bar/txtTitle")
  self.text = self:AddComponent(UITextMeshProUGUIEx, "Text")
  self._rootPhoto = self:AddComponent(UIBaseContainer, "RootPhoto")
  self._photoComponent = self:AddComponent(ChatUploadPhoto, "RootPhoto/ChatUploadPhoto")
  self.text:OnPointerClick(function(eventData)
    self:OnTxtRawPointerClick(eventData)
  end)
end

function ChatItemPost_AllianceNotice:OnLoaded()
  local path, key
  if self:ChatData().extra.noticeType == ChatNoticeType.ALLIANCE_VOTE then
    path = ChatInterface.GetChatUIPath("ChatNotice/zyf_tongmenggonggao_gonggaokuang_biaoti.png")
    key = "alliance_post_poll"
  else
    path = ChatInterface.GetChatUIPath("ChatNotice/sj_liaotian_gonggaobg.png")
    key = "2900001"
  end
  self.bar:LoadSprite(path)
  self.txt_title:SetLocalText(key)
  self:SetMessageTxt()
  local isHavePic, picVer, picSenderUid, smallHeight, smallWidth, bigHeight, bigWidth = self:ChatData():GetNoticePicData()
  local picSpace = 2
  local picContentW = 0
  if isHavePic then
    self._rootPhoto:SetActive(true)
    local showPicW = uploadImgDefaultSize
    local showPicH = uploadImgDefaultSize
    local showPicContentW = uploadImgDefaultSize
    local showPicContentH = uploadImgDefaultSize
    if smallHeight <= smallWidth then
      showPicW = uploadImgDefaultSize / smallHeight * smallWidth
    else
      showPicH = uploadImgDefaultSize / smallWidth * smallHeight
      showPicContentH = math.min(uploadImgHeightMax, showPicH)
    end
    self._rootPhoto:SetSizeDeltaXY(showPicContentW, showPicContentH)
    self._photoComponent:OnLoaded(nil, {
      picVer = picVer,
      senderUid = picSenderUid,
      bigWidth = showPicW,
      bigHeight = showPicH,
      isAdaptSize = false,
      isSizeSameContent = true,
      contentW = showPicContentW,
      contentH = showPicContentH
    }, {
      type = ReportType.chatPhoto,
      chatData = self:ChatData()
    })
    self._photoComponent:UpdatePhoto()
    picContentW = showPicContentW + picSpace
  else
    self._rootPhoto:SetActive(false)
  end
  local itemContentMaxWidth = 560
  local txtMaxWidth = itemContentMaxWidth - picContentW
  local preferredValues = self.text.unity_tmpro:GetPreferredValues(txtMaxWidth, 0)
  local textShowWidth = txtMaxWidth < preferredValues.x and txtMaxWidth or preferredValues.x
  self.text.rectTransform:SetSizeWithCurrentAnchors(CS.UnityEngine.RectTransform.Axis.Horizontal, textShowWidth)
  self.text.rectTransform:SetSizeWithCurrentAnchors(CS.UnityEngine.RectTransform.Axis.Vertical, preferredValues.y)
  if isHavePic then
    local txtAnchoredPos = self.text:GetAnchoredPosition()
    self._rootPhoto:SetAnchoredPositionXY(txtAnchoredPos.x + txtMaxWidth, txtAnchoredPos.y)
  end
end

function ChatItemPost_AllianceNotice:OnRecycle()
end

function ChatItemPost_AllianceNotice:SetMessageTxt()
  local chatData = self:ChatData()
  if chatData == nil then
    return
  end
  self.text.unity_tmpro:SetInputHtmlTagEmpty()
  if chatData.extraJsonData then
    local showNotice, noticeAddExtraJsonData = ChatInterface.GetShowNoticeAndAddTempData(chatData:getMsg(), chatData.extraJsonData)
    if noticeAddExtraJsonData and noticeAddExtraJsonData[ChatAlNoticeSpecialDataType.PointShare] then
      local pointShare = noticeAddExtraJsonData[ChatAlNoticeSpecialDataType.PointShare]
      if pointShare and 0 < #pointShare then
        local maxLinkEndIndex = string.word_count(showNotice) - 1 - 1
        for i = 1, #pointShare do
          local data = pointShare[i]
          local index = data[ChatAlNoticeSpecialDataParamType.Index]
          local strLen = data.wordLen
          local endIndex = index + strLen - 1
          self.text.unity_tmpro:AddInputHtmlTag("color=#249bc5", "/color", index - 1, endIndex - 1)
          self.text.unity_tmpro:AddInputHtmlTag("u", "/u", index - 1, endIndex - 1)
          local shareData = data[ChatAlNoticeSpecialDataParamType.shareData]
          local jumpData = {
            x = shareData.x,
            y = shareData.y,
            wid = shareData.worldId,
            sid = shareData.sid
          }
          local json = rapidjson.encode(jumpData)
          local linkId = base64.encode(json)
          local linkStarIndex = index - 1
          local linkEndIndex = endIndex - 1 - 1
          if maxLinkEndIndex < linkEndIndex and maxLinkEndIndex > linkStarIndex then
            linkEndIndex = maxLinkEndIndex
          end
          self.text.unity_tmpro:AddInputHtmlTag("link=" .. linkId, "/link", linkStarIndex, linkEndIndex)
        end
      end
    end
    self.text:SetText_NotNative(showNotice)
  else
    local message = self:ChatData():getSuperParsedResult()
    if message == nil then
      message = self:ChatData():getMessageWithExtra(false)
      self:ChatData():setSuperParsedResult(message)
    end
    self.text:SetText_NotNative(message)
  end
end

function ChatItemPost_AllianceNotice:OnTxtRawPointerClick(eventData)
  local clickPos = eventData.position
  local linkId = self.text:TryGetPointerClickLinkID(clickPos)
  if string.IsNullOrEmpty(linkId) then
    local targetObj = self.gameObject
    local deepFindLen = 2
    for i = 1, deepFindLen do
      local parent = targetObj.transform.parent
      if IsNull(parent) then
        break
      end
      targetObj = parent.gameObject
      if self.text.unity_tmpro:ThroughPointerClickHandler(targetObj, eventData) then
        break
      end
    end
    return
  end
  local jsonData = base64.decode(linkId)
  if string.IsNullOrEmpty(jsonData) then
    return
  end
  local shareData = rapidjson.decode(jsonData)
  if shareData == nil then
    return
  end
  local chatData = {}
  if shareData.postType ~= nil then
    chatData.post = shareData.postType
  else
    chatData.post = PostType.Text_PointShare
  end
  chatData.param = shareData
  local shareStr = ShareDecode.Decode(chatData, shareData, true)
  local posX = shareData.x
  local posY = shareData.y
  local worldId = shareData.wid
  local sid = shareData.sid
  local point = SceneUtils.TilePosToIndex({x = posX, y = posY}, ForceChangeScene.World)
  UIUtil.ShowMessage(Localization:GetString("alliance_announcement_5", shareStr), 2, "", "", function()
    GoToUtil.CloseAllWindows()
    GoToUtil.GotoWorldPos(SceneUtils.TileIndexToWorld(point), nil, nil, nil, sid, worldId, nil)
  end, nil, nil, nil)
end

return ChatItemPost_AllianceNotice
