local this = class("pagePhotoPreview", G_UIPageBase)

function this.bind()
  return {
    activeImgPreview = false,
    activeMoviePreview = false,
    activeShowInfo = false,
    activeShowLogo = false,
    activeLogo = false,
    activeInfo = false,
    txt_playerName = "",
    txt_playerLevel = "",
    activeEdit = false,
    activeQQ = true,
    activeWechat = true,
    activeTiktok = true
  }
end

function this.methods()
  return {
    onClick_close = function(self)
      L_UI:close(self.pageName)
    end,
    onClick_save = function(self)
      if self.rt then
        self:saveTexture()
      elseif not string.isEmpty(self.moviePath) then
        self:saveMovie()
      end
    end,
    onClick_qq = function(self)
    end,
    onClick_wechat = function(self)
    end,
    onClick_tiktok = function(self)
    end,
    onClick_edit = function(self)
      L_UI:open("pagePhotoEdit", {
        rt = self.rt,
        onEditComplete = handler(self, self.onEditComplete)
      })
    end,
    onValueChange_togInfo = function(self, isOn)
      self:showPlayerInfo(isOn)
    end,
    onValueChange_togLogo = function(self, isOn)
      self:showLogo(isOn)
    end
  }
end

function this:preOpen(options)
  self.saveFlags = {}
  self.rt = options.rt
  self.moviePath = options.moviePath
  if self.rt then
    self.tex = self.rt:ToTexture2D()
    C_CameraCaptureUtil.SetAlphaOne(self.tex)
    self.bind.activeEdit = not options.isPhotoTask
    self:showImg()
    self.bind.activeShowInfo = not options.isPhotoTask
    self.bind.activeShowLogo = not options.isPhotoTask
    self.bind.activeQQ = not options.isPhotoTask
    self.bind.activeWechat = not options.isPhotoTask
    self.bind.activeTiktok = not options.isPhotoTask
    self:fitPhotoSize()
  elseif not string.isEmpty(self.moviePath) then
    self.bind.activeEdit = false
    self.bind.activeShowInfo = false
    self.bind.activeShowLogo = false
    self:showMovie()
  end
end

function this:showImg()
  self.bindComponents.imgPreview.texture = self.tex
  self.bind.activeImgPreview = true
  local mat = C_UnityObject.Instantiate(self.bindComponents.imgPreview.material)
  mat:EnableKeyword("FIX_TO_GAMMA")
  self.bindComponents.imgPreview.material = mat
end

function this:saveTexture()
  local platform = C_SettingUtility.GetPlatform()
  if platform == L_Const.platform.windows or platform == L_Const.platform.editor then
    local dir = CS.System.Environment.GetFolderPath(CS.System.Environment.SpecialFolder.MyPictures) .. "/LSXY_PHOTO"
    if not self.saveFlags[self:getSaveFlag()] then
      self:addSaveFlag()
      local path = string.format("%s/photo_%s.png", dir, CS.System.DateTime.Now:ToString("yyMMddHHmmss"))
      if self.bind.activeInfo or self.bind.activeLogo then
        local texture = self:saveWithRt()
        C_PhotoManager.SaveTexture2DByPath(path, texture, false)
      else
        C_PhotoManager.SaveTexture2DByPath(path, self.tex, false)
      end
      printf(path)
    end
    if L_PhotoManager.useHighResolution then
      L_FlyMsgManager:showNormalMsgByKey("notice_pagePhotoPreview_hero_01", {
        [0] = dir
      })
    else
      L_FlyMsgManager:showNormalMsgByKey("notice_photo_address", {
        [0] = dir
      })
    end
  else
    L_FlyMsgManager:showNormalMsg("\239\191\189\239\191\189\198\189\204\168\239\191\189\239\191\189\206\180\214\167\239\191\189\239\191\189")
  end
end

function this:showMovie()
  self.bind.activeMoviePreview = true
  self.bindComponents.moviePlayer:PlayMovieByPath(self.moviePath, true)
end

function this:saveMovie()
  local platform = C_SettingUtility.GetPlatform()
  if platform == L_Const.platform.windows or platform == L_Const.platform.editor then
    local dir = CS.System.Environment.GetFolderPath(CS.System.Environment.SpecialFolder.MyVideos) .. "/LSXY_VIDEOS/"
    if not self.saveFlag then
      C_FileUtility.MoveFile(self.moviePath, dir)
      printf(dir)
      self.saveFlag = true
    end
    L_FlyMsgManager:showNormalMsgByKey("notice_photo_address", {
      [0] = dir
    })
  else
    L_FlyMsgManager:showNormalMsgByKey("notice_pagePhotoPreview_hero_02")
  end
end

function this:close()
  if self.rt then
    C_RenderTexture.ReleaseTemporary(self.rt)
  end
end

function this:fitPhotoSize()
  local width = self.tex.width
  local height = self.tex.height
  local containerSize = self.bindComponents.imgContainer.rect.size
  local ratio = width / height
  local targetWidth, targetHeight
  if ratio < containerSize.x / containerSize.y then
    targetHeight = containerSize.y
    targetWidth = targetHeight * ratio
  else
    targetWidth = containerSize.x
    targetHeight = targetWidth / ratio
  end
  local size = C_Vector2(targetWidth, targetHeight)
  self.bindComponents.imgRect.sizeDelta = size
end

function this:showLogo(isOn)
  self.bind.activeLogo = isOn
end

function this:showPlayerInfo(isOn)
  self.bind.activeInfo = isOn
  if isOn and not self.isInitInfo then
    self.isInitInfo = true
    self:initPlayerInfo()
  end
end

function this:initPlayerInfo()
  L_PhotoManager:loadHeadTex(L_FriendStore:getPlayerAvatars(L_PlayerStore:getPlayerBaseInfo(), L_Const.avatarTextureIndex.head), function(tex)
    if self.bindComponents.img_playerHead ~= nil and tex ~= nil then
      local rect = C_Rect(0, 0, tex.width, tex.height)
      local pivot = C_Vector2.one * 0.5
      self.bindComponents.img_playerHead.sprite = Unity.Sprite.Create(tex, rect, pivot)
    end
  end)
  self.bind.txt_playerName = L_PlayerStore:getPlayerName()
  self.bind.txt_playerLevel = tostring(L_PlayerStore:getLv())
end

function this:initCaptureCanvas()
  local canvas = L_ResPool:syncGameObject("Program/UIScene/pre_UICaptureCanvas.prefab", C_LuaUtility.GetRootNode())
  self.captureCanvas = canvas
  local cam = canvas.transform:Find("UICaptureCamera"):GetComponent(typeof(CS.UnityEngine.Camera))
  self.cam = cam
end

function this:copyRoot()
  local targetSize = C_Vector2(self.tex.width, self.tex.height)
  local curSize = self.bindComponents.imgRect.sizeDelta
  local scale = C_Vector3(targetSize.x / curSize.x, targetSize.y / curSize.y, 1)
  local newRoot = C_UnityObject.Instantiate(self.bindComponents.imgPreview.gameObject, self.captureCanvas.transform)
  newRoot.transform.localPosition = C_Vector3.zero
  newRoot.transform.localScale = scale
end

function this:saveWithRt()
  self:initCaptureCanvas()
  self:copyRoot()
  local camRt = C_RenderTexture.GetTemporary(self.tex.width, self.tex.height)
  self.cam.targetTexture = camRt
  self.cam:Render()
  local texture = C_CameraCaptureUtil.GetTextureFromRT(self.cam.targetTexture)
  C_CameraCaptureUtil.SetAlphaOne(texture)
  if self.captureCanvas then
    C_GameObject.Destroy(self.captureCanvas)
  end
  C_RenderTexture.ReleaseTemporary(camRt)
  return texture
end

function this:addSaveFlag()
  local f = self:getSaveFlag()
  if f then
    self.saveFlags[f] = true
  end
end

function this:getSaveFlag()
  local f
  local isPlayerInfo = self.bind.activeInfo
  local isLogo = self.bind.activeLogo
  if isPlayerInfo and isLogo then
    f = 3
  elseif not isPlayerInfo and not isLogo then
    f = 0
  elseif isPlayerInfo then
    f = 1
  elseif isLogo then
    f = 2
  end
  if f then
    return f
  end
end

function this:onEditComplete(tex)
  self.tex = tex
  self.bindComponents.imgPreview.texture = self.tex
  self:fitPhotoSize()
  self.saveFlags = {}
end

return this
