package com.yihu.jw.wechat.service;

import com.yihu.jw.entity.base.wx.JsApiTicket;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.hospital.prescription.service.entrance.TnyyEntranceService;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.jw.wechat.dao.JsapiTicketDao;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.dao.WxAccessTokenDao;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.network.HttpUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.*;

/**
 * Created by Administrator on 2017/5/18
 */
@Service
public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAccessTokenDao> {


    private Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);

    @Autowired
    private WxAccessTokenDao wxAccessTokenDao;

    @Autowired
    private WechatDao wechatDao;

    @Autowired
    private JsapiTicketDao jsapiTicketDao;
    @Autowired
    private TnyyEntranceService tnyyEntranceService;


    public WxWechatDO getWxInfo(String wxId){
        return wechatDao.findOne(wxId);
    }
    /**
     * 根据原始id查找
     * @param appOriginId
     * @return
     */
    public WxAccessTokenDO getWxAccessTokenByOriginId(String appOriginId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findByAppOriginId(appOriginId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wxWechat.getId());
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            /*String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result = HttpUtil.sendGet(token_url, params);*/
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return :"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wxWechat.getId());
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * wechatId 删除无效 wechatId
     * @param wechatId
     */
    @Transactional
    public void deleteByWechatId(String wechatId){
        wxAccessTokenDao.deleteByWechatId(wechatId);
    }
    
    /**
     * 过期后删掉accesstoken,  重新获取
     * @param wechatId
     * @return
     */
    @Transactional
    public String updateAccessToken(String wechatId){
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAccessTokenDao.save(newaccessToken);
                return token;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public WxAccessTokenDO getWxAccessTokenById(String wechatId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            if (wechatId.equalsIgnoreCase("sd_tnzyy_wx")){
                return  getAccessTokenById(wechatId);
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 泰安获取token
     * @param wechatId
     * @return
     */
    public WxAccessTokenDO getAccessTokenById(String wechatId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            com.alibaba.fastjson.JSONObject json = tnyyEntranceService.getAccessToken();
            if (json.containsKey("AccessToken")) {
                String token = json.get("AccessToken").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(7200);
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取凭证
     * @param accId 微信原始id
     * @return
     */
    public Iterable<JsApiTicket> findJsapiTicket(String accId) {
        return jsapiTicketDao.findJsapiTicket(accId);
    }


    public void delJsapiTicket(JsApiTicket jsApiTicket) {
        jsapiTicketDao.delete(jsApiTicket);
    }

    /**
     * 添加JsapiTicket
     */
    public void addJsapiTicket(JsApiTicket jsApiTicket) {
        jsApiTicket.setAdd_timestamp(System.currentTimeMillis());
        jsApiTicket.setCzrq(new Date());
        jsapiTicketDao.save(jsApiTicket);
    }
}
