SmartUserRelationServiceImpl.java 7.25 KB
package com.glsx.smart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.HttpUtils;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.smart.constant.Constants;
import com.glsx.smart.dao.entity.SmartUserChannel;
import com.glsx.smart.dao.entity.SmartUserRelation;
import com.glsx.smart.dao.mapper.SmartUserChannelMapper;
import com.glsx.smart.dao.mapper.SmartUserRelationMapper;
import com.glsx.smart.exception.BusinessException;
import com.glsx.smart.exception.ResultEnum;
import com.glsx.smart.service.SmartUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Description:
 * <p>Project: chejia-smart
 *
 * @author wbh
 * @date 2021-03-15
 */
@Slf4j
@Service
public class SmartUserRelationServiceImpl implements SmartUserRelationService {

    @Value("${device_remote_url}")
    private String remoteUrl;

    @Value("${tuya_user_sync}")
    private String tuyaSyncUser;

    @Value("${aqara_user_sync}")
    private String aqaraSyncUser;

    @Resource
    private SmartUserChannelMapper userChannelMapper;

    @Resource
    private SmartUserRelationMapper relationMapper;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return relationMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insertOrUpdate(SmartUserRelation userRelation) {
        if (userRelation.getId() == null) {
            return relationMapper.insertSelective(userRelation);
        } else {
            SmartUserRelation record = relationMapper.selectByPrimaryKey(
                    userRelation.getId());
            if (record != null) {
                return relationMapper.updateByPrimaryKeySelective(userRelation);
            } else {
                throw new BusinessException(ResultEnum.ID_NOT_FOUND);
            }
        }
    }

    @Override
    public synchronized Long insertSelective(SmartUserRelation record) {
        SmartUserRelation request = new SmartUserRelation();
        request.setPhone(record.getPhone());
        request.setChannel(record.getChannel());  //涂鸦
        SmartUserRelation user = relationMapper.getSingle(request);
        if(user != null && user.getId() > 0L){
            record.setId(user.getId());
            relationMapper.updateByPrimaryKeySelective(record);
        } else{
            relationMapper.insertSelective(record);
        }
        return record.getId();
    }

    @Override
    public SmartUserRelation getSingle(SmartUserRelation record) {
        SmartUserRelation userRelation = relationMapper.getSingle(record);
        if(userRelation != null){
            userRelation.setChannelList(userChannelMapper.selectByUserId(userRelation.getId()));
        }
        return userRelation;
    }

    @Override
    public SmartUserRelation selectByPrimaryKey(Long id) {
        return relationMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(SmartUserRelation record) {
        return relationMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateBatchSelective(List<SmartUserRelation> list) {
        return relationMapper.updateBatchSelective(list);
    }

    @Override
    public int batchInsert(List<SmartUserRelation> list) {
        return relationMapper.batchInsert(list);
    }

    @Override
    public String syncTuYaUser(String mobile, String password, Long userId) {
        String thirdId = this.syncTuYaUser(mobile, password);
        if(thirdId != null){
            this.saveUserChannel(userId, thirdId,Constants.USER_CHANNEL_TUYA);
        }
        return thirdId;
    }

    @Override
    public String syncAqaraUser(String mobile, Long userId) {
        Map<String, String> returnMap = this.syncAqaraUserCore(mobile);
        String thirdId = null;
        if(returnMap != null){
            //保存绿米渠道用户数据
            thirdId = returnMap.get("openId");
            this.saveUserChannel(userId, thirdId,Constants.USER_CHANNEL_AQARA);
        }
        return thirdId;
    }

    /**
     * 保存用户渠道数据
     * @param userId
     * @param thirdId
     * @param channel
     */
    private void saveUserChannel(Long userId, String thirdId, Byte channel){
        SmartUserChannel userChannel = new SmartUserChannel();
        userChannel.setUserId(userId);
        userChannel.setCreateTime(new Date());
        userChannel.setThirdId(thirdId);
        userChannel.setChannel(channel);
        userChannelMapper.insertSelective(userChannel);
    }

    /**
     * 同步用户到涂鸦
     * @param mobile
     * @param password
     * @return
     */
    private String syncTuYaUser(String mobile, String password){
        Map<String, String> object = new HashMap<>();
        object.put("country_code", "86");
        object.put("username", mobile);
        object.put("username_type", "1");
        object.put("password", password);
        try {
            StringBuffer syncUserUrl = new StringBuffer(remoteUrl);
            syncUserUrl.append(tuyaSyncUser);
            log.info("请求注册涂鸦平台接口地址:{},参数:{}", syncUserUrl.toString(), JSON.toJSONString(object));
            String result = HttpUtils.post(syncUserUrl.toString(), JSON.toJSONString(object));
            log.info("注册涂鸦平台返回结果:{}", result);
            if (!StringUtils.isEmpty(result)) {
                JSONObject json = JSON.parseObject(result);
                if (json.getInteger("code").equals(200)) {
                    return json.getJSONObject("message").getString("uid");
                }
            }
        } catch (Exception e) {
            log.error("同步涂鸦平台失败:{}", e);
        }
        return null;
    }

    /**
     * 同步用户到绿米
     * @param mobile
     * @return
     */
    public Map<String, String> syncAqaraUserCore(String mobile){
        Map<String, String> object = new HashMap<>();
        object.put("account", mobile);
        object.put("password", mobile + "abc");  //默认密码涂鸦端
        try {
            StringBuffer syncUserUrl = new StringBuffer(remoteUrl);
            syncUserUrl.append(aqaraSyncUser);
            log.info("请求绿米平台用户接口地址:{},参数:{}", syncUserUrl.toString(), JSON.toJSONString(object));
            String result = HttpUtils.post(syncUserUrl.toString(), JSON.toJSONString(object));
            log.info("请求绿米平台用户返回结果:{}", result);
            if (!StringUtils.isEmpty(result)) {
                JSONObject json = JSON.parseObject(result);
                if (json.getInteger("code").equals(200)) {
                    Map<String, String> returnMap = new HashMap<>();
                    JSONObject message = json.getJSONObject("message");
                    returnMap.put("openId", message.getString("openId"));
                    returnMap.put("accessToken", message.getString("accessToken"));
                    return returnMap;
                }
            }
        } catch (Exception e) {
            log.error("请求绿米平台用户失败:{}", e);
        }
        return null;
    }
}