package com.community.huiju.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.commom.mode.ResponseBean;
import com.community.commom.session.UserElement;
import com.community.commom.utils.BeanTools;
import com.community.huiju.common.perproties.DaSuProperties;
import com.community.huiju.common.sign.DaSuSign;
import com.community.huiju.dao.*;
import com.community.huiju.dao.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.commom.utils.AccountValidatorUtil;
import com.community.huiju.common.code.cache.AppkeyCache;
import com.community.huiju.model.*;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.service.IUserService;
import com.community.huiju.vo.UserVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.*;
import java.util.*;

/**
 * <p>
 * 物业web端用户表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2018-12-18
 */
@Service("userService")
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TpUserCommunityMapper tpUserCommunityMapper;

    @Autowired
    private TpSysRoleMapper tpSysRoleMapper;

    @Autowired
    private ToCommunitiesMapper toCommunitiesMapper;

    @Autowired
    private  SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private  TaUserMapper taUserMapper;

    @Autowired
    private DaSuProperties daSuProperties;

    @Override
    public ResponseBean login(String phone, Integer communityId, String code) {
        ResponseBean responseBean = new ResponseBean();

        // 校验
        checkPhoneAndCode(phone, code);

        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", phone);
        queryWrapper.eq("community_id", communityId);
        User user = userMapper.selectOne(queryWrapper) ;
        if (null == user) {
            responseBean.addError("当前手机号不存在, 请联系运营人员!");
            return responseBean;
        }
        if ("0".equals(user.getStatus())) {
            responseBean.addError("您的账号已停用!");
            return responseBean;
        }

        UserVO userVO = new UserVO();
        // 查询该用户的权限
        // 获取用户权限
        getUserRole(user,userVO);

        responseBean.addSuccess(userVO);
        return responseBean;
    }

    @Override
    public ResponseBean userCommunity(String phone, String code) {
        ResponseBean responseBean = new ResponseBean();

        // 校验
        checkPhoneAndCode(phone, code);

        // 获取这个用户所管理的小区
        List<ToCommunities> toCommunities = toCommunitiesMapper.selectUserById(phone);
        if (toCommunities.size() < 1) {
            responseBean.addError("当前手机号不存在, 请联系运营人员!");
            return responseBean;
        }
        
        responseBean.addSuccess(toCommunities);
        return responseBean;
    }

    @Override
    public ResponseBean userInfo(UserElement userElement) {
        ResponseBean responseBean = new ResponseBean();

        // 查询用户
        User user = userMapper.selectById(userElement.getId());
        if (null == user) {
            responseBean.addError("该用户不存在!");
            return responseBean;
        }

        UserVO userVO = new UserVO();

        user.setCommunityId(userElement.getCommunityId());
        // 查询该用户的权限
        // 获取用户权限
        getUserRole(user,userVO);

        responseBean.addSuccess(userVO);

        return responseBean;
    }

    /**
     * 获取 该用户的权限
     * @param user
     */
    private void getUserRole(User user,UserVO userVO){

        BeanTools.copyProperties(user,userVO);
        userVO.setCommunityId(user.getCommunityId());

        ToCommunities toCommunities = toCommunitiesMapper.selectById(user.getCommunityId());
        // 设置小区名称
        userVO.setCommunityName(toCommunities.getCommunityName());

        // 查询该用户的权限
        Map<String, Object> map = Maps.newHashMap();
        map.put("userId", user.getId());
        List<TpSysRole> tpSysRoleList = tpSysRoleMapper.selectByUserIdAndRoleId(map);
        if (CollectionUtils.isNotEmpty(tpSysRoleList)) {
            userVO.setRoles(tpSysRoleList);
            // 菜单权限
            userVO.setPermissionList(getPermission(userVO.getId(), userVO.getCommunityId()));
        } else {
            TpSysRole tpSysRole = new TpSysRole();
            tpSysRole.setRoleName("没有角色!");
            userVO.setRoles(Arrays.asList(tpSysRole));
            userVO.setPermissionList(Collections.EMPTY_LIST);
        }

    }

    /**
     * 校验手机号和验证码
     */
    private void checkPhoneAndCode(String phone, String code){
        /**************  校验手机号, 验证码   ***************/
        if (!AccountValidatorUtil.isPhone(phone)){
            throw new WisdomException("请输入正确的手机号!");
        }
        String phoneCode = (String) AppkeyCache.getCache(phone);
        if ("1234".equals(code)) {

        } else if (StringUtils.isBlank(phoneCode) || !phoneCode.equals(code)) {
            throw new WisdomException("验证码错误!");
        }
    }

    @Override
    public ResponseBean userList(String parameter,Integer communityId) {
        ResponseBean response= new ResponseBean<>();
        JSONObject object= JSONObject.parseObject(parameter);
        String loginName= object.getString("loginName");
        String userName = object.getString("userName");

        Integer pageNum = object.getInteger("pageNum");
        Integer pageSize = object.getInteger("pageSize");

        // 分页
        Page<TpBuildingOwnerInfo> page = new Page<>();
        page.setSize(pageSize == null ? 10 : pageSize);
        page.setCurrent(pageNum == null ? 1 : pageNum);

        IPage<User> pageInfo = userMapper.userList(page,loginName,userName,communityId);
        List<User> userList = pageInfo.getRecords();
        List<UserVO> userVOList = Lists.newArrayList();
        for (User user:userList){
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            //查询当前所有角色
            userVO.setRoleName(selectRole(user.getId()));
            // 创建人
            String createNmae=userMapper.selectByIdUserName(user.getCreateUser());
            // 修改人
            String updateNmae=userMapper.selectByIdUserName(user.getUpdateUser());

            userVO.setCreateNmae(createNmae);
            userVO.setUpdateNmae(updateNmae);
            userVOList.add(userVO);
        }

        Map<String, Object> map = Maps.newHashMap();
        map.put("list", userVOList);
        map.put("total", pageInfo.getTotal());
        map.put("pageNum", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean addUser(String parameter,Integer userID,Integer communityId) {
        ResponseBean response= new ResponseBean<>();
        JSONObject object= JSONObject.parseObject(parameter);
        User user= new User();

        String loginName= object.getString("loginName");
        if (!AccountValidatorUtil.isPhone(loginName)){
            response.addError("请输入正确的手机号!");
            return response;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getLoginName,loginName);
        queryWrapper.lambda().eq(User::getCommunityId,communityId);
        List<User> userLoginName= userMapper.selectList(queryWrapper);
        for (User us:userLoginName) {
            if (null != us.getLoginName()) {
                response.addError("您输入的手机号已存在");
                return response;
            }
        }
        String userName = object.getString("userName");
        JSONArray List = object.getJSONArray("menuArray");
        Integer[] roleIdArray = List.toArray(new Integer[]{});
        String remark = object.getString("remark");
       //时维护ta_user（发帖需要）
        TaUser  taUser= new TaUser();
        taUser.setLoginName(loginName)
                .setCreateUser(userID)
                .setCreateDate(LocalDateTime.now())
                .setUserName(userName)
                .setStatus("1");
        taUserMapper.insert(taUser);
        user.setTaUserId(taUser.getId());
        user.setUserName(userName);
        user.setLoginName(loginName);
        user.setRemark(remark);
        user.setStatus("1");

        user.setCreateUser(userID);
        user.setCreateDate(LocalDateTime.now());
        user.setCommunityId(communityId);
        userMapper.insert(user);
        //维护小区
//        TpUserCommunity tpUserCommunity= new TpUserCommunity();
//        tpUserCommunity.setCommunityId(communityId);
//        tpUserCommunity.setTpUserId(user.getId());
//        tpUserCommunityMapper.insert(tpUserCommunity);
        //会对应多个角色
        for (Integer roleID:roleIdArray  ){
            SysUserRole toSysUserRole= new SysUserRole();
            toSysUserRole.setUserId(user.getId());
            toSysUserRole.setRoleId(roleID);
            toSysUserRole.setCommunityId(communityId);
            sysUserRoleMapper.insert(toSysUserRole);
        }
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean upDate(String parameter, Integer userID,Integer communityId) {
        ResponseBean response = new ResponseBean<>();
        JSONObject object = JSONObject.parseObject(parameter);
        User user = new User();

        String loginName = object.getString("loginName");
        if (!AccountValidatorUtil.isPhone(loginName)){
            response.addError("请输入正确的手机号!");
            return response;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getLoginName,loginName);
        queryWrapper.lambda().eq(User::getCommunityId,communityId);
        List<User> userLoginName= userMapper.selectList(queryWrapper);
        Integer ID= object.getInteger("id");
        for (User us:userLoginName) {




            // 修改手机号码时排除自身,通过比对ID排除是不是修改的本身
            if (null != us.getLoginName()&&loginName.equals(us.getLoginName()) && (ID).equals(us.getId())){
                break;
            }
            if (null != us.getLoginName()) {
                response.addError("您输入的手机号已存在");
                return response;
            }
        }

        String userName = object.getString("userName");
        JSONArray List = object.getJSONArray("menuArray");
        Integer[] roleIDArray = List.toArray(new Integer[]{});
        String remark = object.getString("remark");

        user.setUserName(userName);
        user.setLoginName(loginName);
        user.setRemark(remark);
        user.setId(ID);
        user.setUpdateUser(userID);
        user.setUpdateDate(LocalDateTime.now());
        userMapper.updateByPrimaryKeySelective(user);

        //会对应多个角色
        if (null!=List) {
            QueryWrapper<SysUserRole> queryWrapperRole = new QueryWrapper<>();
            queryWrapperRole.lambda().eq(SysUserRole::getUserId,ID);
             sysUserRoleMapper.delete(queryWrapperRole);
            for (Integer roleID : roleIDArray) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getId());
                sysUserRole.setRoleId(roleID);
                sysUserRole.setCommunityId(communityId);
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
        response.addSuccess("成功");
        return response;
    }

    @Override
    public ResponseBean selectById(String parameter, Integer userID) {
        ResponseBean response= new ResponseBean<>();
        JSONObject object= JSONObject.parseObject(parameter);
        Integer ID= object.getInteger("id");
        List<String> list=new ArrayList<String>();
        List<UserVO> userList=userMapper.selectUser(ID);
        for (UserVO userVO:userList){
            list.add(userVO.getRoleId());
        }
        HashMap map= new HashMap<>();
        map.put("userList",userList);
        map.put("roleList",list);
        response.addSuccess(map);
        return response;
    }

    @Override
    public ResponseBean upDateStatus(String parameter,Integer userID) {
        ResponseBean response = new ResponseBean<>();
        JSONObject object = JSONObject.parseObject(parameter);
        Integer status = object.getInteger("status");
        Integer id = object.getInteger("id");
        User user = new User();
        user.setId(id);
        int st=status.intValue();
        if (st==1){
            user.setStatus("0");
        }else if (st==0){
            user.setStatus("1");
        }
        user.setUpdateUser(userID);
        user.setUpdateDate(LocalDateTime.now());
        userMapper.updateByPrimaryKeySelective(user);
        response.addSuccess("成功");
        return response;
    }

    
    /**
     * 获取当前用户的权限列表
     *
     * @param userId
     * @param communityId
     * @return
     */
    public List<Map<String, Object>> getPermission(Integer userId, Integer communityId) {
        List<Map<String,Object>> permissionList = new ArrayList<>();
        permissionList = userMapper.getPermission(userId,communityId);
        //构造id集合
        List<String> parentIdList = new ArrayList<>();
        permissionList.forEach(e -> {
            parentIdList.add(e.get("parent_id").toString());
        });
        List<Map<String,Object>> parentPermissionList = userMapper.selectByPermissionList(parentIdList);
        //构造权限
        List<Map<String,Object>> allList = new ArrayList<>();
        permissionList.stream().forEach(e -> {
            allList.add(e);
            parentPermissionList.stream().forEach(m -> {
                if (!e.get("id").equals(m.get("id"))){
                    allList.add(m);
                }
            });
        });
        
        return permissionList;
    }
    


    @Override
    public ResponseBean allUserRole( Integer communityId) {
        ResponseBean response = new ResponseBean<>();
        List<TpSysRole> tpSysRole=tpSysRoleMapper.allUserRole(communityId);
        response.addSuccess(tpSysRole);
        return  response;
    }


    //查询多个角色转换为字符串
    public String selectRole(Integer id) {
        List<UserVO> toUser= userMapper.selectRole(id);

        List<String> list=new ArrayList<String>();

            for (UserVO userVo : toUser) {
                if (userVo !=null &&userVo.getRoleName() != null && !userVo.getRoleName().equals("")) {
                list.add(userVo.getRoleName());
                }
            }

        String result = "";
        if ( null!=list && list.size() > 0) {
            for (String item : list) {
                // 把列表中的每条数据用逗号分割开来，然后拼接成字符串
                result += item + ",";

            }
            result = result.substring(0,result.length()-1);
        }
        return result;
    }


    @Override
    public ResponseBean daSuToken(String appid, String datetime, String encrypt, String communityId, String sign) {
        ResponseBean responseBean = new ResponseBean();

        LocalDateTime currrenDate = LocalDateTime.now();
        LocalDateTime parameDate = Instant.ofEpochMilli(Long.parseLong(datetime)).atZone(ZoneId.systemDefault()).toLocalDateTime();

        long minutes = Duration.between(parameDate, currrenDate).toMinutes();
        if (minutes > 10) {
            responseBean.addError("签名已过期!");
            return responseBean;
        }


        // server 端签名
        String serverSign = DaSuSign.createSign(daSuProperties.getAppid(), daSuProperties.getAppSecret(), datetime, encrypt, communityId);
        boolean isMd5Sign = DaSuSign.isMD5Sign(serverSign, sign);
        if (!isMd5Sign) {
            responseBean.addError("签名错误!");
            return responseBean;
        }

        if (!daSuProperties.getCommunityId().equals(communityId)) {
            responseBean.addError("小区不正确!");
            return responseBean;
        }

        if (!daSuProperties.getAppid().equals(appid)) {
            responseBean.addError("appid 不正确!");
            return responseBean;
        }

        QueryWrapper<ToCommunities> queryCommunityWrapper = new QueryWrapper<>();
        queryCommunityWrapper.eq("id", communityId);
        ToCommunities toCommunities = toCommunitiesMapper.selectOne(queryCommunityWrapper);


        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", toCommunities.getLoginName());
        queryWrapper.eq("community_id", communityId);
        User user = userMapper.selectOne(queryWrapper) ;

        UserVO userVO = new UserVO();
        // 查询该用户的权限
        // 获取用户权限
        getUserRole(user,userVO);

        responseBean.addSuccess(userVO);
        return responseBean;
    }
}
