package com.github.wxiaoqi.security.admin.biz;

import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.admin.entity.AppUser;
import com.github.wxiaoqi.security.admin.entity.Group;
import com.github.wxiaoqi.security.admin.entity.User;
import com.github.wxiaoqi.security.admin.mapper.AppUserMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.Query;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.github.wxiaoqi.security.auth.common.constatns.CommonConstants.DATA_ALL_TRUE;

/**
 * @author keliii
 */
@Service
public class AppUserBiz extends BaseBiz<AppUserMapper, AppUser> {

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Cache(key="appUser{1}")
    public AppUser getUserByUsername(String username){
        AppUser user = new AppUser();
        user.setUsername(username);
        return mapper.selectOne(user);
    }

    public TableResultResponse<AppUser> selectPage(Query query, AppUser currentUser) {
        if(DATA_ALL_TRUE.equals(currentUser.getDataAll())) {
            return super.selectByQuery(query);
        }else {
            Example example = new Example(User.class);
            if(query.entrySet().size()>0) {
                Example.Criteria criteria = example.createCriteria();
                for (Map.Entry<String, Object> entry : query.entrySet()) {
                    criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                }
            }
            if(StringUtils.isNotBlank(currentUser.getDataCompany())){
                example.createCriteria().andIn("companyId", Arrays.asList(currentUser.getDataCompany().split(",")));
            }
            if(StringUtils.isNotBlank(currentUser.getDataZone())){
                example.createCriteria().andIn("zoneId", Arrays.asList(currentUser.getDataZone().split(",")));
            }
            Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
            List<AppUser> list = mapper.selectByExample(example);
            return new TableResultResponse<AppUser>(result.getTotal(), list);
        }
    }

    public List<Group> selectGroupsByAppUserId(Integer id) {
        return mapper.selectGroupsByAppUserId(id);
    }

    @Transactional
    public void insertAppUserGroup(Integer appUserId, Set<Integer> groups) {
        mapper.deleteAppUserGroup(appUserId);
        if (groups != null && groups.size() > 0) {
            mapper.insertAppUserGroup(appUserId, groups);
        }
    }
}
