package com.yihu.jw.wechat.service;

import com.yihu.jw.entity.base.wx.JsApiTicket;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.HcyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.TnyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.wechat.dao.WechatDao;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WechatInfoService {

    @Autowired
    private WechatDao wechatDao;
    
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;
    @Autowired
    private TnyyEntranceService tnyyEntranceService;
    @Autowired
    private HcyyEntranceService hcyyEntranceService;

    /**
     * 通过code获取判断openid
     *
     * @param code
     * @return
     */
    public String getOpenidByCode(String code,String appId,String appSecret) throws Exception {
        String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String params = "appid=" + appId + "&secret=" +appSecret+ "&code=" + code + "&grant_type=authorization_code";
        String result = HttpUtil.sendGet(token_url, params);
        System.out.println("getOpenidByCode:"+result);
        JSONObject json = new JSONObject(result);
        if (json.has("openid")) {
            return json.get("openid").toString();
        }else{
            throw new Exception(result);
        }
    }

    /**
     * 通过code获取判断openid
     *
     * @param code
     * @return
     */
    public String getOpenidByCode(String code,String wxId) throws Exception {
        //通过wxId获取appId和appSecret
        WxWechatDO wxWechatDO = wechatDao.findById(wxId);
        return getOpenidByCode(code,wxWechatDO.getAppId(),wxWechatDO.getAppSecret());
    }
    
    /**
     * 获取微信的jsapi_ticket
     *
     * @return
     */
    public String getJsapi_ticketByToken(String wxId) throws Exception {
        try {
            System.out.println("getJsapi_ticketByToken="+wxId);
            Iterable<JsApiTicket> jsapiTickets = null;
            WxWechatDO wxWechat = null;
            
            //中山医院互联网医院
            if("xm_zsyy_wx".equals(wxId) || "xm_xzzx_wx".equals(wxId) || "xm_ykyy_wx".equals(wxId)||"xm_hcyy_wx".equals(wxId)){
                jsapiTickets = wxAccessTokenService.findJsapiTicket(wxId);
            }else{
                wxWechat = wxAccessTokenService.getWxInfo(wxId);
                jsapiTickets = wxAccessTokenService.findJsapiTicket(wxWechat.getAppOriginId());
            }
            
            if (jsapiTickets != null) {
                for (JsApiTicket jsApiTicket : jsapiTickets) {
                    if ((System.currentTimeMillis() - jsApiTicket.getAdd_timestamp()) < (jsApiTicket.getExpires_in() * 1000)) {
                        return jsApiTicket.getJsapi_ticket();
                    } else {
                        wxAccessTokenService.delJsapiTicket(jsApiTicket);
                        break;
                    }
                }
            }
            String token = "";
            
            //中山医院互联网医院
            if("xm_zsyy_wx".equals(wxId)) {
                String response = entranceService.getAccessToken("100033");
                net.sf.json.JSONObject object1 = net.sf.json.JSONObject.fromObject(response);
                if (null != object1&&null!=object1.get("respCode") && "00".equals(object1.get("respCode"))) {
                    token  = object1.getJSONObject("respEntity").getString("access_token");
                } else {
                    throw new Exception("获取ACCESSTOKEN失败");
                }

            }else if("xm_xzzx_wx".equals(wxId)){
                token = xzzxEntranceService.getXzToken();
            }else if("xm_hcyy_wx".equals(wxId)){
                token = hcyyEntranceService.getHcToken();
            }else if("sd_tnzyy_wx".equals(wxId)){
                com.alibaba.fastjson.JSONObject jsonObject = tnyyEntranceService.getAccessToken();
                if (jsonObject.getString("ResultCode")!=null&&jsonObject.getString("ResultCode").equalsIgnoreCase("0")){
                    token = jsonObject.getString("AccessToken");
                }else {
                    throw new Exception("获取ACCESSTOKEN失败");
                }
            }else{
                token = wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
            }
            System.out.println("getticket_token:"+token);
            if (token != null) {
                String token_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
                String params = "access_token=" + token + "&type=jsapi";
                String result = HttpUtil.sendGet(token_url, params);
                System.out.println("result:"+result);
                JSONObject json = new JSONObject(result);
                System.out.println("getticket:"+result);
                if (json.has("ticket")) {
                    String ticket = json.get("ticket").toString();
                    String expires_in = json.get("expires_in").toString();
                    JsApiTicket newJsApiTicket = new JsApiTicket();
                    newJsApiTicket.setJsapi_ticket(ticket);
                    newJsApiTicket.setExpires_in(Long.parseLong(expires_in));
                    if("xm_zsyy_wx".equals(wxId) || "xm_xzzx_wx".equals(wxId) || "xm_ykyy_wx".equals(wxId)||"xm_hcyy_wx".equals(wxId)){
                        newJsApiTicket.setAcc_id(wxId);
                    }else{
                        newJsApiTicket.setAcc_id(wxWechat.getAppOriginId());
                    }
                    
                    wxAccessTokenService.addJsapiTicket(newJsApiTicket);
                    return ticket;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new Exception(e.getMessage());
        }
    }
}
