package com.ssj.service.conch.conch.service.impl;

import com.alibaba.fastjson.JSON;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.message.custom.Text;
import com.ssj.bean.weixin.message.custom.TextCustom;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.dao.conch.conch.dao.ConchDerverDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.PasswordUtil;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.framework.weixin.util.NewsUtil;
import com.ssj.service.conch.common.service.ConchCommonService;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.weixin.utils.Location;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sh
 * @className ConchDerverServiceImpl
 * @description TODO
 * @date 2020/7/13
 */
@Service
@Transactional
public class ConchDerverServiceImpl extends BaseServiceImpl<ConchDerver, String> implements ConchDerverService {

    protected Logger logger   = LoggerFactory.getLogger(this.getClass());

    private String DERVER ="DERVER_";
    private String PDDERVER ="PD_DERVER_";

    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private ConchDerverDao conchDerverDao;
    @Autowired
    private ILibVipService vipService;

    @Autowired
    private UserService userService;

    @Autowired
    private SconXingeService sconXingeService;
    @Autowired
    private EasemobService easemobService;

    @Autowired
    private ConchCommonService conchCommonService;

    @Autowired
    private LibVipServiceService libVipServiceService;

    @Override
    public PagingAndSortingRepository<ConchDerver, String> getDao() {
        return conchDerverDao;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ConchDerver getConchDerverByImei(String imei) {
        return conchDerverDao.getConchDerverByImei(imei);
    }

    @Override
    public Map<String, String> bindingVip(String vipId, String derver, String userId, String openId) {
        Map<String,String> map  =new HashMap<String, String>();
        logger.info("设备号:{}, userId：{}，vipId：{}", derver, userId, vipId);
        ConchDerver  conchDerver=this.findByDerver(derver);
        if(conchDerver !=null){
            String derVipId = conchDerver.getVipId();
            if(derVipId!=null&&derVipId.trim().length()>0){
                if(derVipId.equals(vipId)){
                    logger.info("您已绑定过该设备,无需再绑定");
                    map.put("stat", "1");
                    map.put("mgs", "您已绑定过该设备,无需再绑定");
                    return map;
                }else{
                    logger.info("设备已被其他用户绑定");
                    map.put("stat", "-1");
                    map.put("mgs", "设备已被其他用户绑定");
                    return map;
                }
            }else{
				/*//此小塾为试用的
				if (conchDerver.getUseType() == 2) {
					*//*ResponseEntity responseEntity = new ResponseEntity();
					if (conchCommonService.conchTryServiceOperate(responseEntity, userId, derver, conchDerver.getUseDays())) {
						map.put("stat", "-1");
						map.put("mgs", responseEntity.getMsg());
						return map;
					}*//*
					conchCommonService.giveBindConchZybServiceV1(vipId, conchDerver.getUseDays());
				} else if (conchDerver.getUseType() == 3) {
					//永久的小塾，每绑定一次送10年
					//libVipServiceService.saveLibVipServiceV2("S003", "C004", vipId, new Date(), 120, "zyb");
				}*/
                //给对应服务
                //conchCommonService.giveBindConchZybServiceV2(vipId, conchDerver.getUseDays(), conchDerver.getUseType());
                conchCommonService.giveBindConchZybServiceV3(vipId, conchDerver);

                LibVip libVip =vipService.getById(vipId);
                libVip.setActivateTime(new Date());
                libVip.setDerver(derver);

                //推送贝壳消息，创建用户
                String derUserId = libVip.getChildUserId();
                if(StringUtils.isBlank(derUserId)){
                    User childUserInfo = new User();
                    childUserInfo.setId( IdWorker.generateId());
                    childUserInfo.setEasemobName(userService.createUniqueEasemobName());
                    //创建小孩环信账号
                    easemobService.createUserSingle(childUserInfo.getEasemobName(), null);
                    User parentUserInfo = userService.getById(libVip.getUserId());
                    if(StringUtils.isBlank(parentUserInfo.getEasemobName())) {
                        parentUserInfo.setEasemobName(userService.createUniqueEasemobName());
                        //创建家长环信账号
                        easemobService.createUserSingle(parentUserInfo.getEasemobName(), null);
                        userService.save(parentUserInfo);
                    }
                    //添加家长和小孩的好友关系
                    easemobService.addFriendSingle(parentUserInfo.getEasemobName(), childUserInfo.getEasemobName());

                    childUserInfo.setPassword("123456");
                    //需要创建小塾的账号密码
                    childUserInfo.setPwdSalt(PasswordUtil.generateSalt());
                    childUserInfo.setPassword(PasswordUtil.initPassword(childUserInfo.getPassword(), childUserInfo.getPwdSalt()));
                    childUserInfo.setCreateTime(new Date());
                    userService.save(childUserInfo);
                    libVip.setChildUserId(childUserInfo.getId());
                }else {
                    User childUserInfo = userService.getById(derUserId);
                    if(StringUtils.isBlank(childUserInfo.getEasemobName())) {
                        childUserInfo.setEasemobName(userService.createUniqueEasemobName());
                        userService.save(childUserInfo);
                        //创建小孩环信账号
                        easemobService.createUserSingle(childUserInfo.getEasemobName(), null);
                        User parentUserInfo = userService.getById(libVip.getUserId());
                        if(StringUtils.isBlank(parentUserInfo.getEasemobName())) {
                            parentUserInfo.setEasemobName(userService.createUniqueEasemobName());
                            //创建家长环信账号
                            easemobService.createUserSingle(parentUserInfo.getEasemobName(), null);
                            userService.save(parentUserInfo);
                        }
                        //添加家长和小孩的好友关系
                        easemobService.addFriendSingle(parentUserInfo.getEasemobName(), childUserInfo.getEasemobName());
                    }
                }
                conchDerver.setUserId(libVip.getChildUserId());
                conchDerver.setVipId(vipId);
                conchDerver.setUpdatedDate(new Date());
                logger.info("恭喜您绑定成功");




                int isService  =conchDerver.getIsService();
                if(isService==0){
                    String key="LOCATION_"+openId;
                    Location location1=tokenManager.get(key, Location.class);
                    tokenManager.set(key, location1,1);//设置1秒直接失效

                }


                conchCommonService.giveBindConchZybService(libVip.getId());

                vipService.save(libVip);
                this.save(conchDerver);
                tokenManager.set(DERVER+derver, conchDerver,1);


                TextCustom textCustom  =new TextCustom();
                textCustom.setMsgtype("text");
                textCustom.setTouser(openId);
                Text text = new  Text();
                text.setContent("恭喜您绑定成功");
                textCustom.setText(text);
                NewsUtil.send(tokenManager.getSSJAccessToken(), textCustom);

                /**
                 * 在微信自动回复的时候生成了token 以userId 开头的keys 数据，绑定后，直接给删除以userId开头数据
                 */
                tokenManager.batchDel(userId+"*");

                //推送绑定成功消息给小塾
                Map<String,Object> map1 = new HashMap<String,Object>();
                map1.put("type", "BIND");
                map1.put("time", new Date());
                map1.put("data", "");
                String content = JSON.toJSONString(map1);
                sconXingeService.asynPushThreadTask(derver, vipId,1,content, PushConstants.PUSH_OTHER);
                map.put("stat", "1");
                map.put("mgs", "恭喜您绑定成功");
                return map;
            }
        }else{
            map.put("stat", "-1");
            map.put("mgs", "设备不存在");
            return map;
        }
    }

    @Override
    public String findByDerverBinding(String derver, String userId) {
        ConchDerver  conchDerver=this.findByDerver(derver);
        if(conchDerver !=null){
            logger.info("derver="+derver);
            String derVipId = conchDerver.getVipId();
            logger.info("derVipId=" + derVipId);
            if (StringUtil.isNotBlank(derVipId)) {
                LibVip libVip = vipService.getById(derVipId);
                if (userId.equals(libVip.getUserId())) {
                    logger.info("您已经绑定该设备，无需重复绑定");
                    return "您已经绑定该设备，无需重复绑定";
                }
                logger.info("设备已被其他用户绑定");
                return "该设备已被其他用户绑定";
            }
            //如果是试用小塾，需要判断是否还可以再绑定(此业务废弃！！！现有业务为：满足对应条件绑定试用小塾送相应时长的服务)
			/*if (conchDerver.getUseType() == 2) {
				//用户试用小塾记录
				ConchDerverUseRecord useRecord = conchDerverUseRecordService.findByUserIdAndDerver(userId, derver);
				if (useRecord != null) {
					//检验是否在有效试用期内
					if (!DateHelper.compareTwoDate(new Date(), useRecord.getEndTime())) {
                        //tokenManager.setString("sharingschool" + derver, "1", 5);
						logger.info("此小塾相机试用已到期，不能再次绑定");
						return "此小塾相机试用已到期，不能再次绑定";
					}
				}
			}*/
            return "1";
        }
        return "该设备不存在!";
    }

    @Override
    public ConchDerver findByDerver(String derver) {
        return conchDerverDao.findByDerver(derver);
    }

    @Override
    public ResponseEntity untyingParents(String derver) {
        ResponseEntity responseEntity = new ResponseEntity();
        logger.info("贝壳开始解绑设备号:{}", derver);
        ConchDerver conchDerver = this.findByDerver(derver);
        if(conchDerver!=null){
            String vipId = conchDerver.getVipId();
            if(vipId!=null){
                LibVip  libVip =vipService.getById(vipId);
                if(libVip !=null){
                    logger.info("贝壳开始解绑设备号核对成功");
                    logger.info(JSON.toJSONString(conchDerver));
                    conchDerverDao.updateByDerver(derver);
                    vipService.updateVipByVipId(vipId);//解除用户关系（会员为空，服务也为空了）
                    //userService.delete(conchDerver.getUserId());//删除小孩的身份。
                    libVipServiceService.updateVipServiceByVipId(vipId);//服务改为无效
                    //推送解绑消息
                    //推送解绑绑定成功消息给小塾
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("type", "BIND");
                    map.put("time", new Date());
                    map.put("data", "{}");
                    String content = JSON.toJSONString(map);
                    sconXingeService.asynPushThreadTask(derver, vipId,1,content,PushConstants.PUSH_OTHER);
                    //清除贝壳accessToken
                    String token = tokenManager.getToken(conchDerver.getUserId(),"APP");
                    if(token!=null){
                        tokenManager.removeToken(token,"APP");
                    }
                    //清除贝壳设备信息缓存
                    tokenManager.delString(DERVER+derver);
                    //是否删除用户关系
                    responseEntity.success("解绑成功");
                }else{
                    responseEntity.failure("该设备绑定关系不存在！");
                }
            }else{
                responseEntity.failure("该设备绑定关系不存在！");
            }
        }else{
            responseEntity.failure("该设备不存在！");
        }
        return responseEntity;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ConchDerver findByUserId(String userId) {
        return conchDerverDao.findByUserId(userId);
    }
}
