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.bo.UserBo;
import com.github.wxiaoqi.security.admin.bo.UserStaffBo;
import com.github.wxiaoqi.security.admin.dto.AccountBindDTO;
import com.github.wxiaoqi.security.admin.dto.StaffStatisticsFindDTO;
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 com.github.wxiaoqi.security.common.vo.PageDataVO;
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.*;
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);
    }

    public List<UserStaffBo> findAllStaffs() {
        List<UserStaffBo> userStaffBos = mapper.selectAllStaffs();
        return CollectionUtils.isEmpty(userStaffBos)? Collections.EMPTY_LIST:userStaffBos;
    }

    public List<AppUserVo> getUserByUserIdList(List<Integer> userIds) {
          List<AppUserVo> appUserVos =  mapper.getUserByUserIdList(userIds);
        return CollectionUtils.isEmpty(appUserVos)?Collections.EMPTY_LIST:appUserVos;
    }

    public PageDataVO<UserStaffBo> findAllStaffsByCompanyIdAndPostionIdWithPage(StaffStatisticsFindDTO staffStatisticsFindDTO) {
       return PageDataVO.pageInfo(staffStatisticsFindDTO.getPage(),staffStatisticsFindDTO.getLimit(),()->mapper.findAllStaffsByCompanyIdAndPostionId(staffStatisticsFindDTO));
    }

    public List<UserStaffBo> findStaffsByIdsAndCompanyAndPostion(StaffStatisticsFindDTO staffStatisticsFindDTO) {
        List<UserStaffBo> staffBos = mapper.findAllStaffsByCompanyIdAndPostionId(staffStatisticsFindDTO);
        return CollectionUtils.isEmpty(staffBos)?Collections.EMPTY_LIST:staffBos;
    }

    public AppUserVo findByCode(String code) {
        AppUserVo appUserVo = new AppUserVo();
        AppUserDetail appUserDetail = new AppUserDetail();
        appUserDetail.setCode(code);
        appUserDetail = mapper.selectOne(appUserDetail);
        org.springframework.beans.BeanUtils.copyProperties(appUserDetail,appUserVo);
        return appUserVo;
    }

    public AppUserVo getUser(Integer userId) {

        return mapper.getUser(userId);
    }

    public List<UserBo> findUserBosByPhones(List<String> phones) {
        List<UserBo> userBoList = mapper.findUserBosByPhones(phones);
        return CollectionUtils.isEmpty(userBoList)?Collections.emptyList():userBoList;
    }


    /**
     * 判断员工是否是APP用户
     *
     * @return
     */
    public AppUserDetail checkeIsAppUser(Integer userid) {
        Example example = new Example(AppUserDetail.class);
        example.createCriteria().andEqualTo("userid", userid);
        List<AppUserDetail> appUserDetailList = mapper.selectByExample(example);
        if (appUserDetailList != null && appUserDetailList.size() != 0) {
            return appUserDetailList.get(0);
        }
        return null;
    }

    public List<AppUserDetail> findAllUsers() {
        Example example = new Example(AppUserDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isdel",0);
        List<AppUserDetail> userDetails = mapper.selectByExample(example);
        return CollectionUtils.isEmpty(userDetails)?Collections.emptyList():userDetails;
    }

    public List<AppUserDetail> findAllUserDetailWithNoProinceCode() {
        List<AppUserDetail> appUserDetails = mapper.selectAllWithNoProviinceCode();
        return CollectionUtils.isEmpty(appUserDetails)?Collections.EMPTY_LIST:appUserDetails;
    }

    public List<UserBo> findUserDetailByUserIds(List<Integer> userIds) {
        List<UserBo> userBoList  = mapper.selectUserByUserIds(userIds);
        return CollectionUtils.isEmpty(userBoList)?Collections.EMPTY_LIST:userBoList;
    }
}
