local this = {}

function this:req_getHistory(callback)
  L_Net:sendMessage(MsgGenCode.CSProtoGachaList, nil, function(rspData, errorCode)
    local historys = rspData.historys
    if historys then
      self:rsp_syncHistoryList(historys)
    end
    if callback then
      callback()
    end
  end)
end

function this:req_raffle(poolId, times, callback)
  local data = {
    pool_id = poolId,
    single = times == 1
  }
  L_Net:sendMessage(MsgGenCode.CSProtoGachaBuy, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      local rewards = rspData.rewards
      if rewards then
        self:rsp_syncResultList(rewards)
      end
      if callback then
        callback()
      end
    end
  end)
end

function this:req_raffleChoose(chooseData, callback)
  local data = {
    pool_id = chooseData.pool_id,
    choose_type = chooseData.choose_type,
    choose_id = chooseData.choose_id
  }
  L_Net:sendMessage(MsgGenCode.CSProtoGachaChoose, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:rsp_syncHistoryList(data)
  self.data.historyList = {}
  for i = 1, #data do
    local history = require(L_R.store .. "raffle.data.historyitem").new()
    history.propId = data[i].item_id
    history.propType = data[i].item_type
    history.propNum = data[i].item_num
    history.cardPoolId = data[i].pool_id
    history.time = data[i].time
    table.insert(self.data.historyList, history)
  end
  table.sort(self.data.historyList, function(a, b)
    return a.time > b.time
  end)
end

function this:rsp_syncGachaPoolInfo(data)
  for i, v in pairs(data) do
    local cardPool = self:getCardPool(v.pool_id, true)
    cardPool.pool_id = v.pool_id
    cardPool.last_time = v.last_time
    cardPool.day_count = v.day_count
    cardPool.total_count = v.total_count
    cardPool.choose_id = v.choose_id
    cardPool.choose_type = v.choose_type
    cardPool.choose_num = v.choose_num
  end
  self:call(self.event.refreshCardPoolList)
end

function this:rsp_syncResultList(data)
  self.data.resultList = {}
  self.data.curCardIndex = 0
  for i, v in pairs(data) do
    local mainRewards = v.mainRewards.rewards
    local result = require(L_R.store .. "raffle.data.resultitem").new()
    result.mainPropId = mainRewards[1].itemid
    result.mainPropType = mainRewards[1].itemtype
    result.mainPropNum = mainRewards[1].itemnum
    result.attachRewards = {}
    local attachRewards = v.attachRewards and v.attachRewards.rewards or {}
    for i1, v1 in pairs(attachRewards or {}) do
      table.insert(result.attachRewards, {
        type = v1.itemtype,
        id = v1.itemid,
        num = v1.itemnum
      })
    end
    table.insert(self.data.resultList, result)
  end
end

return this
