/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ifish.helper;

import com.ifish.API.GwellApi;
import com.ifish.API.Mail;
import com.ifish.API.SendMobile;
import com.ifish.bean.Tbl_Device;
import com.ifish.bean.Tbl_Device_User;
import com.ifish.bean.Tbl_HardWare_Type;
import com.ifish.bean.Tbl_User;
import com.ifish.bean.Tbl_Vender;
import com.ifish.enums.GwellEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.enums.SendTypeEnum;
import com.ifish.enums.SmsSignEnum;
import com.ifish.enums.SmsTemplateEnum;
import com.ifish.mapper.Tbl_User_Mapper;
import com.ifish.util.IfishUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author Administrator
 */
@Component
public class UserHelper implements UserHelperI {

    /**
     * redis缓存服务器方法接口
     */
    @Autowired
    private RedisHelperI redisHelperI;

    /**
     * 所有tbl_user表的操作方法接口
     */
    @Autowired
    private Tbl_User_Mapper tbl_User_Mapper;

    @Autowired
    private DeviceHelperI deviceHelperI;

    @Autowired
    private HardWareTypeHelperI hardWareTypeHelperI;

    @Autowired
    private RedisKeyHelperI redisKeyHelperI;

    @Autowired
    private SendMobile sendMobile;

    @Autowired
    private FastDFSClientI fastDFSClientI;

    /**
     * 登陆接口
     *
     * @param user
     * @return
     */
    @Override
    public Object login(Tbl_User user) {
        try {
            Tbl_User tmpUser = null;
            //如果用户手机不为空，进行手机登陆
            if (StringUtils.isNotBlank(user.getPhoneNumber())) {
                tmpUser = tbl_User_Mapper.getUserByPhoneNumber(user.getPhoneNumber());
                return checkUserPassword(tmpUser, user);
            } //如果用户邮箱不为空，进行邮箱登陆
            else if (StringUtils.isNotBlank(user.getUserEmail())) {
                tmpUser = tbl_User_Mapper.getUserByUserEmail(user.getPhoneNumber());
                return checkUserPassword(tmpUser, user);
            } //如果用户手机邮箱都为空，用户ID不为空，则进行游客登陆
            else if (user.getUserId() != null && user.getUserId() > 0) {
                tmpUser = getUserById(user.getUserId());
                return touristLogin(tmpUser);
            } else if (StringUtils.isNotBlank(user.getToken())) {
                tmpUser = getTbl_UserByToken(user.getToken());
                if (tmpUser != null) {
                    return touristLogin(tmpUser);
                } else {
                    return touristRegister();
                }
            }
            //密码不正确
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 手机验证成功后用户注册
     *
     * @param user
     * @return
     */
    @Override
    public Object registerUserMobile(Tbl_User user) {
        if (StringUtils.isBlank(user.getPhoneNumber()) || user.getUserId() > 0) {
            return IfishUtil.returnJson(ResultEnum.error401.getKey(), "");
        }
        //随机生成6位用户名
        user.setNickName("鱼友" + IfishUtil.getCharAndNumr(5));
        user.setIsRegisterGwell("0");
        user.setUserType("1");
        Date date = new Date();
        user.setCreateTime(date);
        user.setUserImg("http://139.196.24.156:83/00/00/" + (new Random().nextInt(7) + 1) + ".png");
        user.setUpdateTime(date);
        int i = tbl_User_Mapper.insertUserByPhoneNumberAndEmail(user);
        Map dataMap = new HashMap();
        if (i > 0) {

            //注册技威
            //4.1未注册技威，则注册获取code1，code2
            Map gwellMap = registUserGWell(user, false);
            user = (Tbl_User) gwellMap.get("user");
            if (StringUtils.isNotBlank(user.getP2pverifyCode1()) && StringUtils.isNotBlank(user.getP2pverifyCode2()) && StringUtils.isNotBlank(user.getGwellUserid())) {
                dataMap.put("P2PVerifyCode1", user.getP2pverifyCode1());
                dataMap.put("P2PVerifyCode2", user.getP2pverifyCode2());
                dataMap.put("gwellUserID", user.getGwellUserid());
                tbl_User_Mapper.updateUser(user);
            }
        } else {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
        //返回给App的数据
        dataMap.put("userId", user.getUserId());
        dataMap.put("phoneNumber", user.getPhoneNumber());
        dataMap.put("userSex", user.getUserSex());
        dataMap.put("userImg", user.getUserImg());
        dataMap.put("nickName", user.getNickName());

        return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
    }

    /**
     * 邮箱用户发送注册链接
     */
    @Override
    public Object registerByEmail(Tbl_User user) {
        try {
            if (StringUtils.isBlank(user.getUserEmail()) || StringUtils.isBlank(user.getUserPassword())) {
                return IfishUtil.returnJson(ResultEnum.error401.getKey(), "");
            } else {
                String md5 = IfishUtil.EncoderByMd5(user.getUserEmail() + user.getUserPassword());
                Map map = new HashMap();
                map.put("email", user.getUserEmail());
                map.put("password", user.getUserPassword());
                if (StringUtils.isNotBlank(user.getToken())) {
                    map.put("token", user.getToken());
                }
                String key = redisKeyHelperI.getEmailRedisKey(md5);
                redisHelperI.setRedis(key, IfishUtil.ObjectToJson(map), 30, TimeUnit.MINUTES);
                Mail.sendRegisterCodeTest(user.getUserEmail(), md5);
                return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
            }
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 添加邮箱用户
     *
     * @param md5
     * @return
     */
    @Override
    public String registerEmail(String md5) {
        String key = redisKeyHelperI.getEmailRedisKey(md5);
        String redisString = redisHelperI.getRedis(key);
        if (StringUtils.isBlank(redisString)) {
            return "链接超时，请重新注册！";
        } else {
            Map map = (Map) IfishUtil.JsonToRealMap(redisString);
            Tbl_User user = new Tbl_User();
            user.setUserEmail(map.get("email").toString());
            user.setUserPassword(map.get("password").toString());
            if (map.get("token") != null && StringUtils.isNotBlank(map.get("token").toString())) {
                user.setToken(map.get("token").toString());
            }
            //随机生成6位用户名
            user.setNickName("鱼友" + IfishUtil.getCharAndNumr(5));
            user.setIsRegisterGwell("0");
            user.setUserType("1");
            Date date = new Date();
            user.setCreateTime(date);
            user.setUserImg("http://139.196.24.156:83/00/00/" + (new Random().nextInt(7) + 1) + ".png");
            user.setUpdateTime(date);
            int i = tbl_User_Mapper.insertUserByPhoneNumberAndEmail(user);
            if (i > 0) {
                try {
                    //注册技威
                    //4.1未注册技威，则注册获取code1，code2
                    Map gwellMap = registUserGWell(user, false);
                    user = (Tbl_User) gwellMap.get("user");
                    tbl_User_Mapper.updateUser(user);
                } catch (Exception e) {
                }
                return "注册成功，请用邮箱和密码进行登陆！";
            }
        }
        return "注册失败，请联系管理员！";
    }

//    /**
//     * 根据类型和手机号，发送验证码
//     *
//     * @param sendType
//     * @param phoneNumber
//     * @return
//     */
//    @Override
//
//    public Object getSecurityCodeByPhoneNumber(String sendType, String phoneNumber) {
//        Tbl_User user = getUserByPhoneNumber(phoneNumber);
//        if (sendType.equals(SendTypeEnum.register.getKey())) {
//            if (user != null) {
//                //手机号注册过，发送错误码
//                return IfishUtil.returnJson(ResultEnum.warn201.getKey(), "");
//            } else {
//                //手机未被注册，获取验证码
//                return sendSecurityCode(phoneNumber, SmsSignEnum.sign4.getValue(), SmsTemplateEnum.SMS_720018.getKey());
//            }
//        } //找回密码
//        else if (sendType.equals(SendTypeEnum.findpwd.getKey())) {
//            if (user != null) {
//                //手机号存在，获取验证码
//                return sendSecurityCode(phoneNumber, SmsSignEnum.sign5.getValue(), SmsTemplateEnum.SMS_720021.getKey());
//            } else {
//                //手机号不存在，发送错误码
//                return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
//            }
//        } else {
//            //未知操作，返回错误码
//            return IfishUtil.returnJson(ResultEnum.warn203.getKey(), "");
//        }
//    }
//    /**
//     * 根据类型和邮件地址，发送验证码
//     *
//     * @param sendType
//     * @param phoneNumber
//     * @return
//     */
//    @Override
//    public Object getSecurityCodeByEmail(String sendType, String Email) {
//        Tbl_User user = getUserByEmail(Email);
//        if (sendType.equals(SendTypeEnum.register.getKey())) {
//            if (user != null) {
//                //邮箱注册过，发送错误码
//                return IfishUtil.returnJson(ResultEnum.warn201.getKey(), "");
//            } else {
//                //邮箱未被注册，获取验证码
////                String code = Mail.sendRegisterCodeTest(Email);
////                if (StringUtils.isNotBlank(code)) {
////                    return IfishUtil.returnJson(ResultEnum.success.getKey(),"");
////                }
//            }
//        } //找回密码
//        else if (sendType.equals(SendTypeEnum.findpwd.getKey())) {
//            if (user != null) {
//                //手机号存在，获取验证码
//                String code = Mail.sendRegisterCode(Email);
//                return IfishUtil.returnJson(ResultEnum.success.getKey(), code.toString());
//            } else {
//                //手机号不存在，发送错误码
//                return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
//            }
//        } else {
//            //未知操作，返回错误码
//            return IfishUtil.returnJson(ResultEnum.warn203.getKey(), "");
//        }
//        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
//    }
    /**
     * 根据用户ID从缓存中获取用户对象
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public Tbl_User getUserById(Integer userId) throws Exception {
        Tbl_User tmpUser = null;
        String userKey = redisKeyHelperI.getTbl_UserRedisKeyByUserId(userId);
        String userString = redisHelperI.getRedis(userKey);
        //1.从数据库或缓存中读取用户对象
        if (StringUtils.isNotBlank(userString)) {
            tmpUser = (Tbl_User) IfishUtil.JsonToBean(userString, Tbl_User.class);
        } else {
            tmpUser = tbl_User_Mapper.getUserByUserId(userId + "");
            if (tmpUser != null && tmpUser.getUserId() > 0) {
                redisHelperI.setRedis(userKey, IfishUtil.ObjectToJson(tmpUser));
            }
        }
        return tmpUser;
    }

    /**
     * 游客注册接口
     *
     * @return
     */
    @Override
    public Object touristRegister() {
        Tbl_User user = new Tbl_User();
        user.setUserType("0");
        int i = tbl_User_Mapper.insertUserByTourist(user);
        Map result = new HashMap();
        if (i > 0 && user.getUserId() > 0) {
            //4.1未注册技威，则注册获取code1，code2
            Map gwellMap = registUserGWell(user, false);
            user = (Tbl_User) gwellMap.get("user");
            if (StringUtils.isBlank(user.getP2pverifyCode1()) || StringUtils.isBlank(user.getP2pverifyCode2()) || StringUtils.isBlank(user.getGwellUserid())) {
                return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
            }
            Integer updateInteger = tbl_User_Mapper.updateUser(user);
            //如果修改失败，返回错误信息
            if (updateInteger <= 0) {
                return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
            }
            result.put("userId", user.getUserId());
            result.put("P2PVerifyCode1", user.getP2pverifyCode1());
            result.put("P2PVerifyCode2", user.getP2pverifyCode2());
            result.put("gwellUserID", user.getGwellUserid());
            return IfishUtil.returnJson(ResultEnum.success.getKey(), result);
        } else {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    @Override
    public Object updateUser(Tbl_User user) {
        try {
            //用户ID
            Integer userId = user.getUserId();
            if (userId != null) {
                //查找用户信息
                Tbl_User curUser = getUserById(userId);
                if (curUser != null) {
                    //是否需要更新
                    boolean bln = false;
                    //昵称
                    String nickName = user.getNickName();
                    if (StringUtils.isNotBlank(nickName)) {
                        //敏感词过滤
                        if (nickName.contains("爱鱼奇") || nickName.contains("官方")) {
                            return IfishUtil.returnJson(ResultEnum.warn203.getKey(), "");
                        } else {
                            curUser.setNickName(nickName);
                            bln = true;
                        }
                    }
                    //性别
                    String userSex = user.getUserSex();
                    if (StringUtils.isNotBlank(userSex)) {
                        curUser.setUserSex(userSex);
                        bln = true;
                    }

                    //有参数变更
                    if (bln) {
                        //更新用户信息
                        curUser.setUpdateTime(new Date());
                        tbl_User_Mapper.updateUser(user);
                        redisKeyHelperI.deleteRedisByTbl_User(user);
                    }
                    Map userMap = getUserMap(user);
                    return IfishUtil.returnJson(ResultEnum.success.getKey(), userMap);
                } else {
                    return IfishUtil.returnJson(ResultEnum.warn211.getKey(), "");
                }
            } else {
                return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
            }
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 修改用户头像
     *
     * @param file
     * @param userId
     * @return
     */
    @Override
    public Object updateUserImg(MultipartFile file, Integer userId, String path) {
        try {
            if (file.isEmpty() && StringUtils.isBlank(path)) {
                return IfishUtil.returnJson(ResultEnum.warn205.getKey(), "");
            }
            String img = "";
            if (file.isEmpty()) {
                img = path;
            } else {
                img = fastDFSClientI.uploadFileToFastDFS(file);
                if (StringUtils.isBlank(img)) {
                    return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
                }
            }

            Tbl_User user = getUserById(userId);
            user.setUserImg(img);
            int i = tbl_User_Mapper.updateUser(user);
            if (i > 0) {
                redisKeyHelperI.deleteRedisByTbl_User(user);
                Map userMap = getUserMap(user);
                return IfishUtil.returnJson(ResultEnum.success.getKey(), userMap);
            }
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 根据手机号从缓存或数据库中取得用户对象
     *
     * @param phoneNumber
     * @param email
     * @return
     */
    public Tbl_User getUserByPhoneNumber(String phoneNumber) {
        Tbl_User tmpUser = null;
        try {
            String userKey = redisKeyHelperI.getTbl_UserRedisKeyByPhoneNumber(phoneNumber);
            String userString = redisHelperI.getRedis(userKey);
            //1.从数据库或缓存中读取用户对象
            if (StringUtils.isNotBlank(userString)) {
                tmpUser = (Tbl_User) IfishUtil.JsonToBean(userString, Tbl_User.class);
            } else {
                tmpUser = tbl_User_Mapper.getUserByPhoneNumber(phoneNumber);
                if (tmpUser != null && tmpUser.getUserId() > 0) {
                    redisHelperI.setRedis(userKey, IfishUtil.ObjectToJson(tmpUser));
                }
            }
        } catch (Exception e) {
        }
        return tmpUser;
    }

    /**
     * 根据邮箱从缓存或数据库中取得用户对象
     *
     * @param email
     * @return
     */
    public Tbl_User getUserByEmail(String email) {
        Tbl_User tmpUser = null;
        try {
            String userKey = redisKeyHelperI.getTbl_UserRedisKeyByEmail(email);
            String userString = redisHelperI.getRedis(userKey);
            //1.从数据库或缓存中读取用户对象
            if (StringUtils.isNotBlank(userString)) {
                tmpUser = (Tbl_User) IfishUtil.JsonToBean(userString, Tbl_User.class);
            } else {
                tmpUser = tbl_User_Mapper.getUserByUserEmail(email);
                if (tmpUser != null && tmpUser.getUserId() > 0) {
                    redisHelperI.setRedis(userKey, IfishUtil.ObjectToJson(tmpUser));
                }
            }
        } catch (Exception e) {
        }
        return tmpUser;
    }

    /**
     * 根据token从缓存或数据库中取得用户对象
     *
     * @param token
     * @return
     */
    public Tbl_User getTbl_UserByToken(String token) {
        Tbl_User tmpUser = null;
        try {
            String userKey = redisKeyHelperI.getTbl_UserRedisKeyByToken(token);
            String userString = redisHelperI.getRedis(userKey);
            //1.从数据库或缓存中读取用户对象
            if (StringUtils.isNotBlank(userString)) {
                tmpUser = (Tbl_User) IfishUtil.JsonToBean(userString, Tbl_User.class);
            } else {
                tmpUser = tbl_User_Mapper.getUserByUserToken(token);
                if (tmpUser != null && tmpUser.getUserId() > 0) {
                    redisHelperI.setRedis(userKey, IfishUtil.ObjectToJson(tmpUser));
                }
            }
        } catch (Exception e) {
        }
        return tmpUser;
    }

    /**
     * 邮箱和手机登陆用户，需要进行密码验证，游客登陆不需要
     *
     * @param tmpUser
     * @param user
     * @return
     * @throws Exception
     */
    private Object checkUserPassword(Tbl_User tmpUser, Tbl_User user) throws Exception {
        //2.如果都为空，则没有此用户，返回未注册信息
        if (tmpUser == null) {
            //用户不存在
            return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
        }
        //3.验证密码是否正确
        if (tmpUser.getUserPassword().equals(user.getUserPassword())) {
            //4.如果密码正确，确认是否更新用户信息

            //是否更新
            boolean isUpdate = false;

            //4.1未注册技威，则注册获取code1，code2
            Map gwellMap = registUserGWell(tmpUser, isUpdate);
            tmpUser = (Tbl_User) gwellMap.get("user");
            isUpdate = (Boolean) gwellMap.get("isUpdate");

            //4.3登陆次数修改
            Integer logincount = tbl_User_Mapper.executeLoginUpdate(tmpUser.getUserId(), user.getLoginType());
            //修改失败，返回错误信息
            if (logincount <= 0) {
                return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
            }
            //4.4验证是否需要修改技威等信息，如果需要则进行修改
            if (isUpdate) {
                Integer updateInteger = tbl_User_Mapper.updateUser(tmpUser);
                //如果修改失败，返回错误信息
                if (updateInteger <= 0) {
                    return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
                }
                redisKeyHelperI.deleteRedisByTbl_User(tmpUser);
            }

            //4.5 获取用户数据
            Map userMap = getUserMap(tmpUser);
            //4.8获取用户绑定设备信息和摄像头信息
            Map deviceMap = getDeviceList(tmpUser);
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("user", userMap);
            dataMap.put("device", deviceMap.get("list"));
            dataMap.put("camera", deviceMap.get("list2"));
            return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
        } else {
            //密码不正确
            return IfishUtil.returnJson(ResultEnum.warn204.getKey(), "");
        }
    }

    /**
     * 游客登陆接口
     *
     * @param tmpUser
     * @return
     * @throws Exception
     */
    private Object touristLogin(Tbl_User tmpUser) throws Exception {
        //2.如果为空，则没有此用户，返回未注册信息
        if (tmpUser == null) {
            //用户不存在
            return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
        }

        //是否更新
        boolean isUpdate = false;

        //4.1未注册技威，则注册获取code1，code2
        Map gwellMap = registUserGWell(tmpUser, isUpdate);
        tmpUser = (Tbl_User) gwellMap.get("user");
        isUpdate = (Boolean) gwellMap.get("isUpdate");

        //4.4验证是否需要修改技威等信息，如果需要则进行修改
        if (isUpdate) {
            Integer updateInteger = tbl_User_Mapper.updateUser(tmpUser);
            //如果修改失败，返回错误信息
            if (updateInteger <= 0) {
                return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
            }
            redisKeyHelperI.deleteRedisByTbl_User(tmpUser);
        }

        //4.5 获取用户数据
        Map userMap = getUserMap(tmpUser);
        //4.8获取用户绑定设备信息和摄像头信息
        Map deviceMap = getDeviceList(tmpUser);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("user", userMap);
        dataMap.put("device", deviceMap.get("list"));
        dataMap.put("camera", deviceMap.get("list2"));
        return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);

    }

    /**
     * 未注册技威，则注册获取code1，code2
     *
     * @param tmpUser
     * @param isUpdate
     * @return
     */
    private Map registUserGWell(Tbl_User tmpUser, boolean isUpdate) {
        //4.1未注册技威，则注册获取code1，code2
        if (StringUtils.isBlank(tmpUser.getIsRegisterGwell()) || tmpUser.getIsRegisterGwell().equals("0")) {
            String code = "";
            //如果有手机用手机号注册，否则用用户ID注册
            if (StringUtils.isBlank(tmpUser.getPhoneNumber())) {
                code = tmpUser.getUserId() + "";
            } else if (StringUtils.isNotBlank(tmpUser.getPhoneNumber())) {
                code = tmpUser.getPhoneNumber();
            } else if (StringUtils.isNotBlank(tmpUser.getUserEmail())) {
                code = tmpUser.getUserEmail().replace(".com", "").replace(".cn", "");
            }
            //注册技威
            Map<String, String> map = GwellApi.Register(code);
            String result = map.get("result");
            if (result != null) {
                //注册成功
                if (result.equals(GwellEnum.success.getKey())) {
                    String P2PVerifyCode1 = map.get("P2PVerifyCode1");
                    String P2PVerifyCode2 = map.get("P2PVerifyCode2");
                    String gwellUserID = map.get("UserID");
                    tmpUser.setIsRegisterGwell("1");
                    tmpUser.setP2pverifyCode1(P2PVerifyCode1);
                    tmpUser.setP2pverifyCode2(P2PVerifyCode2);
                    tmpUser.setGwellUserid(gwellUserID);
                    isUpdate = true;
                } //已经注册过
                else if (GwellEnum.repeat.getKey().equals(result)) {
                    tmpUser.setIsRegisterGwell("1");
                    isUpdate = true;
                }
            }
        }//已经注册过技威
        else if (tmpUser.getIsRegisterGwell().equals("1")) {
            //code1和code2为空则重新登陆获取
            String P2PVerifyCode1 = tmpUser.getP2pverifyCode1();
            String P2PVerifyCode2 = tmpUser.getP2pverifyCode2();
            String gwellUserID = tmpUser.getGwellUserid();
            if (P2PVerifyCode1.equals("") || P2PVerifyCode2.equals("") || gwellUserID.equals("")) {
                Map<String, String> map = GwellApi.Login(tmpUser.getPhoneNumber());
                String result = map.get("result");
                //登陆成功
                if (result != null && result.equals(GwellEnum.success.getKey())) {
                    P2PVerifyCode1 = map.get("P2PVerifyCode1");
                    P2PVerifyCode2 = map.get("P2PVerifyCode2");
                    gwellUserID = map.get("UserID");
                    tmpUser.setP2pverifyCode1(P2PVerifyCode1);
                    tmpUser.setP2pverifyCode2(P2PVerifyCode2);
                    tmpUser.setGwellUserid(gwellUserID);
                    isUpdate = true;
                }
            }
        }
        Map resultMap = new HashMap();
        resultMap.put("user", tmpUser);
        resultMap.put("isUpdate", isUpdate);
        return resultMap;
    }

    /**
     * 登录成功,返回给App数据
     *
     * @param tmpUser
     * @return
     */
    private Map getUserMap(Tbl_User tmpUser) {
        //登录成功,返回给App数据
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("userId", tmpUser.getUserId().toString());
        //如果手机号不为空
        if (StringUtils.isNotBlank(tmpUser.getPhoneNumber())) {
            userMap.put("phoneNumber", tmpUser.getPhoneNumber());
        }
        //如果邮箱不为空
        if (StringUtils.isNotBlank(tmpUser.getUserEmail())) {
            userMap.put("userEmail", tmpUser.getUserEmail());
        }
        userMap.put("nickName", tmpUser.getNickName());
        userMap.put("userSex", tmpUser.getUserSex());
        userMap.put("userImg", tmpUser.getUserImg());
        userMap.put("P2PVerifyCode1", tmpUser.getP2pverifyCode1());
        userMap.put("P2PVerifyCode2", tmpUser.getP2pverifyCode2());
        userMap.put("gwellUserID", tmpUser.getGwellUserid());
        //userMap.put("userType", tmpUser.getUserType());
        if (tmpUser.getUpdateTime() != null) {
            userMap.put("updateTime", IfishUtil.format(tmpUser.getUpdateTime()));
        }

        return userMap;
    }

    /**
     * 获取用户绑定设备信息
     *
     * @param tmpUser
     * @return
     */
    private Map getDeviceList(Tbl_User tmpUser) throws Exception {
        //设备信息
        List<Object> list = new ArrayList<Object>();
        //摄像头信息
        List<Object> list2 = new ArrayList<Object>();
        //获取用户拥有设备
        List<Tbl_Device_User> deviceUserList = deviceHelperI.getDeviceUsersByUserId(tmpUser.getUserId());
        List<Integer> deviceIds = new ArrayList<Integer>();
        List<Integer> cameraIds = new ArrayList<Integer>();
        for (Tbl_Device_User deviceUser : deviceUserList) {
            Tbl_Device device = deviceHelperI.getDeviceById(deviceUser.getDeviceId());
            if (device.getIsCamera().equals("1")) {
                cameraIds.add(device.getDeviceId());
                list2.add(getCameraInfo(device, deviceUser));
            } else {
                deviceIds.add(device.getDeviceId());
                //封装设备返回信息
                list.add(getDeviceInfo(device, deviceUser));
            }

        }

        Map map = new HashMap();
        map.put("list", list);
        map.put("list2", list2);
        return map;
    }

    /**
     * 封装设备返回信息
     *
     * @param device
     * @param deviceUser
     * @return
     */
    @Override
    public Map<String, Object> getDeviceInfo(Tbl_Device device, Tbl_Device_User deviceUser) throws Exception {
        Map<String, Object> deviceMap = new HashMap<String, Object>();
        deviceMap.put("userId", deviceUser.getUserId());
        deviceMap.put("deviceId", deviceUser.getDeviceId());
        deviceMap.put("isMaster", deviceUser.getIsMaster());
        deviceMap.put("showName", deviceUser.getShowName());
        deviceMap.put("macAddress", device.getMacAddress());
        deviceMap.put("isBlacklist", device.getIsBlacklist());
        deviceMap.put("customIconName", deviceUser.getCustomIconName());
        deviceMap.put("customShowName", deviceUser.getCustomShowName());
        deviceMap.put("deviceIp", device.getDeviceIp());
        deviceMap.put("loginTime", device.getLoginTime());
        if (device.getBrandCode() != null && device.getBrandCode().equals("YUEM") && device.getCreateTime().before(IfishUtil.StrToDate("2016-04-26"))) {
            //是否显示预警推送
            deviceMap.put("isPushWendu", "0");
        } else {
            //是否显示预警推送
            deviceMap.put("isPushWendu", "1");
        }
        //控制方案
        String type = device.getHardwareType();
        if (type != null) {
            Tbl_HardWare_Type hardwareType = hardWareTypeHelperI.getHardwareTypeByTypeCode(type);
            if (hardwareType != null) {
                //设备类型
                deviceMap.put("type", type);
                //有无工作模式
                deviceMap.put("isWorkModel", hardwareType.getIsWorkModel());
                //控制信息
                deviceMap.put("controlAmount", hardwareType.getControlAmount());
                deviceMap.put("timerAmount", hardwareType.getTimerAmount());
                //背光/柜灯
                deviceMap.put("isLightness", hardwareType.getIsLightness());
                deviceMap.put("isSarkLamp", hardwareType.getIsSarkLamp());
                //自定义图标
                deviceMap.put("isCustomIcon", hardwareType.getIsCustomIcon());
                deviceMap.put("iconLink", hardwareType.getIconLink());
                deviceMap.put("allIconName", hardwareType.getAllIconName());
                deviceMap.put("allShowName", hardwareType.getAllShowName());
                deviceMap.put("defaultIconName", hardwareType.getDefaultIconName());
                deviceMap.put("defaultShowName", hardwareType.getDefaultShowName());
                deviceMap.put("updateTime", hardwareType.getUpdateTime());
                //换水提醒
                deviceMap.put("todayRemind", device.getTodayRemind());
                deviceMap.put("waterRemind", device.getWaterRemind());
                deviceMap.put("remindDate", device.getRemindDate() != null ? IfishUtil.format1(device.getRemindDate()) : "");
                deviceMap.put("remindCycle", device.getRemindCycle() != null ? device.getRemindCycle() : "");
            }
        }
        //厂家
        if (device.getBrandCode() != null) {
            //厂家
            Tbl_Vender venderList = new Tbl_Vender();
            venderList = hardWareTypeHelperI.getVenderListByBrandCode(device.getBrandCode());
            deviceMap.put("venderList", venderList);
        } else {
            //默认爱鱼奇
            Tbl_Vender defaultVenderList = new Tbl_Vender();
            defaultVenderList = hardWareTypeHelperI.getVenderListByBrandCode("AYQ");
            deviceMap.put("venderList", defaultVenderList);
        }
        return deviceMap;
    }

    /**
     * 封装摄像头返回信息
     *
     * @param camera
     * @param cameraUser
     * @param device
     * @param deviceUser
     * @return
     */
    public Map<String, Object> getCameraInfo(Tbl_Device camera, Tbl_Device_User cameraUser) {
        Map<String, Object> cameraMap = new HashMap<String, Object>();
        cameraMap.put("cameraId", camera.getDeviceId());
        cameraMap.put("isMaster", cameraUser.getIsMaster());
        cameraMap.put("isLook", cameraUser.getIsLook());
        cameraMap.put("isActive", StringUtils.isNotBlank(camera.getActiveCode()) ? "1" : "0");
        cameraMap.put("showName", cameraUser.getShowName());
        return cameraMap;
    }

    /**
     * 发送手机验证码
     *
     * @param phoneNumber
     * @param smsSign
     * @param smsTemplate
     * @return
     */
    public Object sendSecurityCode(String phoneNumber, String smsSign, String smsTemplate) {
        Integer code = (int) (Math.random() * 9000 + 1000);
        boolean bln = sendMobile.sendSmsNum(phoneNumber, code.toString(), smsSign, smsTemplate);
        //发送验证码
        if (bln) {
            return IfishUtil.returnJson(ResultEnum.success.getKey(), code.toString());
        } else {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

}
