local module = class("moduleWardrobeColorSelect", G_UIModuleBase)
local _AvatarTpl = L_GameTpl:getWardrobeAvatarTpl()
local _ColorTpl = L_GameTpl:getWardrobeColorTpl()
local _WardrobeTpl = L_GameTpl:getWardrobeTpl()

function module.bind()
  return {
    colorText = "",
    colorList = {
      moduleName = "pages/MOD/Module/modColorSelectItem"
    }
  }
end

function module.methods()
  return {
    colorList = {
      selectColor = function(self, colorId)
        L_ModStore:selectModColorId(self.bind.wardrobeType, self.bind.colorIndex, colorId)
        for i = 1, #self.bind.colorList do
          local value = self.bind.colorList:getValue(i)
          self.bind.colorList:change(i, {
            isSelect = value.colorId == colorId
          })
        end
        L_ModStore:setIsChanged(true)
      end
    }
  }
end

function module:refreshUI()
  local avatarId = L_ModStore:getTempAvatarWardrobe(self.bind.wardrobeType)
  local modTpl = _AvatarTpl:getTplById(avatarId)
  local allColorList = _AvatarTpl:getColorId(modTpl)[self.bind.colorIndex]
  local isFindSelect = false
  local tmp = {}
  for i, v in pairs(allColorList or {}) do
    local colorId = allColorList[i]
    local colorTpl = _ColorTpl:getTplById(colorId)
    local isSelectColorId = L_ModStore:isTempSelectColor(self.bind.wardrobeType, self.bind.colorIndex, colorId)
    isFindSelect = isFindSelect or isSelectColorId
    table.insert(tmp, {
      colorId = colorId,
      colorValue = _ColorTpl:getIconColor(colorTpl),
      colorName = _ColorTpl:getName(colorTpl),
      isSelect = isSelectColorId
    })
  end
  if table.isEmpty(tmp) then
    table.insert(tmp, {
      colorValue = "#FFFFFF",
      colorName = L_WordsTpl:getValue("ui_moduleQuickRoulette"),
      colorId = -1,
      isSelect = not isFindSelect
    })
  end
  table.sort(tmp, function(a, b)
    return a.colorId < b.colorId
  end)
  if not isFindSelect and self.bind.wardrobeType == L_ModStore.modType.eye then
    for i = 1, #tmp do
      if self.bind.colorList[i] and self.bind.colorList[i].isSelect then
        tmp[i].isSelect = true
        L_ModStore:selectModColorId(L_ModStore.modType.eye, self.bind.colorIndex, tmp[i].colorId)
        break
      end
    end
  end
  self.bind.colorList:clear()
  self.bind.colorList:insert_array(tmp)
end

function module:open()
  self:refreshUI()
end

return module
