/*
 * 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.bean.DeviceUserBean;
import com.ifish.entity.Camera;
import com.ifish.entity.CameraUser;
import com.ifish.entity.Device;
import com.ifish.entity.DeviceCamera;
import com.ifish.entity.HardwareType;
import com.ifish.entity.ShopsInfo;
import com.ifish.entity.User;
import com.ifish.entity.VenderList;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.GwellEnum;
import com.ifish.enums.NeteaseEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.enums.SubDirectoryEnum;
import com.ifish.gwell.GwellApi;
import com.ifish.mapper.Tbl_User_Mapper;
import com.ifish.netease.NeteaseIM;
import com.ifish.util.IfishFilePath;
import com.ifish.util.IfishUtil;
import com.ifish.util.RedisKey;
import com.ifish.util.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户管理所有接口方法
 *
 * @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 NeteaseIM neteaseIM;

    @Autowired
    private DeviceUserHelperI deviceUserHelperI;

    @Autowired
    private ShopsInfoHelperI shopsInfoHelperI;

    @Autowired
    private HardWareVenderHelperI hardWareVenderHelperI;

    @Autowired
    private CameraUserHelperI cameraUserHelperI;

    /**
     * 登陆接口
     *
     * @param user
     * @return
     */
    @Override
    public Object login(User user) {
        try {
            User tmpUser = tmpUser = tbl_User_Mapper.getUserByPhoneNumber(user.getPhoneNumber());
            //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 = (User) gwellMap.get("user");
                isUpdate = (boolean) gwellMap.get("isUpdate");

                //4.2未注册云信，则注册云信，获取云信token
                Map imMap = registUserNetease(tmpUser, isUpdate);
                tmpUser = (User) imMap.get("user");
                isUpdate = (boolean) imMap.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(), "");
                    }
                    saveUserToRedis(tmpUser);
                }

                //4.5 获取用户数据
                Map userMap = getUserMap(tmpUser);
                //4.6自己的商家对象
                Map shopsInfoMap = getShopInfoMap(tmpUser);
                //4.7选择的看护商家对象
                Map kanhuShopsInfoMap = getKanhuShopInfoMap(tmpUser);
                //4.8获取用户绑定设备信息，设备和摄像头信息
                Map deviceMap = getDeviceList(tmpUser);
                //4.9获取用户绑定摄像头信息
                List<Object> list2 = getCameraList(tmpUser);
                Map<String, Object> dataMap = new HashMap<String, Object>();
                dataMap.put("user", userMap);
                dataMap.put("shopsInfo", shopsInfoMap);
                dataMap.put("shopsInfo2", kanhuShopsInfoMap);
                dataMap.put("device", deviceMap.get("list"));
                dataMap.put("camera", list2);
                dataMap.put("deviceCamera", deviceMap.get("list3"));
                return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
            } else {
                //密码不正确
                return IfishUtil.returnJson(ResultEnum.warn204.getKey(), "");
            }
        } catch (Exception e) {
            return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
        }
    }

    /**
     * 根据用户ID从缓存中获取用户对象
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public User getUserById(Integer userId) throws Exception {
        User tmpUser = null;
        String userKey = RedisKey.User_Key + userId;
        String userString = redisHelperI.getRedis(userKey);
        //1.从数据库或缓存中读取用户对象
        if (StringUtils.isNotBlank(userString)) {
            tmpUser = (User) StringUtil.JsonToBean(userString, User.class);
        } else {
            tmpUser = tbl_User_Mapper.getUserByUserId(userId + "");
            saveUserToRedis(tmpUser);
        }
        return tmpUser;
    }

    /**
     * 未注册技威，则注册获取code1，code2
     *
     * @param tmpUser
     * @param isUpdate
     * @return
     */
    private Map registUserGWell(User tmpUser, boolean isUpdate) {
        //4.1未注册技威，则注册获取code1，code2
        if (tmpUser.getIsRegisterGwell().equals(BooleanEnum.NO.getKey())) {
            //注册技威
            Map<String, String> map = GwellApi.Register(tmpUser.getPhoneNumber());
            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(BooleanEnum.YES.getKey());
                    tmpUser.setP2PVerifyCode1(P2PVerifyCode1);
                    tmpUser.setP2PVerifyCode2(P2PVerifyCode2);
                    tmpUser.setGwellUserID(gwellUserID);
                    isUpdate = true;
                } //已经注册过
                else if (GwellEnum.repeat.getKey().equals(result)) {
                    tmpUser.setIsRegisterGwell(BooleanEnum.YES.getKey());
                    isUpdate = true;
                }
            }
        }//已经注册过技威
        else if (tmpUser.getIsRegisterGwell().equals(BooleanEnum.YES.getKey())) {
            //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;
    }

    /**
     * 未注册云信，则注册云信，获取云信token
     *
     * @param tmpUser
     * @param isUpdate
     * @return
     */
    private Map registUserNetease(User tmpUser, boolean isUpdate) throws Exception {
        if (tmpUser.getIsRegisterNetease().equals(BooleanEnum.NO.getKey())) {
            //注册云信
            Map<String, String> map = neteaseIM.createAccid(tmpUser.getUserId().toString(), tmpUser.getNickName(), IfishFilePath.getPath(SubDirectoryEnum.headImage, tmpUser.getUserImg()), "");
            if (map != null) {
                String code = map.get("code");
                if (code.equals(NeteaseEnum.status200.getKey())) {
                    tmpUser.setIsRegisterNetease(BooleanEnum.YES.getKey());
                    tmpUser.setNeteaseToken(map.get("token"));
                    isUpdate = true;
                    //发送云信消息
                    User imUser = getNeteaseIMUser();
                    if (imUser != null) {
                        neteaseIM.sendMsg(imUser.getUserId().toString(), tmpUser.getUserId().toString(), "感谢您使用爱鱼奇，连接智能设备请查看下方说明书，内含操作视频：http://u.eqxiu.com/s/KmmVl87l \n摄像头售后：021-54131006\n睿芯插排售后：15757401229\n绚多插排售后：18857689069\n松诺插排售后：13392205468", "");
                    }
                } else if (code.equals(NeteaseEnum.status414.getKey())) {
                    tmpUser.setIsRegisterNetease(BooleanEnum.YES.getKey());
                    isUpdate = true;
                }
            }
        } //已注册云信
        else if (tmpUser.getIsRegisterNetease().equals(BooleanEnum.YES.getKey())) {
            //token为空
            if (tmpUser.getNeteaseToken().equals("")) {
                //获取云信token
                Map<String, String> map = neteaseIM.refreshToken(tmpUser.getUserId().toString());
                if (map != null) {
                    String code = map.get("code");
                    if (code.equals(NeteaseEnum.status200.getKey())) {
                        tmpUser.setNeteaseToken(map.get("token"));
                        isUpdate = true;
                    }
                }
            }
        }
        Map resultMap = new HashMap();
        resultMap.put("user", tmpUser);
        resultMap.put("isUpdate", isUpdate);
        return resultMap;
    }

    /**
     * 登录成功,返回给App数据
     *
     * @param tmpUser
     * @return
     */
    private Map getUserMap(User tmpUser) {
        //登录成功,返回给App数据
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("userId", tmpUser.getUserId().toString());
        userMap.put("phoneNumber", tmpUser.getPhoneNumber());
        userMap.put("nickName", tmpUser.getNickName());
        userMap.put("userSex", tmpUser.getUserSex());
        userMap.put("signature", tmpUser.getSignature());
        userMap.put("userImg", tmpUser.getUserImg());
        userMap.put("P2PVerifyCode1", tmpUser.getP2PVerifyCode1());
        userMap.put("P2PVerifyCode2", tmpUser.getP2PVerifyCode2());
        userMap.put("gwellUserID", tmpUser.getGwellUserID());
        userMap.put("neteaseToken", tmpUser.getNeteaseToken());
        userMap.put("userType", tmpUser.getUserType());
        userMap.put("shopsUserId", tmpUser.getShopsUserId());
        if (tmpUser.getUpdateTime() != null) {
            userMap.put("updateTime", IfishUtil.format(tmpUser.getUpdateTime()));
        }

        return userMap;
    }

    /**
     * 自己的商家对象
     *
     * @param tmpUser
     * @return
     */
    private Map getShopInfoMap(User tmpUser) throws Exception {
        Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
        if (tmpUser.getUserId() != null) {
            ShopsInfo shopsInfo = shopsInfoHelperI.getShopsInfoByUserId(tmpUser.getUserId());
            if (shopsInfo != null) {
                shopsInfoMap.put("shopsId", shopsInfo.getShopsId());
                shopsInfoMap.put("userId", shopsInfo.getUserId());
                shopsInfoMap.put("userImg", tmpUser.getUserImg());
                shopsInfoMap.put("userName", shopsInfo.getUserName());
                shopsInfoMap.put("shopsName", shopsInfo.getShopsName());
                shopsInfoMap.put("shopsPhone", shopsInfo.getShopsPhone());
                shopsInfoMap.put("shopsProvince", shopsInfo.getShopsProvince());
                shopsInfoMap.put("shopsCity", shopsInfo.getShopsCity());
                shopsInfoMap.put("shopsArea", shopsInfo.getShopsArea());
                shopsInfoMap.put("shopsAddress", shopsInfo.getShopsAddress());
                shopsInfoMap.put("picture1", shopsInfo.getPicture1());
                shopsInfoMap.put("picture2", shopsInfo.getPicture2());
                shopsInfoMap.put("picture3", shopsInfo.getPicture3());
                shopsInfoMap.put("picture4", shopsInfo.getPicture4());
                shopsInfoMap.put("status", shopsInfo.getStatus());
                shopsInfoMap.put("reason", shopsInfo.getReason());
            }
        }
        return shopsInfoMap;
    }

    /**
     * 选择的看护商家对象
     *
     * @param tmpUser
     * @return
     */
    private Map getKanhuShopInfoMap(User tmpUser) throws Exception {
        //选择的看护商家对象
        Map<String, Object> shopsInfo2Map = new HashMap<String, Object>();
        if (tmpUser.getShopsUserId() != null && tmpUser.getShopsUserId() > 0) {
            ShopsInfo shopsInfo = shopsInfoHelperI.getShopsInfoByUserId(tmpUser.getShopsUserId());
            if (shopsInfo != null) {
                User tmp2User = getUserById(tmpUser.getShopsUserId());
                shopsInfo2Map.put("shopsId", shopsInfo.getShopsId());
                shopsInfo2Map.put("userId", shopsInfo.getUserId());
                shopsInfo2Map.put("userImg", tmp2User.getUserImg());
                shopsInfo2Map.put("userName", shopsInfo.getUserName());
                shopsInfo2Map.put("shopsName", shopsInfo.getShopsName());
                shopsInfo2Map.put("shopsPhone", shopsInfo.getShopsPhone());
                shopsInfo2Map.put("shopsProvince", shopsInfo.getShopsProvince());
                shopsInfo2Map.put("shopsCity", shopsInfo.getShopsCity());
                shopsInfo2Map.put("shopsArea", shopsInfo.getShopsArea());
                shopsInfo2Map.put("shopsAddress", shopsInfo.getShopsAddress());
                shopsInfo2Map.put("picture1", shopsInfo.getPicture1());
                shopsInfo2Map.put("picture2", shopsInfo.getPicture2());
                shopsInfo2Map.put("picture3", shopsInfo.getPicture3());
                shopsInfo2Map.put("picture4", shopsInfo.getPicture4());
                shopsInfo2Map.put("status", shopsInfo.getStatus());
                shopsInfo2Map.put("reason", shopsInfo.getReason());
            }
        }
        return shopsInfo2Map;
    }

    /**
     * 获取用户绑定设备信息
     *
     * @param tmpUser
     * @return
     */
    private Map getDeviceList(User tmpUser) throws Exception {
        //设备信息
        List<Object> list = new ArrayList<Object>();
        //获取用户拥有设备
        List<DeviceUserBean> deviceUserList = deviceUserHelperI.getDeviceUsersByUserId(tmpUser.getUserId());
        List<Integer> deviceIds = new ArrayList<Integer>();
        for (DeviceUserBean deviceUser : deviceUserList) {
            Device device = deviceUserHelperI.getDeviceById(deviceUser.getDeviceId());
            deviceIds.add(device.getDeviceId());
            //封装设备返回信息
            list.add(getDeviceInfo(device, deviceUser));
        }

        //设备-摄像头
        List<Object> list3 = new ArrayList<Object>();
        //设备已关联摄像头
        if (deviceIds.size() > 0) {
            for (Integer deviceId : deviceIds) {
                List<DeviceCamera> deviceCameraList = deviceUserHelperI.getDeviceCameraListByDeviceId(deviceId);
                for (DeviceCamera deviceCamera : deviceCameraList) {
                    Map<String, Object> deviceCameraMap = new HashMap<String, Object>();
                    deviceCameraMap.put("cameraId", deviceCamera.getDeviceCameraId().getCameraId());
                    deviceCameraMap.put("deviceId", deviceCamera.getDeviceCameraId().getDeviceId());
                    list3.add(deviceCameraMap);
                }
            }
        }
        Map map = new HashMap();
        map.put("list", list);
        map.put("list3", list3);
        return map;
    }

    /**
     * 封装设备返回信息
     *
     * @param device
     * @param deviceUser
     * @return
     */
    public Map<String, Object> getDeviceInfo(Device device, DeviceUserBean 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", BooleanEnum.NO.getKey());
        } else {
            //是否显示预警推送
            deviceMap.put("isPushWendu", BooleanEnum.YES.getKey());
        }
        //控制方案
        String type = device.getHardwareType();
        if (type != null) {
            HardwareType hardwareType = hardWareVenderHelperI.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) {
            //厂家
            VenderList venderList = new VenderList();
            venderList = hardWareVenderHelperI.getVenderListByBrandCode(device.getBrandCode());
            deviceMap.put("venderList", venderList);
        } else {
            //默认爱鱼奇
            VenderList defaultVenderList = new VenderList();
            defaultVenderList = hardWareVenderHelperI.getVenderListByBrandCode("AYQ");
            deviceMap.put("venderList", defaultVenderList);
        }
        return deviceMap;
    }

    /**
     * 获取用户绑定摄像头信息
     *
     * @param tmpUser
     * @return
     */
    public List<Object> getCameraList(User tmpUser) throws Exception {
        //摄像头信息
        List<Object> list2 = new ArrayList<Object>();
        //获取用户拥有摄像头
        List<CameraUser> cameraUserList = cameraUserHelperI.getCameraUserListByUserId(tmpUser.getUserId());
        for (CameraUser cameraUser : cameraUserList) {
            Camera camera = cameraUserHelperI.getCameraById(cameraUser.getCameraUserId().getCameraId());
            //封装摄像头返回信息
            list2.add(getCameraInfo(camera, cameraUser));
        }
        return list2;
    }

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

    /**
     * 将用户对象保存至redis缓存中,有效期1天
     *
     * @param user
     */
    private void saveUserToRedis(User user) throws Exception {
        String key = RedisKey.User_Key + user.getUserId();
        redisHelperI.setRedis(key, StringUtil.ObjectToJson(user));
    }

    /**
     * 获取云信的用户信息
     *
     * @return
     * @throws Exception
     */
    private User getNeteaseIMUser() throws Exception {
        User user = null;
        String key = RedisKey.User_Key + IfishFilePath.netease_phone;
        String userString = redisHelperI.getRedis(key);

        //1.从数据库或缓存中读取用户对象
        if (StringUtils.isNotBlank(userString)) {
            user = (User) StringUtil.JsonToBean(userString, User.class);
        } else {
            user = tbl_User_Mapper.getUserByPhoneNumber(IfishFilePath.netease_phone);
            redisHelperI.setRedis(key, StringUtil.ObjectToJson(user), 30, TimeUnit.DAYS);
        }
        return user;
    }
}
