package com.yihu.jw.oauth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.auth.OauthRsaKeyDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.RSAEncrypt;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.utils.security.MD5;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Trick on 2020/3/10.
 */
@Service
@Transactional
public class OauthSsoService {

    Logger logger = LoggerFactory.getLogger(OauthSsoService.class);

    @Autowired
    private OauthRsaKeyDao rsaKeyDao;

    @Autowired
    private BasePatientDao basePatientDao;

    @Autowired
    private BasePatientWechatDao basePatientWechatDao;


    public static String getAuthCode()throws Exception{

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","王志南");
        jsonObject.put("idcard","350524199405230613");
        jsonObject.put("mobile","15426852352");
        jsonObject.put("openid","oJ0gPsxhKj1Z6JtkKBjJk0VQD2YE");
        String authCode = jsonObject.toJSONString();
//        logger.info("authCode:"+authCode);

//        String publicKey = getSsoPublic("1", "appid");

        String jm = RSAEncrypt.encrypt(authCode,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQZep11XbI4r7P/VFDjGj00vGJoYpUQpk36MVGo1aXjzWtjfosMM4KdQSaYVMfuctnJIBUiAUHPyH52SLo4ZfDG5p1DBjaeXMWiLH2IIsxF3Xo+aHSjHyS0N12w2ITSW/gjUYXGlUX9uzyl2cHl9rU1nIjm6PYfMdXJbTH1a3fOwIDAQAB");
        System.out.print("12211222==="+jm);
        return jm;
    }

    public String getSsoPublic(String code,String appId)throws Exception{
        /**
         * 删除之前秘钥
         */
        List<OauthRsaKeyDO> oauthRsaKeyDOs = rsaKeyDao.findByCodeAndAppId(code,appId);
        if(oauthRsaKeyDOs!=null&&oauthRsaKeyDOs.size()>0){
            rsaKeyDao.delete(oauthRsaKeyDOs);
        }
        /**
         * 生成新的秘钥
         */
        OauthRsaKeyDO oauthRsaKeyDO = new OauthRsaKeyDO();
        Map<Integer, String> key  = RSAEncrypt.genKeyPair();
        oauthRsaKeyDO.setCode(code);
        oauthRsaKeyDO.setAppId(appId);
        oauthRsaKeyDO.setPublicKey(key.get(0));
        oauthRsaKeyDO.setPrivateKey(key.get(1));
        oauthRsaKeyDO.setCreateTime(new Date());
        rsaKeyDao.save(oauthRsaKeyDO);
        return oauthRsaKeyDO.getPublicKey();
    }

    public Map<String,Object> savePatient(String code,String appId,String authCode)throws Exception{
        Map<String,Object> rs = new HashedMap();

        try{
            String jsonStr = decrypt(code,appId,authCode);

            JSONObject info = JSON.parseObject(jsonStr);

            String name = info.getString("name");
            if(StringUtils.isBlank(name)){
                rs.put("code",-1);
                rs.put("mes","用户姓名获取失败");
                return rs;
            }
            String idcard = info.getString("idcard");
            if(StringUtils.isBlank(idcard)){
                rs.put("code",-2);
                rs.put("mes","身份证获取失败");
                return rs;
            }
            String mobile = info.getString("mobile");
            if(StringUtils.isBlank(mobile)){
                rs.put("code",-3);
                rs.put("mes","手机号获取失败");
                return rs;
            }
            String openid = info.getString("openid");
            if(StringUtils.isBlank(openid)){
                rs.put("code",-4);
                rs.put("mes","openid获取失败");
                return rs;
            }

            if(StringUtils.isNotBlank(idcard)){

                BasePatientDO basePatientDO = basePatientDao.findByIdcardAndDel(idcard,"1");
                if(basePatientDO!=null){

                    rs.put("code",1);
                    rs.put("mes","获取居民信息成功");
                    rs.put("patient",basePatientDO);
                    return rs;
                }

                BasePatientDO patient = new BasePatientDO();

                String salt = UUID.randomUUID().toString().substring(0,5);

                String pw = idcard.substring(idcard.length()-6);

                patient.setIdcard(idcard);
                patient.setName(name);
                patient.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                patient.setSalt(salt);
                patient.setMobile(mobile);
                patient.setDel("1");
                patient.setEnabled(1);
                patient.setLocked(0);
                patient.setCreateTime(new Date());
                patient.setUpdateTime(new Date());
                patient.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));
                patient.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(idcard)));

                BasePatientDO temp = basePatientDao.save(patient);

                //保存openid
                BasePatientWechatDo wechatDo = new BasePatientWechatDo();
                wechatDo.setOpenid(openid);
                wechatDo.setPatientId(temp.getId());
                wechatDo.setWechatId(appId);
                basePatientWechatDao.save(wechatDo);

                rs.put("code",1);
                rs.put("mes","获取居民信息成功");
                rs.put("patient",temp);

                return rs;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        rs.put("code",-5);
        rs.put("mes","居民信息同步失败");
        return rs;
    }

    public String decrypt(String code,String appId,String authCode)throws Exception{
        List<OauthRsaKeyDO> oauthRsaKeyDOs = rsaKeyDao.findByCodeAndAppId(code,appId);

        OauthRsaKeyDO oauthRsaKeyDO = oauthRsaKeyDOs.get(0);
        String str = RSAEncrypt.decrypt(authCode,oauthRsaKeyDO.getPrivateKey());
        logger.info("decrypt : "+str);
        return  str;
    }
    public static void main(String ag[])throws Exception{

        String str = RSAEncrypt.decrypt(getAuthCode(),"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJBl6nXVdsjivs/9UUOMaPTS8YmhilRCmTfoxUajVpePNa2N+iwwzgp1BJphUx+5y2ckgFSIBQc/IfnZIujhl8MbmnUMGNp5cxaIsfYgizEXdej5odKMfJLQ3XbDYhNJb+CNRhcaVRf27PKXZweX2tTWciObo9h8x1cltMfVrd87AgMBAAECgYBUBVl2Ey25GmcZMzcz7OGtg4jUItEQ0mfBJoqT3bsnGUeMo05spEFfyFNTWUo67aszawPZLARxAQVOElDD3XCmSDLs3vTJW2jbLQQSe33dPshEI/yzXaSloj86zut/9X84rDcHC19VIe55MNkXIUM6d65p5lAgB27/0WRvGsI58QJBAP52ZNtNQGBWVZvm/SdfZ0FgWFnGmleixrxgGNFqboY+ZLn3erlupWPe1QUpv2/0v+kkULrxNNgr9uY1qXMcW90CQQCRRUXX0j7yA213u9FNKfUeUjt8f8bwhifsclLM4bnVy1XAigAiLuf3QjBRqCRpnkeNNK3UX0y13cY0fDqLpOH3AkAL9HYCk5uNqyC0hWKpYeMRADzGYv1HVr9thDpGRHDS38WNsyHR6m/cxFBPwMlcsiv+ARXF4qUv7sjXwfenD9MFAkBYY9HvU5nBH5zHsZvUW6ctX9OaGRUu3DIGiDkhOGceUq5GjLEwG2JA7CECTlB5gzj+DgOGqMXAEsS6wqvMs/JZAkBozjFD92ANzWwDnZCR2XfdvkY8ogIeU4u3Ri5z6QG9QEkc3ucB6zJyz0bXEbRqf8qlWV90iXAFFxvaRJRR00my");
        System.out.println("decrypt : "+str);

    }

}
