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.User;
import com.github.wxiaoqi.security.admin.mapper.MenuMapper;
import com.github.wxiaoqi.security.admin.mapper.UserMapper;
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.TableResultResponse;
import com.github.wxiaoqi.security.common.util.Query;
import org.apache.commons.lang3.StringUtils;
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.Arrays;
import java.util.List;
import java.util.Map;

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;
    @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<User> selectPage(Query query, User currentUser) {
        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.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                }
            }
            example.createCriteria().andGreaterThan("id",1);
            Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
            List<User> list = mapper.selectByExample(example);
            return new TableResultResponse<User>(result.getTotal(), list);
        }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(",")));
            }
            example.createCriteria().andGreaterThan("id",1);
            Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
            List<User> list = mapper.selectByExample(example);
            return new TableResultResponse<User>(result.getTotal(), list);
        }
    }

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

    public User getUserByUid(Integer toUid){
        User user=mapper.getUserByUid(toUid);
        if(user!=null){
            user=mapper.selectByPrimaryKey(user.getId());
        }
        return user;
    }
}
