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.dto.BaseUserDTO;
import com.github.wxiaoqi.security.admin.entity.User;
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.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;

/**
 * ${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;

    @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);
        return mapper.selectOne(user);
    }

    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 User getUserByUid(Integer userId){
        return mapper.selectByPrimaryKey(userId);
    }


    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);
    }
}
