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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.dto.BaseUserDTO;
import com.github.wxiaoqi.security.admin.entity.User;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.admin.mapper.MenuMapper;
import com.github.wxiaoqi.security.admin.mapper.UserMapper;
import com.github.wxiaoqi.security.admin.vo.BaseUserVo;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.constant.UserConstant;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.vehicle.entity.CompanyInfo;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.CompanySearchDTO;
import com.xxfc.platform.vehicle.pojo.CompanySearchVO;
import com.xxfc.platform.vehicle.pojo.dto.CompanyInfoFindDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

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

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

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private UserAuthUtil userAuthUtil;


    @Autowired
    private VehicleFeign vehicleFeign;

    @Autowired
    private  GroupBiz groupBiz;

    @Autowired
    BranchCompanyBiz branchCompanyBiz;

    @Override
    public void insertSelective(User entity) {
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(entity.getPassword());
        entity.setPassword(password);
        super.insertSelective(entity);
    }

    @Override
    @CacheClear(pre="user{1.username}")
    @Transactional(rollbackFor = Exception.class)
    public void updateSelectiveById(User entity) {
        User user1= super.selectById(entity.getId());
        if(user1!=null&&StringUtils.isNotBlank(entity.getPassword())&&!user1.getPassword().equals(entity.getPassword())){
            String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(entity.getPassword());
            entity.setPassword(password);
        }
        super.updateSelectiveById(entity);
    }

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

//    /**
//     * 根据用户名获取用户信息
//     * @param userId
//     * @return
//     */
//    @Cache(key="user{1}")
//    public User getUserByUserId(Integer userId){
//        return mapper.selectByPrimaryKey(userId);
//    }

    public TableResultResponse<BaseUserVo> selectPage(Query query, User currentUser) {
        List<BaseUserVo> userVos=new ArrayList<>();
        List<User> list =new  ArrayList<>();
        Page<Object> result;
        if(DATA_ALL_TRUE.equals(currentUser.getDataAll())) {
            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.orLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                }
            }
            example.createCriteria().andGreaterThan("id",1);
            result = PageHelper.startPage(query.getPage(), query.getLimit());
            list = mapper.selectByExample(example);
        }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.orLike(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(",")));
            }
            if(StringUtils.isNotBlank(currentUser.getDataCorporation())){
                example.createCriteria().andIn("corporationId", Arrays.asList(currentUser.getDataCorporation().split(",")));
            }
            example.createCriteria().andGreaterThan("id",1);
            result = PageHelper.startPage(query.getPage(), query.getLimit());
             list = mapper.selectByExample(example);

            }
        if (list.size() > 0){
            List<User> list1 =list.stream().filter(x-> x.getCompanyId()==null || x.getCompanyId() == 0).collect(Collectors.toList());
            List<Long> corporationIds=list1.stream().map(User::getCorporationId).distinct().collect(Collectors.toList());
            CompanyInfoFindDTO companyInfoFindDTO=new CompanyInfoFindDTO();
            companyInfoFindDTO.setIds(corporationIds);
            ObjectRestResponse< List<CompanyInfo>> restResponse = vehicleFeign.listByIds(companyInfoFindDTO);
            Map<Long,CompanyInfo> companyInfoMaps=new HashMap<>();
            if (restResponse.getData() != null){
                List<CompanyInfo> companyInfos=restResponse.getData();
                if (companyInfos != null && companyInfos.size() > 0){
                    for (CompanyInfo companyInfo:companyInfos){
                        companyInfoMaps.put(companyInfo.getId(),companyInfo);
                    }
                }
            }

            List<Integer> companyIds=list.stream().map(User::getCompanyId).distinct().collect(Collectors.toList());
            CompanySearchDTO companySearchDTO=new CompanySearchDTO();
            companySearchDTO.setCompanyIds(companyIds);
            ObjectRestResponse<List<CompanySearchVO>> restResponse1= vehicleFeign.listByIds(companySearchDTO);
            Map<Integer,CompanySearchVO> companyMaps=new HashMap<>();
            if (restResponse1.getData() != null){
                List<CompanySearchVO> companySearchVOS=restResponse1.getData();
                if (companySearchVOS != null && companySearchVOS.size() > 0){
                    for (CompanySearchVO companySearchVO:companySearchVOS){
                        companyMaps.put(companySearchVO.getId(),companySearchVO);
                    }
                }
            }

            for (User user : list){
                BaseUserVo userVo=new BaseUserVo();
                BeanUtils.copyProperties(user,userVo);
                CompanyInfo companyInfo=companyInfoMaps.get(userVo.getCorporationId());
                if (companyInfo != null ){
                    userVo.setCorporationName(companyInfo.getName());
                }
                CompanySearchVO companySearchVO= companyMaps.get(userVo.getCompanyId());
                if (companySearchVO != null ){
                    userVo.setCompanyName(companySearchVO.getName());
                    userVo.setCorporationName(companySearchVO.getCompanyName());
                }
                userVo.setGroupList(groupBiz.getUserGroups(userVo.getId()));
                userVos.add(userVo);
            }
        }
        return new TableResultResponse<BaseUserVo>(result.getTotal(), userVos);
    }

    public List<User> getCountByUsername(String username){
        User user = new User();
        user.setUsername(username);
        return mapper.select(user);
    }

    public List<User> getCountByUsernameBiz(String username, Integer bizType, String mobilePhone){
//        User user = new User();
//        user.setUsername(username);
//        user.setBizType(bizType);
//        user.setStatus(SYS_TRUE);
//        user.setIsDel(SYS_FALSE);
        //        return mapper.select(user);
        return selectByWeekend(w -> {
            w.andEqualTo(User::getUsername, username);
            w.andEqualTo(User::getBizType, bizType);
            w.andEqualTo(User::getIsDel, SYS_FALSE);
            w.andEqualTo(User::getStatus, SYS_TRUE);
            if(StrUtil.isNotBlank(mobilePhone)) {
                w.andEqualTo(User::getMobilePhone, mobilePhone);
            }
            return w;
        });
    }

    public User getUserByUid(Integer userId){
        return mapper.selectByPrimaryKey(userId);
    }

    public User getUserByAppUserId(Integer appUserId){
        User user = new User();
        user.setAppUserId(appUserId);
        List<User> select = mapper.select(user);
        if (select.size() > 0){
            return  select.get(0);
        }
        return null;
    }


    public  ObjectRestResponse userinfoByAppUserIdV2(Integer appUserId){
        User user = getUserByAppUserId(appUserId);
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        if (user.getDataCorporation() != null){
            com.github.wxiaoqi.security.admin.dto.CompanySearchDTO companySearchDTO =new com.github.wxiaoqi.security.admin.dto.CompanySearchDTO();
            companySearchDTO.setDataCorporationIds(Arrays.asList(user.getDataCorporation().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList()));
            List<com.github.wxiaoqi.security.admin.vo.CompanySearchVO> companySearchVOList=branchCompanyBiz.getList(companySearchDTO);
            if(companySearchVOList != null && companySearchVOList.size() > 0){
                List<Integer> companyIds = companySearchVOList.stream().map(com.github.wxiaoqi.security.admin.vo.CompanySearchVO::getId).distinct().collect(Collectors.toList());
                user.setCompanyIds(companyIds);
            }
        }else if (user.getDataCompany() != null ){
            List<Integer> companyIds = Arrays.asList(user.getDataCompany().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            user.setCompanyIds(companyIds);
        }
        return new ObjectRestResponse<User>().rel(true).data(user);
    }

    public ObjectRestResponse<User> userinfoByMobilePhone(String mobilePhone){
        User user = selectOne(new User(){{
            setMobilePhone(mobilePhone);
            setIsDel(SYS_FALSE);
            setStatus(SYS_TRUE);
        }});
        if (user == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.USER_NOTEXIST_CODE, ResultCode.getMsg(ResultCode.USER_NOTEXIST_CODE));
        }
        if (user.getDataCorporation() != null){
            com.github.wxiaoqi.security.admin.dto.CompanySearchDTO companySearchDTO =new com.github.wxiaoqi.security.admin.dto.CompanySearchDTO();
            companySearchDTO.setDataCorporationIds(Arrays.asList(user.getDataCorporation().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList()));
            List<com.github.wxiaoqi.security.admin.vo.CompanySearchVO> companySearchVOList=branchCompanyBiz.getList(companySearchDTO);
            if(companySearchVOList != null && companySearchVOList.size() > 0){
                List<Integer> companyIds = companySearchVOList.stream().map(com.github.wxiaoqi.security.admin.vo.CompanySearchVO::getId).distinct().collect(Collectors.toList());
                user.setCompanyIds(companyIds);
            }
        }else if (user.getDataCompany() != null ){
            List<Integer> companyIds = Arrays.asList(user.getDataCompany().split(",")).parallelStream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            user.setCompanyIds(companyIds);
        }
        return new ObjectRestResponse<User>().rel(true).data(user);
    }

    public List<BaseUserVo> getList(BaseUserDTO baseUserDTO){
        return  mapper.selectList(baseUserDTO);
    }
    public ObjectRestResponse selectList(BaseUserDTO baseUserDTO){
        Integer page=baseUserDTO.getPage()==null?1:baseUserDTO.getPage();
        Integer limit=baseUserDTO.getLimit()==null?10:baseUserDTO.getLimit();
        PageDataVO<BaseUserVo> dataVO= PageDataVO.pageInfo(page, limit, ()->getList(baseUserDTO));
        List<BaseUserVo> list=dataVO.getData();
        if (list != null && list.size() > 0){
            for (BaseUserVo baseUserVo:list){
                baseUserVo.setGroupList(groupBiz.getUserGroups(baseUserVo.getId()));
            }
        }
        return  ObjectRestResponse.succ(dataVO);
    }
}
