local this = {}

function this:init()
  this.super.init(self)
  self.data = {
    achievementList = {},
    achievementGroupRewardList = {}
  }
end

function this:state()
  return {}
end

function this:getAchievementItem(achievementId, isCreate)
  local entity = self.data.achievementList[achievementId]
  if entity == nil and isCreate then
    entity = require(L_R.store .. "achievement.achievementItem").new()
    self.data.achievementList[achievementId] = entity
    entity.achievementId = achievementId
  end
  return entity
end

function this:getAchievementListByGroupId(groupId)
  local list = self.data.achievementList
  local res = {}
  for k, v in pairs(list) do
    if v.groupId == groupId then
      res[v.achievementId] = v
    end
  end
  return res
end

function this:getAchievementList()
  return self.data.achievementList
end

function this:getIsAchievementRewardCollect(groupId)
  return self.data.achievementGroupRewardList[groupId] or false
end

function this:getFinishCountOfGroup(groupId)
  local achievement_list = self:getAchievementListByGroupId(groupId)
  local finish_count = 0
  for i, v in pairs(achievement_list) do
    if self:getIsAchievementCompleted(v.achievementId) then
      finish_count = finish_count + v.version
    else
      finish_count = finish_count + v.version - 1
    end
  end
  return finish_count
end

function this:getIsAchievementCompleted(achievementId)
  local achievementTpl = L_GameTpl:getAchievementTpl()
  local tpl = achievementTpl:getTplById(achievementId)
  local conditions = achievementTpl:getFinishCondi(tpl)
  local param = achievementTpl:getParam(tpl)
  local first_achievementId = achievementTpl:getFirstAchi(tpl)
  achievementId = first_achievementId == 0 and achievementId or first_achievementId
  local countList = self:getAchievementItem(achievementId).count
  for i = 1, #conditions do
    if param > countList[i] then
      return false
    end
  end
  return true
end

function this:getEachLevelFinishNum()
  local achievement_list = self:getAchievementList()
  local finishRate_dic = {}
  local achievementTpl = L_GameTpl:getAchievementTpl()
  for _, v in pairs(achievement_list) do
    local tpl = achievementTpl:getTplById(v.achievementId)
    local achiLevel = achievementTpl:getAchiLevel(tpl)
    if v.version > 1 then
      for j = 1, v.version - 1 do
        local key = achiLevel - j
        if finishRate_dic[key] then
          finishRate_dic[key] = finishRate_dic[key] + 1
        else
          finishRate_dic[key] = 1
        end
      end
    end
    if self:getIsAchievementCompleted(v.achievementId) then
      if finishRate_dic[achiLevel] then
        finishRate_dic[achiLevel] = finishRate_dic[achiLevel] + 1
      else
        finishRate_dic[achiLevel] = 1
      end
    end
  end
  return finishRate_dic
end

return this
