package com.yizhi.application.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.site.application.enums.PortalEnum;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.ras.RSAUtil;
import com.yizhi.wechat.application.feign.PublicConfigClient;
import com.yizhi.wechat.application.feign.WeiXinClient;
import com.yizhi.wechat.application.vo.wechat.*;
import com.yizhi.wechat.application.vo.wechat.domain.PublicPlatformConfigVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;


/**
 * 微信登录对接
 *
 * @author lilingye
 * @since 2018-5-10 13:48:46
 */
@RestController
@Api(tags = "微信登录接口")
@RequestMapping("public/wechat")
public class WechatController {

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatController.class);
    @Autowired
    private WeiXinClient weiXinClient;
    @Autowired
    private PublicConfigClient publicConfigClient;
//    @Autowired
//    private SZWeiXinClient szWeiXinClient;

    @Autowired
    private AccountClient accountClient;

    /**
     * 获取微信服务号用户的信息
     *
     * @param appid 应用APPID
     * @param code  调用微信api接口获取的code值
     */
    @ApiOperation(value = "获取微信公众号用户信息", notes = "获取微信公众号用户信息", response = WUserInfoVO.class)
    @RequestMapping(value = "/get/wechatuser", method = RequestMethod.GET)
    public Response<WUserInfoVO> getWUserInfo(
            @ApiParam(name = "companyCode", value = "公司code")  @RequestParam(value = "companyCode",required = false) String companyCode,
            @ApiParam(name = "siteCode", value = "站点cdoe")  @RequestParam(value = "siteCode",required = false) String siteCode,
            @ApiParam(name = "code", value = "调用微信接口获取code") @RequestParam(name = "code") String code,
            @ApiParam(name = "appid", value = "应用的APPID") @RequestParam(name = "appid", required = true) String appid,
            @ApiParam(name = "agentId", value = "机构Id") @RequestParam(name = "agentId", required = false) String agentId,
            @ApiParam(name = "source", value = "source") @RequestParam(name = "source", required = false) Integer source,
            @ApiParam(name = "是否加密 true；加密") @RequestParam(name = "isEncrypt", required = false,defaultValue = "false") Boolean isEncrypt) throws InvocationTargetException, IllegalAccessException {



        LOGGER.info("============================================");
        LOGGER.info("参数code{}", code);
        LOGGER.info("参数appid{}", appid);
        LOGGER.info("参数isEncrypt{}", isEncrypt);
        LOGGER.info("============="+JSON.toJSON(new Date())+"================");
        // 获取微信用户的信息
        RequestContext context = ContextHolder.get();
        LOGGER.info("getWUserInfo上下文获取CompanyCode{}" + context.getCompanyCode());
        LOGGER.info("getWUserInfo参数获取CompanyCode{}" + companyCode);
        /**if("wl44cff5b45f".equals(appid)){
            com.yizhi.szwechat.application.vo.szwechat.WechatUserInfoVO szUserInfo = szWeiXinClient.getUserInfo(code, appid, agentId, source);
            LOGGER.info("苏州银行私有微信对接返回的信息:{}", JSON.toJSON(szUserInfo));
            WechatUserInfoVO szWechatUserInfoVO = new WechatUserInfoVO();
            szWechatUserInfoVO.setCode(szUserInfo.getCode());
            szWechatUserInfoVO.setMsg(szUserInfo.getMsg());
            com.yizhi.szwechat.application.vo.szwechat.WUserInfoVO SZWUserInfoVO = szUserInfo.getWUserInfoVO();
            com.yizhi.wechat.application.vo.wechat.WUserInfoVO destWUserInfoVO = new WUserInfoVO();
            org.apache.commons.beanutils.BeanUtils.copyProperties(destWUserInfoVO,SZWUserInfoVO);
            szWechatUserInfoVO.setWUserInfoVO(destWUserInfoVO);
            if (szWechatUserInfoVO.getWUserInfoVO() != null) {
                LOGGER.info("苏州银行私有微信接口正常返回");
                if (isEncrypt) {
                    String openId = szWechatUserInfoVO.getWUserInfoVO().getWechatuserid();
                    try {
                        String encryptOpenId = RSAUtil.encrypt(openId, RSAUtil.PUBLIC_KEY);
                        szWechatUserInfoVO.getWUserInfoVO().setWechatuserid(encryptOpenId);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOGGER.error("苏州银行私有微信加密过程异常：" + e);
                    }
                }
                return Response.ok(szWechatUserInfoVO.getWUserInfoVO());
            } else {
                if (Constants.DEL_FLAG == szWechatUserInfoVO.getCode()) {
                    LOGGER.info("苏州银行私有微信返回的异常" + szWechatUserInfoVO.getCode());
                    return Response.fail(szWechatUserInfoVO.getMsg());
                } else if (szWechatUserInfoVO.getCode() == 5) {
                    LOGGER.info("苏州银行私有微信返回的异常" + szWechatUserInfoVO.getCode());
                    return Response.fail(szWechatUserInfoVO.getMsg());
                } else {
                    return Response.fail();
                }
            }
        }
         */
        WechatUserInfoVO userInfoVO = weiXinClient.getUserInfo(code, appid, agentId,source);
        LOGGER.info("返回的信息:{}", JSON.toJSON(userInfoVO));
        LOGGER.info("============================================");
        if (userInfoVO.getWUserInfoVO() != null) {
            LOGGER.info("接口正常返回");
            if (isEncrypt) {
                String openId = userInfoVO.getWUserInfoVO().getWechatuserid();
                try {
                    String encryptOpenId = RSAUtil.encrypt(openId, RSAUtil.PUBLIC_KEY);
                    userInfoVO.getWUserInfoVO().setWechatuserid(encryptOpenId);
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.error("加密过程异常：" + e);
                }
            }
            return Response.ok(userInfoVO.getWUserInfoVO());
        } else {
            if (Constants.DEL_FLAG == userInfoVO.getCode()) {
                LOGGER.info("返回的异常" + userInfoVO.getCode());
                return Response.fail(userInfoVO.getMsg());
            } else if (userInfoVO.getCode() == 5) {
                LOGGER.info("返回的异常" + userInfoVO.getCode());
                return Response.fail(userInfoVO.getMsg());
            } else {
                return Response.fail();
            }
        }
    }

    @ApiOperation(value = "获取签名", notes = "获取签名")
    @RequestMapping(value = "/get/signature", method = RequestMethod.GET)
    public Response<SignatureVO> getTicket(
            @ApiParam(name = "appid", value = "appid") @RequestParam(name = "appid") String appid,
            @ApiParam(name = "url", value = "当前url") @RequestParam(name = "url") String url,
            @ApiParam(name = "agentId", value = "机构Id") @RequestParam(name = "agentId",required = false) String agentId
    ) {
        if ("".equals(appid.trim()) || "null".equals(appid.trim()) || appid == null) {
            return Response.fail("接口传参不完整!!");
        } else {
            SignatureVO signatureVO = null;
            try {
                signatureVO = weiXinClient.getSignature(appid.trim(), url, agentId.trim());
                LOGGER.info("签名结果：{}",JSON.toJSON(signatureVO));
            } catch (Exception e) {
                LOGGER.info("当前签名异常：{}",e.getMessage());
            }

            if (signatureVO != null) {
                return Response.ok(signatureVO);
            } else {
                return Response.fail();
            }
        }
    }


    @ApiOperation(value = "获取公众号配置新", notes = "获取公众号配置信息")
    @RequestMapping(value = "/get/getconfiginfo", method = RequestMethod.GET)
    public Response<String> getPublicPlatformInfo(
            @ApiParam(name = "siteCode", value = "siteCode") @RequestParam(name = "siteCode") String siteCode,
            @ApiParam(name = "companyCode", value = "companyCode") @RequestParam(name = "companyCode") String companyCode

    ) {
        PublicPlatformConfigVo ppc = new PublicPlatformConfigVo();
        ppc.setSiteCode(siteCode.trim());
        ppc.setCompanyCode(companyCode.trim());
        ppc.setIsDeleted(PortalEnum.ZERO.ordinal());
        PublicPlatformConfigVo config;
        try {
            config = publicConfigClient.findPublicPlatformConfig(ppc);
            PublicPlatformConfigVO publicPlatformConfigVO = new PublicPlatformConfigVO();

            LOGGER.info("配置信息{}", config);

            BeanUtils.copyProperties(config, publicPlatformConfigVO);
            String appId = config.getAppId();
            appId = RSAUtil.encrypt(appId, RSAUtil.PUBLIC_KEY);
            String secret = config.getSecret();
            secret = RSAUtil.encrypt(secret, RSAUtil.PUBLIC_KEY);
            LOGGER.info("appId{}", appId);
            LOGGER.info("配置信息secret{}", secret);
            publicPlatformConfigVO.setAppId(appId);
            publicPlatformConfigVO.setSecret(secret);
            LOGGER.info("-返回信息---" + publicPlatformConfigVO);
            return Response.ok(publicPlatformConfigVO);

        } catch (Exception e) {
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "解绑微信", notes = "解绑微信")
    @RequestMapping(value = "/unbind", method = RequestMethod.GET)
    public Response<WUserInfoVO> unbindWeChatUser(@ApiParam(name = "code", value = "调用微信接口获取code") @RequestParam(name = "code", required = true) String code,
                                              @ApiParam(name = "appId", value = "应用的APPID") @RequestParam(name = "appId", required = true) String appId,
                                              @ApiParam(name = "agentId", value = "机构Id") @RequestParam(name = "agentId", required = false) String agentId) {

        if (StringUtils.isNotBlank(appId.trim())) {
            Boolean flag = weiXinClient.unbindAccount(code.trim(), appId.trim(), agentId.trim());
            if (flag) {
                return Response.ok();
            } else {
                return Response.fail("解绑失败！");
            }
        } else {
            return Response.fail("接口传参不完整!!");
        }
    }
}
