package com.ifish.serviceImpl;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ifish.dao.CameraActiveDao;
import com.ifish.dao.CameraDao;
import com.ifish.dao.CameraUserDao;
import com.ifish.dao.DeviceCameraDao;
import com.ifish.dao.DeviceDao;
import com.ifish.dao.DeviceUserDao;
import com.ifish.dao.HardwareTypeDao;
import com.ifish.dao.LookReportDao;
import com.ifish.dao.PushListDao;
import com.ifish.dao.QuestionsFeedbackDao;
import com.ifish.dao.ShopsInfoDao;
import com.ifish.dao.UserDao;
import com.ifish.dao.VenderListDao;
import com.ifish.dao.VersionDao;
import com.ifish.entity.Camera;
import com.ifish.entity.CameraActive;
import com.ifish.entity.CameraUser;
import com.ifish.entity.CameraUserId;
import com.ifish.entity.Device;
import com.ifish.entity.DeviceCamera;
import com.ifish.entity.DeviceCameraId;
import com.ifish.entity.DeviceUser;
import com.ifish.entity.HardwareType;
import com.ifish.entity.LookReport;
import com.ifish.entity.DeviceUserId;
import com.ifish.entity.PushList;
import com.ifish.entity.QuestionsFeedback;
import com.ifish.entity.ShopsInfo;
import com.ifish.entity.User;
import com.ifish.entity.VenderList;
import com.ifish.entity.Version;
import com.ifish.enums.BooleanEnum;
import com.ifish.enums.GwellEnum;
import com.ifish.enums.Index1Enum;
import com.ifish.enums.Index2Enum;
import com.ifish.enums.Index3Enum;
import com.ifish.enums.NeteaseEnum;
import com.ifish.enums.PushTypeEnum;
import com.ifish.enums.ResultEnum;
import com.ifish.enums.SendTypeEnum;
import com.ifish.enums.ShopsStatusEnum;
import com.ifish.enums.SmsSignEnum;
import com.ifish.enums.SmsTemplateEnum;
import com.ifish.enums.SubDirectoryEnum;
import com.ifish.enums.UserTypeEnum;
import com.ifish.gwell.GwellApi;
import com.ifish.jpush.SmsNumSend;
import com.ifish.mail.Mail;
import com.ifish.netease.NeteaseIM;
import com.ifish.service.BaseService;
import com.ifish.util.IfishFilePath;
import com.ifish.util.IfishUtil;

/**
 * @ClassName: BaseServiceImpl
 * @Description: TODO
 * @author ggw
 *
 */
@Service
@Transactional
public class BaseServiceImpl implements BaseService {

    @Autowired
    private NeteaseIM neteaseIM;
    @Autowired
    private SmsNumSend smsNumSend;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CameraDao cameraDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private VersionDao versionDao;
    @Autowired
    private PushListDao pushListDao;
    @Autowired
    private LookReportDao lookReportDao;
    @Autowired
    private ShopsInfoDao shopsInfoDao;
    @Autowired
    private DeviceUserDao deviceUserDao;
    @Autowired
    private CameraActiveDao cameraActiveDao;
    @Autowired
    private VenderListDao venderListDao;
    @Autowired
    private CameraUserDao cameraUserDao;
    @Autowired
    private DeviceCameraDao deviceCameraDao;
    @Autowired
    private HardwareTypeDao hardwareTypeDao;
    @Autowired
    private QuestionsFeedbackDao questionsFeedbackDao;

    /**
     * 获取验证码
     */
    @Override
    public Object getSecurityCode(String phoneNumber, String sendType) {
        User user = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", 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(), "");
        }
    }

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

    /**
     * 登录
     */
    @Override
    public Object login(User user) {
        //验证用户是否存在,不存在返回错误信息
        User tmpUser = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", user.getPhoneNumber()));
        if (tmpUser == null) {
            //用户不存在
            return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
        } else if (tmpUser.getUserPassword().equals(user.getUserPassword())) {
            //是否更新
            boolean isUpdate = false;
            //未注册技威，则注册获取code1，code2
            if (tmpUser.getIsRegisterGwell().equals(BooleanEnum.NO.getKey())) {
                //注册技威
                Map<String, String> map = GwellApi.Register(user.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(user.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;
                    }
                }
            }
            //未注册云信
            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 = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", IfishFilePath.netease_phone));
                        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;
                        }
                    }
                }
            }
            //更新登陆参数
            userDao.executeLoginUpdate(tmpUser.getUserId(), tmpUser.getLoginType());
            if (isUpdate) {
                this.userDao.update(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()));
            }
            //自己的商家对象
            Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
            if (tmpUser.getUserId() != null) {
                ShopsInfo shopsInfo = this.shopsInfoDao.findUniqueByProperty(Restrictions.eq("userId", 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());
                }
            }
            //选择的的商家对象
            Map<String, Object> shopsInfo2Map = new HashMap<String, Object>();
            if (tmpUser.getShopsUserId() != null) {
                ShopsInfo shopsInfo = this.shopsInfoDao.findUniqueByProperty(Restrictions.eq("userId", tmpUser.getShopsUserId()));
                if (shopsInfo != null) {
                    User tmp2User = this.userDao.get(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());
                }
            }
            //设备信息
            List<Object> list = new ArrayList<Object>();
            //获取用户拥有设备
            List<DeviceUser> deviceUserList = this.deviceUserDao.findByProperty(Restrictions.eq("priId.userId", tmpUser.getUserId()));
            List<Integer> deviceIds = new ArrayList<Integer>();
            for (DeviceUser deviceUser : deviceUserList) {
                Device device = this.deviceDao.get(deviceUser.getPriId().getDeviceId());
                deviceIds.add(device.getDeviceId());
                //封装设备返回信息
                list.add(getDeviceInfo(device, deviceUser));
            }
            //摄像头信息
            List<Object> list2 = new ArrayList<Object>();
            //获取用户拥有摄像头
            List<CameraUser> cameraUserList = this.cameraUserDao.findByProperty(Restrictions.eq("cameraUserId.userId", tmpUser.getUserId()));
            for (CameraUser cameraUser : cameraUserList) {
                Camera camera = this.cameraDao.get(cameraUser.getCameraUserId().getCameraId());
                //封装摄像头返回信息
                list2.add(getCameraInfo(camera, cameraUser));
            }
            //设备-摄像头
            List<Object> list3 = new ArrayList<Object>();
            //设备已关联摄像头
            if (deviceIds.size() > 0) {
                List<DeviceCamera> deviceCameraList = this.deviceCameraDao.findByProperty(Restrictions.in("deviceCameraId.deviceId", deviceIds));
                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<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("user", userMap);
            dataMap.put("shopsInfo", shopsInfoMap);
            dataMap.put("shopsInfo2", shopsInfo2Map);
            dataMap.put("device", list);
            dataMap.put("camera", list2);
            dataMap.put("deviceCamera", list3);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
        } else {
            //密码不正确
            return IfishUtil.returnJson(ResultEnum.warn204.getKey(), "");
        }
    }

    /**
     * 新增保存用户信息
     */
    @Override
    public Object save(User user) {
        //随机生成6位用户名
        user.setNickName("鱼友" + IfishUtil.getCharAndNumr(5));
        user.setIsRegisterGwell(BooleanEnum.NO.getKey());
        user.setIsRegisterNetease(BooleanEnum.NO.getKey());
        user.setNeteaseToken("");
        user.setUserType(UserTypeEnum.userType0.getKey());
        Date date = new Date();
        user.setCreateTime(date);
        user.setUserImg("default/" + (new Random().nextInt(7) + 1) + ".png");
        user.setUpdateTime(date);
        this.userDao.save(user);
        //注册技威
        Map<String, String> map = GwellApi.Register(user.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");
                user.setIsRegisterGwell(BooleanEnum.YES.getKey());
                user.setP2PVerifyCode1(P2PVerifyCode1);
                user.setP2PVerifyCode2(P2PVerifyCode2);
                user.setGwellUserID(gwellUserID);
            } //已经注册过
            else if (result.equals(GwellEnum.repeat.getKey())) {
                user.setIsRegisterGwell(BooleanEnum.YES.getKey());
            }
        }
        //注册云信
        Map<String, String> neteaseMap = neteaseIM.createAccid(user.getUserId().toString(), user.getNickName(), IfishFilePath.getPath(SubDirectoryEnum.headImage, user.getUserImg()), "");
        if (neteaseMap != null) {
            String code = neteaseMap.get("code");
            if (code.equals(NeteaseEnum.status200.getKey())) {
                user.setIsRegisterNetease(BooleanEnum.YES.getKey());
                user.setNeteaseToken(neteaseMap.get("token"));
            } else if (code.equals(NeteaseEnum.status414.getKey())) {
                user.setIsRegisterNetease(BooleanEnum.YES.getKey());
            }
            this.userDao.update(user);
        }
        //发送云信消息
        User imUser = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", IfishFilePath.netease_phone));
        if (imUser != null) {
            neteaseIM.sendMsg(imUser.getUserId().toString(), user.getUserId().toString(), "感谢您使用爱鱼奇，连接智能设备请查看下方说明书，内含操作视频：http://u.eqxiu.com/s/KmmVl87l \n摄像头售后：021-54131006\n睿芯插排售后：18658232626\n绚多插排售后：18857689069\n松诺插排售后：13392205468", "");
        }
        //返回给App的数据
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("userId", user.getUserId().toString());
        dataMap.put("nickName", user.getNickName());
        dataMap.put("updateTime", IfishUtil.format(user.getUpdateTime()));
        return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
    }

    /**
     * 更新用户信息
     */
    @Override
    public Object updateInfo(User user) {
        user.setUpdateTime(new Date());
        userDao.update(user);
        //更新云信
        neteaseIM.updateUinfo(user.getUserId().toString(), user.getNickName(), IfishFilePath.getPath(SubDirectoryEnum.headImage, user.getUserImg()), "");
        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
    }

    /**
     * 验证原密码后更新用户密码
     */
    @Override
    public Object updatePwd(User user, String oldPassword) {
        User tmpUser = this.findById(user.getUserId());
        //判断原密码是否正确
        if (tmpUser.getUserPassword().equals(oldPassword)) {
            //密码正确，更新用户信息
            tmpUser.setUserPassword(user.getUserPassword());
            return this.updateInfo(tmpUser);
        }
        //原密码不正确，返回错误码
        return IfishUtil.returnJson(ResultEnum.warn204.getKey(), "");
    }

    /**
     * 忘记密码短信验证后修改密码
     */
    @Override
    public Object resetPassword(User user) {
        //验证手机号是否存在
        User tmpUser = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", user.getPhoneNumber()));
        if (tmpUser != null) {
            //手机号存在，修改密码
            tmpUser.setUserPassword(user.getUserPassword());
            return this.updateInfo(tmpUser);
        }
        //手机号不存在，返回错误码
        return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
    }

    /**
     * 根据ID查找
     */
    @Override
    public User findById(Integer userId) {
        return this.userDao.get(userId);
    }

    /**
     * 绑定设备
     */
    @Override
    public Object bindDevice(User user, String madAddress) {
        User tmpUser = userDao.get(user.getUserId());
        //用户存在
        if (tmpUser != null) {
            //新增用户拥有设备
            DeviceUser deviceUser = new DeviceUser();
            Device device = this.deviceDao.findUniqueByProperty(Restrictions.eq("macAddress", madAddress));
            boolean bln = false;
            //设备存在
            if (device != null) {
                //关联用户-设备
                deviceUser.getPriId().setUserId(tmpUser.getUserId());
                deviceUser.getPriId().setDeviceId(device.getDeviceId());
                //已关联设备的其他用户
                List<DeviceUser> deviceUserList = this.deviceUserDao.findByProperty(Restrictions.eq("priId.deviceId", device.getDeviceId()), Restrictions.ne("priId.userId", tmpUser.getUserId()));
                //是否已关联
                DeviceUser tmpDdeviceUser = this.deviceUserDao.get(deviceUser.getPriId());
                //已关联
                if (tmpDdeviceUser != null) {
                    //原先不是主控制，则删除其他用户关联关系
                    if (!tmpDdeviceUser.getIsMaster().equals(BooleanEnum.YES.getKey())) {
                        for (DeviceUser du : deviceUserList) {
                            Integer userId = du.getPriId().getUserId();
                            Integer deviceId = du.getPriId().getDeviceId();
                            User tu = this.userDao.get(userId);
                            if (tu != null) {
                                String timestamp = IfishUtil.format(new Date());
                                //基本参数
                                Map<String, String> baseMap = new HashMap<String, String>();
                                baseMap.put("title", PushTypeEnum.remove_device.getValue());
                                baseMap.put("content", "你已于" + timestamp + "失去对“" + du.getShowName() + "”设备的控制权");
                                baseMap.put("user_id", userId.toString());
                                baseMap.put("loginType", tu.getLoginType());
                                //推送参数
                                Map<String, String> pushMap = new HashMap<String, String>();
                                pushMap.put("device_id", deviceId.toString());
                                pushMap.put("device_name", du.getShowName());
                                pushMap.put("timestamp", timestamp);
                                pushMap.put("msg_type", PushTypeEnum.remove_device.getKey());
                                //推送消息
                                jPushNotifcation(baseMap, pushMap);
                            }
                            this.deviceUserDao.delete(du);
                            //删除设备和摄像头关系
                            DeviceCamera deviceCamera = this.deviceCameraDao.findUniqueByProperty(Restrictions.eq("deviceCameraId.deviceId", du.getPriId().getDeviceId()));
                            if (deviceCamera != null) {
                                this.deviceCameraDao.delete(deviceCamera);
                            }
                        }
                    }
                    //变更为主控
                    tmpDdeviceUser.setIsMaster(BooleanEnum.YES.getKey());
                    Date date = new Date();
                    tmpDdeviceUser.setUpdateTime(date);
                    tmpDdeviceUser.setCreateTime(date);
                    this.deviceUserDao.update(tmpDdeviceUser);
                    //返回数据
                    deviceUser.setShowName(tmpDdeviceUser.getShowName());
                    deviceUser.setIsMaster(tmpDdeviceUser.getIsMaster());
                } //未绑定过
                else {
                    //删除其他用户控制权
                    for (DeviceUser du : deviceUserList) {
                        Integer userId = du.getPriId().getUserId();
                        Integer deviceId = du.getPriId().getDeviceId();
                        User tu = this.userDao.get(userId);
                        if (tu != null) {
                            String timestamp = IfishUtil.format(new Date());
                            //基本参数
                            Map<String, String> baseMap = new HashMap<String, String>();
                            baseMap.put("title", PushTypeEnum.remove_device.getValue());
                            baseMap.put("content", "你已于" + timestamp + "失去对“" + du.getShowName() + "”设备的控制权");
                            baseMap.put("user_id", userId.toString());
                            baseMap.put("loginType", tu.getLoginType());
                            //推送参数
                            Map<String, String> pushMap = new HashMap<String, String>();
                            pushMap.put("device_id", deviceId.toString());
                            pushMap.put("device_name", du.getShowName());
                            pushMap.put("timestamp", timestamp);
                            pushMap.put("msg_type", PushTypeEnum.remove_device.getKey());
                            //推送消息
                            jPushNotifcation(baseMap, pushMap);
                        }
                        this.deviceUserDao.delete(du);
                        //删除设备和摄像头关系
                        DeviceCamera deviceCamera = this.deviceCameraDao.findUniqueByProperty(Restrictions.eq("deviceCameraId.deviceId", du.getPriId().getDeviceId()));
                        if (deviceCamera != null) {
                            this.deviceCameraDao.delete(deviceCamera);
                        }
                    }
                    //需要新增
                    bln = true;
                    //新增设备激活时间
                    if (device.getFirstActivate() == null) {
                        device.setFirstActivate(new Date());
                        device = this.deviceDao.save(device);
                    }
                }
            } //设备不存在
            else {
                //新增设备信息
                device = new Device();
                device.setLoginCount(0);
                device.setIsBlacklist(BooleanEnum.YES.getKey());
                device.setMacAddress(madAddress);
                Date date = new Date();
                device.setFirstActivate(date);
                device.setCreateDate(date);
                device.setCreateTime(date);
                device = this.deviceDao.save(device);
                //需要新增
                bln = true;
                deviceUser.getPriId().setUserId(tmpUser.getUserId());
                deviceUser.getPriId().setDeviceId(device.getDeviceId());
            }
            //需要新增
            if (bln) {
                //新增关联关系
                deviceUser.setShowName("鱼缸" + (int) (Math.random() * 9000 + 1000));
                deviceUser.setIsMaster(BooleanEnum.YES.getKey());
                Date date = new Date();
                deviceUser.setUpdateTime(date);
                deviceUser.setCreateTime(date);
                this.deviceUserDao.save(deviceUser);
            }
            //封装设备返回信息
            return IfishUtil.returnJson(ResultEnum.success.getKey(), getDeviceInfo(device, deviceUser));
        } else {
            return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
        }
    }

    /**
     * 绑定摄像头
     */
    @Override
    public Object bindCamera(Integer userId, String cameraId) {
        User user = userDao.get(userId);
        Camera camera = this.cameraDao.get(cameraId);
        //返回数据
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //用户存在
        if (user != null) {
            //摄像头存在
            if (camera != null) {
                //已关联摄像头的用户
                List<CameraUser> CameraUserList = this.cameraUserDao.findByProperty(Restrictions.eq("cameraUserId.cameraId", cameraId));
                //删除摄像头与用户关系
                for (CameraUser cu : CameraUserList) {
                    this.cameraUserDao.delete(cu);
                    //删除设备和摄像头关系
                    DeviceCamera deviceCamera = this.deviceCameraDao.findUniqueByProperty(Restrictions.eq("deviceCameraId.cameraId", cu.getCameraUserId().getCameraId()));
                    if (deviceCamera != null) {
                        this.deviceCameraDao.delete(deviceCamera);
                    }
                }
            } else {
                //摄像头不存在
                camera = new Camera();
                camera.setCameraId(cameraId);
                camera.setCreateTime(new Date());
                this.cameraDao.save(camera);
            }
            //建立关系
            CameraUser cameraUser = new CameraUser();
            CameraUserId cameraUserId = new CameraUserId(userId, cameraId);
            cameraUser.setCameraUserId(cameraUserId);
            cameraUser.setIsMaster(BooleanEnum.YES.getKey());
            cameraUser.setIsLook(BooleanEnum.NO.getKey());
            cameraUser.setIsLive(BooleanEnum.NO.getKey());
            cameraUser.setShowName("摄像头" + (int) (Math.random() * 900 + 100));
            cameraUser.setCreateTime(new Date());
            this.cameraUserDao.save(cameraUser);
            //返回数据
            dataMap.put("cameraId", cameraId);
            dataMap.put("showName", cameraUser.getShowName());
            dataMap.put("isMaster", cameraUser.getIsMaster());
            dataMap.put("isLook", cameraUser.getIsLook());
            dataMap.put("isLive", cameraUser.getIsLive());
            dataMap.put("isActive", camera.getActiveCode() != null && !camera.getActiveCode().equals("") ? "1" : "0");
            return IfishUtil.returnJson(ResultEnum.success.getKey(), dataMap);
        } else {
            return IfishUtil.returnJson(ResultEnum.warn202.getKey(), "");
        }
    }

    /**
     * 激活摄像头
     */
    @Override
    public Object activeCamera(String activeCode, String cameraId) {
        CameraActive cameraActive = this.cameraActiveDao.get(activeCode);
        //激活码有效
        if (cameraActive != null) {
            //激活码被使用
            if (cameraActive.getIsUsed().equals(BooleanEnum.YES.getKey())) {
                return IfishUtil.returnJson(ResultEnum.warn208.getKey(), "");
            } else {
                Camera camera = this.cameraDao.get(cameraId);
                if (camera != null) {
                    if (camera.getActiveCode() != null && !camera.getActiveCode().equals("")) {
                        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
                    } else {
                        //激活成功
                        camera.setActiveCode(activeCode);
                        camera.setActiveTime(new Date());
                        camera.setUpdateTime(new Date());
                        this.cameraDao.update(camera);
                        //激活码改成被使用
                        cameraActive.setIsUsed(BooleanEnum.YES.getKey());
                        this.cameraActiveDao.update(cameraActive);
                        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
                    }
                } else {
                    return IfishUtil.returnJson(ResultEnum.warn210.getKey(), "");
                }
            }
        } else {
            return IfishUtil.returnJson(ResultEnum.warn209.getKey(), "");
        }
    }

    /**
     * 封装摄像头返回信息
     *
     * @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;
    }

    /**
     * 封装设备返回信息
     *
     * @param device
     * @param deviceUser
     * @return
     */
    public Map<String, Object> getDeviceInfo(Device device, DeviceUser deviceUser) {
        Map<String, Object> deviceMap = new HashMap<String, Object>();
        deviceMap.put("userId", deviceUser.getPriId().getUserId());
        deviceMap.put("deviceId", deviceUser.getPriId().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 = this.hardwareTypeDao.get(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 = venderListDao.get(device.getBrandCode());
            deviceMap.put("venderList", venderList);
        } else {
            //默认爱鱼奇
            VenderList defaultVenderList = venderListDao.getDefaultVenderList();
            deviceMap.put("venderList", defaultVenderList);
        }
        return deviceMap;
    }

    /**
     * 更新设备信息
     */
    @Override
    public Object update(DeviceUser deviceUser) {
        DeviceUser tmpDeviceUser = this.deviceUserDao.get(deviceUser.getPriId());
        if (tmpDeviceUser != null) {
            tmpDeviceUser.setUpdateTime(new Date());
            tmpDeviceUser.setShowName(deviceUser.getShowName());
            this.deviceUserDao.update(tmpDeviceUser);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        }
        return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
    }

    /**
     * 更新摄像头信息
     */
    @Override
    public Object update(CameraUserId id, String showName) {
        CameraUser cameraUser = this.cameraUserDao.get(id);
        if (cameraUser != null) {
            cameraUser.setUpdateTime(new Date());
            cameraUser.setShowName(showName);
            this.cameraUserDao.update(cameraUser);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        } else {
            return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
        }
    }

    /**
     * 修改自定义图标
     */
    @Override
    public Object updateCustomIcon(DeviceUser deviceUser) {
        DeviceUser tmpDeviceUser = this.deviceUserDao.get(deviceUser.getPriId());
        if (tmpDeviceUser != null) {
            tmpDeviceUser.setCustomIconName(deviceUser.getCustomIconName());
            tmpDeviceUser.setCustomShowName(deviceUser.getCustomShowName());
            tmpDeviceUser.setUpdateTime(new Date());
            this.deviceUserDao.update(tmpDeviceUser);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        } else {
            return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
        }
    }

    /**
     * 删除绑定的设备
     */
    @Override
    public Object deleteDeviceUser(DeviceUser deviceUser) {
        deviceUser = deviceUserDao.get(deviceUser.getPriId());
        if (deviceUser != null) {
            //是主控则解除全部关系
            if (deviceUser.getIsMaster().equals(BooleanEnum.YES.getKey())) {
                //已关联设备的所有用户
                List<DeviceUser> deviceUserList = this.deviceUserDao.findByProperty(Restrictions.eq("priId.deviceId", deviceUser.getPriId().getDeviceId()), Restrictions.ne("priId.userId", deviceUser.getPriId().getUserId()));
                //删除所有用户控制权
                for (DeviceUser du : deviceUserList) {
                    Integer userId = du.getPriId().getUserId();
                    Integer deviceId = du.getPriId().getDeviceId();
                    User tu = this.userDao.get(userId);
                    if (tu != null) {
                        String timestamp = IfishUtil.format(new Date());
                        //基本参数
                        Map<String, String> baseMap = new HashMap<String, String>();
                        baseMap.put("title", PushTypeEnum.remove_device.getValue());
                        baseMap.put("content", "你已于" + timestamp + "失去对“" + du.getShowName() + "”设备的控制权");
                        baseMap.put("user_id", userId.toString());
                        baseMap.put("loginType", tu.getLoginType());
                        //推送参数
                        Map<String, String> pushMap = new HashMap<String, String>();
                        pushMap.put("device_id", deviceId.toString());
                        pushMap.put("device_name", du.getShowName());
                        pushMap.put("timestamp", timestamp);
                        pushMap.put("msg_type", PushTypeEnum.remove_device.getKey());
                        //推送消息
                        jPushNotifcation(baseMap, pushMap);
                    }
                    //删除设备和用户关系
                    this.deviceUserDao.delete(du);
                }
                //删除设备和摄像头关系
                DeviceCamera deviceCamera = this.deviceCameraDao.findUniqueByProperty(Restrictions.eq("deviceCameraId.deviceId", deviceUser.getPriId().getDeviceId()));
                if (deviceCamera != null) {
                    this.deviceCameraDao.delete(deviceCamera);
                }
            }
            //删除设备和用户关系
            this.deviceUserDao.delete(deviceUser);
        }
        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
    }

    /**
     * 删除绑定的摄像头
     */
    @Override
    public Object deleteCameraUser(Integer userId, String cameraId) {
        CameraUserId cameraUserId = new CameraUserId(userId, cameraId);
        CameraUser cameraUser = this.cameraUserDao.get(cameraUserId);
        if (cameraUser != null) {
            //删除用户摄像头关系
            this.cameraUserDao.delete(cameraUser);
            //删除设备和摄像头关系
            DeviceCamera deviceCamera = this.deviceCameraDao.findUniqueByProperty(Restrictions.eq("deviceCameraId.cameraId", cameraId));
            if (deviceCamera != null) {
                this.deviceCameraDao.delete(deviceCamera);
            }
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        } else {
            return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
        }
    }

    /**
     * 最新版本信息
     */
    @Override
    public Object getNewestVersionInf(String phoneType) {
        Map<String, Object> map = new HashMap<String, Object>();
        //最新版本信息
        Version version = this.versionDao.getNewestVersion(phoneType);
        if (version != null) {
            map.put("versionCode", version.getVersionCode());
            map.put("phoneType", version.getPhoneType());
            map.put("isMustUpdate", version.getIsMustUpdate());
            map.put("uploadContent", version.getUploadContent());
            map.put("appAddress", version.getAppAddress());
        }
        //返回版本信息
        return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
    }

    /**
     * 上传头像
     */
    @Override
    public Object uploadFile(User user, MultipartFile fileUpload) {
        //上传文件名称
        String fileName = fileUpload.getOriginalFilename();
        //验证图片格式
        String extEndName = IfishFilePath.checkImgName(fileName);
        //图片名称
        String picName = user.getUserId() + "_icon.png";
        //验证图片格式
        if (!fileUpload.isEmpty() && extEndName != null) {
            try {
                if (!fileUpload.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_img, picName);
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    fileUpload.transferTo(picFile);
                }
                //更新数据库
                user.setUserImg(picName + "?timestamp=" + System.currentTimeMillis());
                user.setUpdateTime(new Date());
                user = this.userDao.update(user);
                //更新云信
                neteaseIM.updateUinfo(user.getUserId().toString(), user.getNickName(), IfishFilePath.getPath(SubDirectoryEnum.headImage, user.getUserImg()), "");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userImg", user.getUserImg());
            map.put("updateTime", user.getUpdateTime());
            //上传成功
            return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
        }
        return IfishUtil.returnJson(ResultEnum.warn205.getKey(), "");
    }

    @Override
    public Object saveQuestionsFeedback(QuestionsFeedback feedback) {
        Date date = new Date();
        feedback.setCreateTime(date);
        feedback.setQuestionReply("");
        this.questionsFeedbackDao.save(feedback);
//		User user = this.userDao.findById(feedback.getUserId());
//		if(user!=null){
//			Mail.send(user.getNickName()+"("+user.getPhoneNumber()+")的问题反馈", feedback.getQuestionContent());
//		}
        //发送云信消息
        User imUser = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", IfishFilePath.netease_phone));
        if (imUser != null) {
            neteaseIM.sendMsg(feedback.getUserId().toString(), imUser.getUserId().toString(), feedback.getQuestionContent(), "");
        }
        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
    }

    @Override
    public Object shareDeviceByQrCode(Integer userId, Integer deviceId) {
        User user = userDao.get(userId);
        Device device = deviceDao.get(deviceId);
        if (user != null && device != null) {
            DeviceUser deviceUser = new DeviceUser();
            deviceUser.getPriId().setUserId(user.getUserId());
            deviceUser.getPriId().setDeviceId(device.getDeviceId());
            DeviceUser tmpDeviceUser = deviceUserDao.get(deviceUser.getPriId());
            if (tmpDeviceUser != null) {
                //封装设备返回信息
                return IfishUtil.returnJson(ResultEnum.success.getKey(), getDeviceInfo(device, tmpDeviceUser));
            } else {
                deviceUser.setIsMaster(BooleanEnum.NO.getKey());
                deviceUser.setShowName("鱼缸" + (int) (Math.random() * 9000 + 1000));
                Date date = new Date();
                deviceUser.setUpdateTime(date);
                deviceUser.setCreateTime(date);
                this.deviceUserDao.save(deviceUser);
                //封装设备返回信息
                return IfishUtil.returnJson(ResultEnum.success.getKey(), getDeviceInfo(device, deviceUser));
            }
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    /**
     * 极光推送
     *
     * @param userId
     */
    public boolean jPushNotifcation(Map<String, String> baseMap, Map<String, String> pushMap) {
        try {
            //登录类型
            String loginType = baseMap.get("loginType");
            if (loginType != null) {
                //推送消息类型
                String msgType = pushMap.get("msg_type");
                String userId = baseMap.get("user_id");
                String title = baseMap.get("title");
                String content = baseMap.get("content");
                //云信推送
                Map<String, String> neteaseMap = neteaseIM.sendMsg(IfishFilePath.ifish_account, userId, "【" + title + "】" + content, JSON.toJSONString(pushMap));
                boolean neteaseBln = neteaseMap.get("code").equals(NeteaseEnum.status200.getKey());
                //推送记录
                PushList pushList = new PushList();
                if (msgType.equals(PushTypeEnum.remove_device.getKey())) {
                    pushList.setUserId(Integer.valueOf(userId));
                    pushList.setDeviceId(Integer.valueOf(pushMap.get("device_id")));
                    pushList.setPhoneType(loginType);
                    pushList.setShowName(pushMap.get("showName"));
                    pushList.setPushType(msgType);
                    pushList.setPushTitle(title);
                    pushList.setPushContext(content);
                    pushList.setNeteaseStatus(neteaseBln ? BooleanEnum.YES.getKey() : BooleanEnum.NO.getKey());
                    pushList.setCreateTime(new Date());
                    pushListDao.save(pushList);
                    return true;
                } //发送看护报告推送
                else if (msgType.equals(PushTypeEnum.send_report.getKey())) {
                    String reportId = baseMap.get("reportId");
                    if (reportId != null) {
                        pushList.setReportId(Integer.valueOf(reportId));
                    }
                    pushList.setUserId(Integer.valueOf(userId));
                    pushList.setPhoneType(loginType);
                    pushList.setPushType(msgType);
                    pushList.setPushTitle(title);
                    pushList.setPushContext(content);
                    pushList.setPushLink(pushMap.get("push_link"));
                    pushList.setNeteaseStatus(neteaseBln ? BooleanEnum.YES.getKey() : BooleanEnum.NO.getKey());
                    pushList.setCreateTime(new Date());
                    pushListDao.save(pushList);
                    return true;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return false;
    }

    @Override
    public Object getSingleDeviceInf(DeviceUser deviceUser) {
        Integer deviceId = deviceUser.getPriId().getDeviceId();
        Integer userId = deviceUser.getPriId().getUserId();
        if (deviceId != null && userId != null) {
            Device tmpDevice = this.deviceDao.get(deviceId);
            DeviceUser tmpDeviceUser = this.deviceUserDao.get(deviceUser.getPriId());
            if (tmpDevice != null && tmpDeviceUser != null) {
                //封装设备返回信息
                return IfishUtil.returnJson(ResultEnum.success.getKey(), getDeviceInfo(tmpDevice, tmpDeviceUser));
            }
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object getRemindWaterInf(Integer deviceId) {
        Device device = deviceDao.get(deviceId);
        if (device != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            //换水提醒
            map.put("todayRemind", device.getTodayRemind());
            map.put("waterRemind", device.getWaterRemind());
            map.put("remindDate", device.getRemindDate() != null ? IfishUtil.format1(device.getRemindDate()) : "");
            map.put("remindCycle", device.getRemindCycle() != null ? device.getRemindCycle() : "");
            return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object setRemindWaterInf(Device device) {
        Device tmpDevice = this.deviceDao.get(device.getDeviceId());
        if (tmpDevice != null) {
            //设置换水提醒
            tmpDevice.setRemindCycle(device.getRemindCycle());
            tmpDevice.setWaterRemind(device.getWaterRemind());
            //默认今天不需要提醒
            tmpDevice.setTodayRemind(BooleanEnum.NO.getKey());
            //下一次提醒日期
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, device.getRemindCycle());
            tmpDevice.setRemindDate(calendar.getTime());
            this.deviceDao.update(tmpDevice);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("todayRemind", tmpDevice.getTodayRemind());
            map.put("waterRemind", tmpDevice.getWaterRemind());
            map.put("remindDate", IfishUtil.format1(tmpDevice.getRemindDate()));
            map.put("remindCycle", tmpDevice.getRemindCycle());
            return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object deviceBindCamera(Integer deviceId, String cameraId) {
        DeviceCameraId id = new DeviceCameraId(deviceId, cameraId);
        DeviceCamera deviceCamera = this.deviceCameraDao.get(id);
        if (deviceCamera == null) {
            deviceCamera = new DeviceCamera();
            deviceCamera.setDeviceCameraId(id);
            this.deviceCameraDao.save(deviceCamera);
        }
        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
    }

    @Override
    public Object deviceBindCamera1(Integer userId, Integer deviceId, String cameraId) {
        //设备和用户关系
        DeviceUserId priId = new DeviceUserId();
        priId.setDeviceId(deviceId);
        priId.setUserId(userId);
        DeviceUser deviceUser = this.deviceUserDao.get(priId);
        if (deviceUser == null) {
            return IfishUtil.returnJson(ResultEnum.warn207.getKey(), "");
        }
        //摄像头和用户关系
        CameraUserId cuId = new CameraUserId(userId, cameraId);
        CameraUser cameraUser = this.cameraUserDao.get(cuId);
        if (cameraUser == null) {
            return IfishUtil.returnJson(ResultEnum.warn210.getKey(), "");
        }
        //设备和摄像头关系
        DeviceCameraId id = new DeviceCameraId(deviceId, cameraId);
        DeviceCamera deviceCamera = this.deviceCameraDao.get(id);
        if (deviceCamera == null) {
            deviceCamera = new DeviceCamera();
            deviceCamera.setDeviceCameraId(id);
            this.deviceCameraDao.save(deviceCamera);
        }
        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
    }

    @Override
    public Object deleteDeviceCamera(Integer deviceId, String cameraId) {
        DeviceCameraId id = new DeviceCameraId(deviceId, cameraId);
        DeviceCamera deviceCamera = this.deviceCameraDao.get(id);
        if (deviceCamera != null) {
            this.deviceCameraDao.delete(deviceCamera);
        }
        return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
    }

    @Override
    public Object saveShopsInfo(ShopsInfo shopsInfo, MultipartFile file1, MultipartFile file2, MultipartFile file3) {
        //用户ID
        Integer userId = shopsInfo.getUserId();
        User user = this.userDao.get(userId);
        if (user == null) {
            return IfishUtil.returnJson(ResultEnum.warn211.getKey(), "");
        }
        //验证图片格式
        if (!file1.isEmpty() && !file2.isEmpty() && !file3.isEmpty()) {
            try {
                if (!file1.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + userId, "1.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file1.transferTo(picFile);
                }
                if (!file2.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + userId, "2.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file2.transferTo(picFile);
                }
                if (!file3.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + userId, "3.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file3.transferTo(picFile);
                }
                //保存商家信息
                shopsInfo.setPicture1("1.png");
                shopsInfo.setPicture2("2.png");
                shopsInfo.setPicture3("3.png");
                shopsInfo.setStatus(ShopsStatusEnum.status2.getKey());
                shopsInfo.setUpdateTime(new Date());
                shopsInfo.setCreateTime(new Date());
                this.shopsInfoDao.save(shopsInfo);
                //发送邮件
                Mail.send(user.getNickName() + "(" + user.getPhoneNumber() + ")提交审核了", "有提交新的审核!");
                Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
                shopsInfoMap.put("shopsId", shopsInfo.getShopsId());
                shopsInfoMap.put("userId", shopsInfo.getUserId());
                shopsInfoMap.put("userImg", user.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 IfishUtil.returnJson(ResultEnum.success.getKey(), shopsInfoMap);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object updateShopsInfo(ShopsInfo shopsInfo, MultipartFile file1, MultipartFile file2, MultipartFile file3) {
        ShopsInfo tmpShopsInfo = this.shopsInfoDao.get(shopsInfo.getShopsId());
        if (tmpShopsInfo != null) {
            Integer userId = tmpShopsInfo.getUserId();
            try {
                if (file1 != null && !file1.isEmpty() && !file1.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + userId, "1.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file1.transferTo(picFile);
                }
                if (file2 != null && !file2.isEmpty() && !file2.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + userId, "2.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file2.transferTo(picFile);
                }
                if (file3 != null && !file3.isEmpty() && !file3.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + userId, "3.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file3.transferTo(picFile);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //保存商家信息
            tmpShopsInfo.setShopsName(shopsInfo.getShopsName());
            tmpShopsInfo.setUserName(shopsInfo.getUserName());
            tmpShopsInfo.setShopsPhone(shopsInfo.getShopsPhone());
            tmpShopsInfo.setShopsProvince(shopsInfo.getShopsProvince());
            tmpShopsInfo.setShopsCity(shopsInfo.getShopsCity());
            tmpShopsInfo.setShopsArea(shopsInfo.getShopsArea());
            tmpShopsInfo.setShopsAddress(shopsInfo.getShopsAddress());
            tmpShopsInfo.setStatus(ShopsStatusEnum.status2.getKey());
            tmpShopsInfo.setUpdateTime(new Date());
            this.shopsInfoDao.update(tmpShopsInfo);
            User user = this.userDao.get(tmpShopsInfo.getUserId());
            //发送邮件
            Mail.send(user.getNickName() + "(" + user.getPhoneNumber() + ")重新提交审核了", "重新提交了新的审核!");
            Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
            shopsInfoMap.put("shopsId", tmpShopsInfo.getShopsId());
            shopsInfoMap.put("userId", tmpShopsInfo.getUserId());
            shopsInfoMap.put("userImg", user.getUserImg());
            shopsInfoMap.put("userName", tmpShopsInfo.getUserName());
            shopsInfoMap.put("shopsName", tmpShopsInfo.getShopsName());
            shopsInfoMap.put("shopsPhone", tmpShopsInfo.getShopsPhone());
            shopsInfoMap.put("shopsProvince", tmpShopsInfo.getShopsProvince());
            shopsInfoMap.put("shopsCity", tmpShopsInfo.getShopsCity());
            shopsInfoMap.put("shopsArea", tmpShopsInfo.getShopsArea());
            shopsInfoMap.put("shopsAddress", tmpShopsInfo.getShopsAddress());
            shopsInfoMap.put("picture1", tmpShopsInfo.getPicture1());
            shopsInfoMap.put("picture2", tmpShopsInfo.getPicture2());
            shopsInfoMap.put("picture3", tmpShopsInfo.getPicture3());
            shopsInfoMap.put("picture4", tmpShopsInfo.getPicture4());
            shopsInfoMap.put("status", tmpShopsInfo.getStatus());
            shopsInfoMap.put("reason", tmpShopsInfo.getReason());
            return IfishUtil.returnJson(ResultEnum.success.getKey(), shopsInfoMap);
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object updateBaseShopsInfo(ShopsInfo shopsInfo, MultipartFile file4) {
        ShopsInfo tmpShopsInfo = this.shopsInfoDao.get(shopsInfo.getShopsId());
        if (tmpShopsInfo != null) {
            try {
                if (file4 != null && !file4.isEmpty() && !file4.getOriginalFilename().equals("")) {
                    File picFile = new File(IfishFilePath.path_shops + "/" + tmpShopsInfo.getUserId(), "4.png");
                    //不存在则创建
                    if (!picFile.exists()) {
                        picFile.mkdirs();
                    }
                    //保存
                    file4.transferTo(picFile);
                    tmpShopsInfo.setPicture4("4.png");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            tmpShopsInfo.setShopsPhone(shopsInfo.getShopsPhone());
            tmpShopsInfo.setShopsProvince(shopsInfo.getShopsProvince());
            tmpShopsInfo.setShopsCity(shopsInfo.getShopsCity());
            tmpShopsInfo.setShopsArea(shopsInfo.getShopsArea());
            tmpShopsInfo.setShopsAddress(shopsInfo.getShopsAddress());
            tmpShopsInfo.setUpdateTime(new Date());
            this.shopsInfoDao.update(tmpShopsInfo);
            Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
            User user = this.userDao.get(tmpShopsInfo.getUserId());
            shopsInfoMap.put("shopsId", tmpShopsInfo.getShopsId());
            shopsInfoMap.put("userId", tmpShopsInfo.getUserId());
            shopsInfoMap.put("userImg", user.getUserImg());
            shopsInfoMap.put("userName", tmpShopsInfo.getUserName());
            shopsInfoMap.put("shopsName", tmpShopsInfo.getShopsName());
            shopsInfoMap.put("shopsPhone", tmpShopsInfo.getShopsPhone());
            shopsInfoMap.put("shopsProvince", tmpShopsInfo.getShopsProvince());
            shopsInfoMap.put("shopsCity", tmpShopsInfo.getShopsCity());
            shopsInfoMap.put("shopsArea", tmpShopsInfo.getShopsArea());
            shopsInfoMap.put("shopsAddress", tmpShopsInfo.getShopsAddress());
            shopsInfoMap.put("picture1", tmpShopsInfo.getPicture1());
            shopsInfoMap.put("picture2", tmpShopsInfo.getPicture2());
            shopsInfoMap.put("picture3", tmpShopsInfo.getPicture3());
            shopsInfoMap.put("picture4", tmpShopsInfo.getPicture4());
            shopsInfoMap.put("status", tmpShopsInfo.getStatus());
            shopsInfoMap.put("reason", tmpShopsInfo.getReason());
            return IfishUtil.returnJson(ResultEnum.success.getKey(), shopsInfoMap);
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object getShopsStatus(Integer shopsId) {
        ShopsInfo shopsInfo = this.shopsInfoDao.get(shopsId);
        if (shopsInfo != null) {
            User user = this.userDao.get(shopsInfo.getUserId());
            Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
            shopsInfoMap.put("shopsId", shopsInfo.getShopsId());
            shopsInfoMap.put("userId", shopsInfo.getUserId());
            shopsInfoMap.put("userImg", user.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 IfishUtil.returnJson(ResultEnum.success.getKey(), shopsInfoMap);
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object choiceShops(String phoneNumber, Integer userId) {
        //商家用户
        User user = this.userDao.findUniqueByProperty(Restrictions.eq("phoneNumber", phoneNumber));
        //商家和用户不能是同一个帐号
        if (user != null && userId != null && !userId.equals(user.getUserId())) {
            //用户类型是商家
            if (user != null && user.getUserType().equals(UserTypeEnum.userType1.getKey())) {
                //商家信息
                ShopsInfo shopsInfo = this.shopsInfoDao.findUniqueByProperty(Restrictions.eq("userId", user.getUserId()));
                //当前用户
                User tmpUser = this.userDao.get(userId);
                if (shopsInfo != null && tmpUser != null) {
                    tmpUser.setShopsUserId(user.getUserId());
                    tmpUser.setUpdateTime(new Date());
                    this.userDao.update(tmpUser);
                    Map<String, Object> shopsInfoMap = new HashMap<String, Object>();
                    shopsInfoMap.put("shopsId", shopsInfo.getShopsId());
                    shopsInfoMap.put("userId", shopsInfo.getUserId());
                    shopsInfoMap.put("userImg", user.getUserImg());
                    shopsInfoMap.put("userName", user.getNickName());
                    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());
                    //发送云信消息
                    neteaseIM.sendMsg(IfishFilePath.ifish_account, shopsInfo.getUserId().toString(), "【" + PushTypeEnum.shops_push.getValue() + "】恭喜，[" + tmpUser.getNickName() + "]已经将你锁定为他的看护商家，快去看看吧", "");
                    return IfishUtil.returnJson(ResultEnum.success.getKey(), shopsInfoMap);
                }
            }
        }
        return IfishUtil.returnJson(ResultEnum.warn212.getKey(), "");
    }

    @Override
    public Object onoffLook(String cameraId, Integer userId, String status) {
        CameraUserId id = new CameraUserId(userId, cameraId);
        CameraUser cameraUser = this.cameraUserDao.get(id);
        if (cameraUser != null) {
            cameraUser.setIsLook(status);
            this.cameraUserDao.update(cameraUser);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        }
        return IfishUtil.returnJson(ResultEnum.warn210.getKey(), "");
    }

    @Override
    public Object lookReport(Integer userId, String index1, String index2, String index3, String suggestion, MultipartFile fileUpload) {
        try {
            ShopsInfo shopsInfo = this.shopsInfoDao.findUniqueByProperty(Restrictions.eq("userId", userId));
            User user = this.userDao.get(userId);
            if (shopsInfo != null && user != null) {
                String pngName = IfishUtil.uploadFile(fileUpload, IfishFilePath.path_look_img);
                if (pngName != null && !pngName.equals("")) {
                    LookReport lookReport = IfishUtil.getLookFile(shopsInfo, user, index1, index2, index3, suggestion, pngName, IfishFilePath.html_name, IfishFilePath.path_look_html);
                    if (lookReport != null) {
                        this.lookReportDao.save(lookReport);
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("timestamp", IfishUtil.format2(lookReport.getTimestamp()));
                        map.put("totalIndex", lookReport.getTotalIndex());
                        map.put("baifenbi", lookReport.getBaifenbi());
                        map.put("shareImg", pngName);
                        map.put("fileName", lookReport.getHtmlName());
                        map.put("reportId", lookReport.getReportId().toString());
                        return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object sendReport(Integer userId, String fileName) {
        User user = this.userDao.get(userId);
        if (user != null) {
            String timestamp = IfishUtil.format(new Date());
            //基本参数
            Map<String, String> baseMap = new HashMap<String, String>();
            baseMap.put("title", PushTypeEnum.send_report.getValue());
            baseMap.put("content", "[点击查看]您的看护报告已生成，记得抽空看下哟。");
            baseMap.put("user_id", userId.toString());
            baseMap.put("loginType", user.getLoginType());
            //推送参数
            Map<String, String> pushMap = new HashMap<String, String>();
            pushMap.put("push_link", IfishFilePath.getPath(SubDirectoryEnum.look, fileName));
            pushMap.put("timestamp", timestamp);
            pushMap.put("msg_type", PushTypeEnum.send_report.getKey());
            jPushNotifcation(baseMap, pushMap);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object sendReport(Integer userId, String fileName, Integer reportId) {
        User user = this.userDao.get(userId);
        if (user != null) {
            String timestamp = IfishUtil.format(new Date());
            //基本参数
            Map<String, String> baseMap = new HashMap<String, String>();
            baseMap.put("title", PushTypeEnum.send_report.getValue());
            baseMap.put("content", "您的看护报告已生成，记得抽空看下哟，点击查看。");
            baseMap.put("user_id", userId.toString());
            baseMap.put("reportId", reportId.toString());
            baseMap.put("loginType", user.getLoginType());
            //推送参数
            Map<String, String> pushMap = new HashMap<String, String>();
            pushMap.put("push_link", IfishFilePath.getPath(SubDirectoryEnum.look, fileName));
            pushMap.put("title", PushTypeEnum.send_report.getValue());
            pushMap.put("timestamp", timestamp);
            pushMap.put("reportId", reportId.toString());
            pushMap.put("msg_type", PushTypeEnum.send_report.getKey());
            jPushNotifcation(baseMap, pushMap);
            return IfishUtil.returnJson(ResultEnum.success.getKey(), "");
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

    @Override
    public Object getLookReportById(Integer reportId) {
        LookReport lookReport = lookReportDao.get(reportId);
        if (lookReport != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("reportId", lookReport.getReportId());
            map.put("shareImg", lookReport.getShareImg());
            map.put("timestamp", IfishUtil.format2(lookReport.getTimestamp()));
            map.put("index1", lookReport.getIndex1());
            map.put("index2", lookReport.getIndex2());
            map.put("index3", lookReport.getIndex3());
            map.put("suggestion", lookReport.getSuggestion());
            map.put("totalIndex", lookReport.getTotalIndex());
            map.put("baifenbi", lookReport.getBaifenbi());
            map.put("userImg", lookReport.getUserImg());
            map.put("shopsName", lookReport.getShopsName());
            map.put("signature", lookReport.getSignature());
            map.put("index1Text", Index1Enum.getValue(lookReport.getIndex1()));
            map.put("index2Text", Index2Enum.getValue(lookReport.getIndex2()));
            map.put("index3Text", Index3Enum.getValue(lookReport.getIndex3()));
            return IfishUtil.returnJson(ResultEnum.success.getKey(), map);
        }
        return IfishUtil.returnJson(ResultEnum.fail101.getKey(), "");
    }

}
