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

import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.github.wxiaoqi.security.admin.dto.AccountBindDTO;
import com.github.wxiaoqi.security.admin.entity.AppUserDetail;
import com.github.wxiaoqi.security.admin.mapper.AppUserDetailMapper;
import com.github.wxiaoqi.security.admin.rpc.service.AppPermissionService;
import com.github.wxiaoqi.security.admin.vo.AppUserInfoVo;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 16:23
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class AppUserDetailBiz extends BaseBiz<AppUserDetailMapper, AppUserDetail> {

    @Override
    @CacheClear(pre = "user{1.userid}")
    public void updateSelectiveById(AppUserDetail entity) {
        super.updateSelectiveById(entity);
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param userid
     * @return
     */
    public AppUserDetail getUserByUserid(Integer userid) {
        Example example = new Example(AppUserDetail.class);
        example.createCriteria().andEqualTo("userid", userid).andEqualTo("isdel", 0);
        List<AppUserDetail> list = mapper.selectByExample(example);
        if (list != null && list.size() != 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据用户id获取父id
     *
     * @param code
     * @return
     */
    public Integer getUserByCode(String code) {
        Example example = new Example(AppUserDetail.class);
        example.createCriteria().andEqualTo("code", code).andEqualTo("isdel", 0);
        List<AppUserDetail> list = mapper.selectByExample(example);
        if (list != null && list.size() != 0) {
            return list.get(0).getUserid();
        }
        return 0;
    }

    /**
     * 获取用户信息
     *
     * @param userid
     * @return
     */
    @Cache(key = "user{1}")
    public AppUserVo getUserInfoById(Integer userid) {
        return mapper.getUserInfo(userid);
    }

    /**
     * 更新用户信息
     *
     * @param userVo
     */
    @CacheClear(pre = "user{1.userid}")
    public void updUuserInfoById(AppUserVo userVo) {
        AppUserDetail entity = new AppUserDetail();
        Example example = new Example(AppUserDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userid",userVo.getUserid());
        try {
            BeanUtils.copyProperties(entity, userVo);
            if (entity != null) {
                entity.setUpdHost(AppPermissionService.getIp());
                entity.setUpdatetime(Instant.now().toEpochMilli() / 1000L);
                mapper.updateByExampleSelective(entity,example);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    //更新用户信息
    public Map<Integer, AppUserDetail> findUserIdAndUserDetailMapByMemberIds(List<Integer> memberIds) {

        Map<Integer, AppUserDetail> userIdAndAppUserDetailMap = new HashMap<>();
        Example example = new Example(AppUserDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("userid", memberIds);
        List<AppUserDetail> appUserDetails = mapper.selectByExample(example);

        if (CollectionUtils.isNotEmpty(appUserDetails)) {
            userIdAndAppUserDetailMap = appUserDetails.stream().collect(Collectors.toMap(AppUserDetail::getUserid, Function.identity()));
        }
        return userIdAndAppUserDetailMap;
    }

    public void deleteByUserIds(Collection<Integer> userIds) {
        Example example = new Example(AppUserDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("userid", userIds);
        mapper.deleteByExample(example);
    }

    @CacheClear(pre = "user{1}")
    public void updateUserPositionByUserId(Integer userId, Integer positionId) {
        mapper.updateUserPositionByUserId(userId,positionId);
    }

    public AppUserInfoVo findUserInfoByCode(String code) {
        AppUserInfoVo appUserInfoVo = new AppUserInfoVo();

        AppUserDetail appUserDetail = new AppUserDetail();
        appUserDetail.setCode(code);
        AppUserDetail userDetail = mapper.selectOne(appUserDetail);

        if (userDetail==null){
            return appUserInfoVo;
        }
       appUserInfoVo.setHeadimgurl(userDetail.getHeadimgurl());
        appUserInfoVo.setNickname(userDetail.getNickname());
        return  appUserInfoVo;
    }

    public List<Integer> getUserIdByUsername(String keywords) {
        return mapper.getUserIdByUsername(keywords);
    }

    public void updateByUserId(AccountBindDTO accountBindDTO,Integer userId) {

        AppUserDetail appUserDetail = new AppUserDetail();
        if (accountBindDTO.getType().equals("wx")){
            appUserDetail.setWxNickname(accountBindDTO.getNickName());
        }
        if(accountBindDTO.getType().equals("q")){
            appUserDetail.setQqNickname(accountBindDTO.getNickName());
        }
        Example example = new Example(AppUserDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userid",userId);
        mapper.updateByExampleSelective(appUserDetail,example);
    }

    public List<AppUserVo> getUserByUserIds(List<Integer> ids) {
        return mapper.getUserVo(ids);
    }
}
