package com.liangjian.dataplatform.member.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liangjian.dataplatform.member.dao.secondary.WeixinUserInfoRepository;
import com.liangjian.dataplatform.member.entity.po.secondary.WeixinUserInfo;
import com.liangjian.dataplatform.member.service.IWeixinUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.*;
import java.util.Optional;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/14
 */
@Service
public class WeixinUserInfoService implements IWeixinUserInfoService {
    @Autowired
    private WeixinUserInfoRepository weixinUserInfoRepository;

//    @Value("${spring.datasource.secondary.url}")
    private String url = "jdbc:sqlserver://192.168.50.32:1433;databaseName=Mall";
//    @Value("${spring.datasource.secondary.username}")
    private String username = "sa";
//    @Value("${spring.datasource.secondary.password}")
    private String password = "saljhy!@#";

    @Value("${jwt-secret}")
    private String jwtSecret;

    private String encodeSecretPhone(String phone) {
        //这里的phone是明文的，而数据存的是密文的，所以先加密再查
        //但是，这个加密是在sqlserver里去做的，所以要架jdbc先拿到这个电话号码加密的密文
        String secretPhone = null;
        String encodeSql = String.format("select dbo.DesEncryptFixKey('123456','123456e10adc3949ba59abbe56e057f20f883e','%s')",phone);
        try(Connection conn = DriverManager.getConnection(url,username,password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(encodeSql)) {

            rs.next();
            secretPhone = rs.getString(1);
            return secretPhone;
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Optional<WeixinUserInfo> findByPhone(String phone) {
        String secretPhone = encodeSecretPhone(phone);
        return weixinUserInfoRepository.queryBySecretPhone(secretPhone);
    }

    @Override
    public Optional<WeixinUserInfo> findByOpenid(String openid) {
        return weixinUserInfoRepository.queryByOpenid(openid);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int addWeixinUserInfo(WeixinUserInfo userInfo, String phone) {
        Optional<WeixinUserInfo> opt = findByPhone(phone);
        if(opt.isPresent()) {
            WeixinUserInfo fromDb = opt.get();
            //有，说明已经有记录信息
            if(fromDb.getOpenid() == null || fromDb.getOpenid().isEmpty()) {
                //说明未绑定微信
                fromDb.setSubscribe(userInfo.getSubscribe());
                fromDb.setOpenid(userInfo.getOpenid());
                fromDb.setNickname(userInfo.getNickname());
                fromDb.setSex(userInfo.getSex());
                fromDb.setLanguage(userInfo.getLanguage());
                fromDb.setCity(userInfo.getCity());
                fromDb.setProvince(userInfo.getProvince());
                fromDb.setCountry(userInfo.getCountry());
                fromDb.setHeadimgurl(userInfo.getHeadimgurl());
                fromDb.setSubscribeTime(userInfo.getSubscribeTime());
                fromDb.setRemark(userInfo.getRemark());
                fromDb.setGroupid(userInfo.getGroupid());
                fromDb.setTagidList(userInfo.getTagidList());
                fromDb.setSubscribeScene(userInfo.getSubscribeScene());
                fromDb.setQrScene(userInfo.getQrScene());
                fromDb.setQrSceneStr(userInfo.getQrSceneStr());
                fromDb.setUnionid(userInfo.getUnionid());
                try {
                    weixinUserInfoRepository.save(fromDb);
                    return ADD_SUCCESS;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return ADD_ERROR;
                }
            } else {
                //说明已经绑定微信
                return HAS_EXIST;
            }
        } else {
            //无，说明没有会员信息，让前端跳转
            return NOT_USER_REGIS;
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean save(WeixinUserInfo userInfo) {
        if(userInfo.getId() == null) {
            return false;
        }

        try {
            weixinUserInfoRepository.save(userInfo);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    public Optional<String> encodeJwt(WeixinUserInfo userInfo, String remark) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String js = mapper.writeValueAsString(userInfo);
            Long signTime = System.currentTimeMillis();

            String token = JWT.create()
                    .withClaim("signTime", signTime)
                    .withClaim("remark",remark)
                    .withClaim("object",js)
                    .sign(Algorithm.HMAC256(jwtSecret));
            return Optional.of(token);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Optional.empty();
        }
    }

    @Override
    public String decodeStr(String str) {
        String res = "";
        String encodeSql = String.format("select dbo.DesDecryptFixKey('123456','123456e10adc3949ba59abbe56e057f20f883e','%s')", str);
        try(Connection conn = DriverManager.getConnection(url,username,password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(encodeSql)) {

            rs.next();
            res = rs.getString(1);
            return res;
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }
}
