package com.platform.yijia.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.platform.yijia.config.YiJiaRequest;
import com.platform.yijia.param.request.PayInfoRequest;
import com.platform.yijia.param.request.RechargeBalance;
import com.platform.yijia.pojo.CustomerCardUseRecord;
import com.platform.yijia.pojo.Oil;
import com.platform.yijia.pojo.PayOrder;
import com.platform.yijia.service.*;
import com.platform.yijia.utils.CodeMsg;
import com.platform.yijia.utils.ResultData;
import com.platform.yijia.utils.weixinapp.WxPushUtil;
import com.saobei.open.sdk.DefaultSaobeiApiClient;
import com.saobei.open.sdk.SaobeiApiClient;
import com.saobei.open.sdk.model.requst.trade.SaobeiJsPayRequest;
import com.saobei.open.sdk.model.requst.trade.SaobeiMiniPayRequest;
import com.saobei.open.sdk.model.requst.trade.preauth.SaobeiPreAuthMiniPayRequest;
import com.saobei.open.sdk.model.response.trade.SaobeiJsPayResponse;
import com.saobei.open.sdk.model.response.trade.SaobeiMiniPayResponse;
import com.saobei.open.sdk.model.response.trade.preauth.SaobeiPreAuthMiniPayResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;


/*
 * <Title> SaoBeiPayController </Title>
 * <Description> 第三方扫呗支付 </Description>
 * @Author JK
 * @Date 2021年8月18日
 */

@Controller
@YiJiaRequest()
@CrossOrigin
public class SaoBeiPayController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(SaoBeiPayController.class);

    @Resource
    private PayOrderService payOrderService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private StationOilGunService stationOilGunService;
    @Resource
    private CustomerGradeServices customerGradeServices;
    @Resource
    private StationService stationService;
    @Resource
    private CustomerPointsService customerPointsService;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private  CustomerManagerService customerManagerService;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private SysDictDataService sysDictDataService;

    @Value("${yijia.path.global-prefix}")
    private String globalPrefix;
    @Value("${yijia.domainName}")
    private String domainName;

//    商户号:852107011000070
//    终端号：33336510
//    密钥(token)：dbea558077934b95a2f2adf57d278c40

    //测试
//    商户号码：852105942000011
//    终端号：18237172
//    密钥：2ef428f4f76c414282e831baea9e4b0e

    //智慧易加
//    商户号码：845104816000034
//    终端号：18241101
//    密钥：23570b46a955484d92038f6a18d2b9d6

//    public static final String PAY_VER = "110";         //版本号
//    public static final String KEY = "";                //机构秘钥
//    public static final String ACCESS_TOKEN = "2ef428f4f76c414282e831baea9e4b0e";       //支付秘钥
//    public static final String INST_NO = "";            //机构号
//    public static final String MERCHANT_NO = "852105942000011";         //商户号
//    public static final String TERMINAL_ID = "18237172";                //终端号


    /***
     * 公众号云闪付拉起支付
     * @param rechargeBalance
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/yunPayGzh"}, consumes = {"application/json"}, method = {RequestMethod.POST})
    @ResponseBody
    public String yunPayGzh(@RequestBody RechargeBalance rechargeBalance) throws Exception {
        //智慧易加
//    商户号码：845104816000034
//    终端号：18241101
//    密钥：23570b46a955484d92038f6a18d2b9d6
        Gson gson = new Gson();
        ResultData resultData = null;

        if(rechargeBalance !=null && StringUtils.isNotBlank(rechargeBalance.getAmt()) && StringUtils.isNotBlank(rechargeBalance.getOpenId())
                && StringUtils.isNotBlank(rechargeBalance.getUserType()) && rechargeBalance.getStationId() !=null && StringUtils.isNotBlank(rechargeBalance.getOrderNo())){
            String amt = rechargeBalance.getAmt();
            String openId = rechargeBalance.getOpenId();    //公众号的openId
            Integer stationId = rechargeBalance.getStationId();
            String userType = rechargeBalance.getUserType();
            String orderNo = rechargeBalance.getOrderNo();
            CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
            customerCardUseRecord.setOrderNo(orderNo);
            CustomerCardUseRecord cardRecordByOrderNo = electronicMembershipCardService.getCardRecordByOrderNo(customerCardUseRecord);
            if(cardRecordByOrderNo !=null ) {
                if (cardRecordByOrderNo.getStatus() != null && cardRecordByOrderNo.getStatus().equals("0")) {
                    Map<String, String> staPayChannelInfo = stationService.getStationAppIdAndAppSecret(stationId);
                    if(staPayChannelInfo !=null && staPayChannelInfo.containsKey("merchantNo") && staPayChannelInfo.containsKey("terminalId")
                        && staPayChannelInfo.containsKey("yunKey") && staPayChannelInfo.containsKey("gzhAppId")){
                        logger.info("==============================云闪付 公众号电子卡充值 拉起支付 ** 开始 **============================================");
                        //创建client
                        SaobeiApiClient<SaobeiJsPayRequest, SaobeiJsPayResponse> client = new DefaultSaobeiApiClient<>(staPayChannelInfo.get("yunKey"));
                        //创建requst
                        SaobeiJsPayRequest requst = new SaobeiJsPayRequest();
                        requst.setPay_ver("110");
                        requst.setPay_type("010");
                        requst.setService_id("012");
                        requst.setMerchant_no(staPayChannelInfo.get("merchantNo"));                 //商户号
                        requst.setTerminal_id(staPayChannelInfo.get("terminalId"));                 //终端号
                        requst.setTerminal_trace(cardRecordByOrderNo.getOrderNo());                 //订单号
                        requst.setTerminal_time(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));

                        BigDecimal totalFee = new BigDecimal(cardRecordByOrderNo.getAmt().toString()).multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_DOWN);
                        logger.info("该订单金额：" + cardRecordByOrderNo.getAmt().toString()+"; 拉起云闪付上送金额（单位：分)：" + totalFee.toString());
                        requst.setTotal_fee(totalFee.toString());
                        requst.setSub_appid(staPayChannelInfo.get("gzhAppId"));
                        requst.setOpen_id(openId);                      //oJR5R6r4EJhaORFcPap70r_mtFZo   //oRwjv4iHjSUgxNxOJOQ_60Ln7cno

                        Oil oil = new Oil();
                        oil.setOilsType(cardRecordByOrderNo.getCardOilsType());
                        if(cardRecordByOrderNo.getCardOilsType().equals("1") || cardRecordByOrderNo.getCardOilsType().equals("2")){
                            oil.setDictType("oil");
                        }else {
                            oil.setDictType("oil_name");
                        }
                        String cardName =sysDictDataService.selectOilType(oil).getOilName();
                        String orderBody = cardName+ "电子卡" + " - " +cardRecordByOrderNo.getStationName();
                        requst.setOrder_body(orderBody);
                        String notifyUrl = "https://" + this.domainName + "/" + this.globalPrefix + "/getYunPayGzhCallback";
                        logger.info("回调地址："+ notifyUrl);
                        requst.setNotify_url(notifyUrl);
                        //发送请求
                        System.out.println("请求报文:"+JSON.toJSONString(requst));
                        SaobeiJsPayResponse response = client.execute(requst);
                        System.out.println("返回报文:"+JSON.toJSONString(response));
                        resultData = ResultData.success(response);
                        logger.info("==============================云闪付 公众号电子卡 充值 拉起支付 ** 结束 **============================================");
                    }else {
                        resultData = ResultData.error(CodeMsg.STATION_NULL_INFO);
                    }
                }else {
                    resultData = ResultData.error(CodeMsg.ALREADY_PAY);
                }
            }else {
                resultData=ResultData.error(CodeMsg.YEWU_FAIL,"未查询到订单");
            }
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

//    /***
//     * 公众号扫呗支付回调
//     * @param jsonObject
//     * @return
//     */
//    @RequestMapping(value = "/getYunPayGzhCallback", consumes = "application/json", method = RequestMethod.POST)
//    @ResponseBody
//    @Transactional
//    public JSONObject getYunPayGzhCallback(@RequestBody JSONObject jsonObject){
//        JSONObject result = new JSONObject();       //返回给扫呗状态码
//        System.out.println("扫呗调用回调接口返回参数：" + jsonObject);
//        if(jsonObject.containsKey("result_code") && jsonObject.get("result_code").toString().equals("01")){
//
//            //业务逻辑
//
//            //返给扫呗状态码
//            result.put("return_code", "01");
//            result.put("return_msg", "success");
//        }else {
//            result.put("return_code", "02");
//            result.put("return_msg", "fail");
//        }
//        return result;
//    }

    /***
     * 小程序云闪付拉起支付
     * @param payInfoRequest
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/yunPay"}, consumes = {"application/json"}, method = {RequestMethod.POST})
    @ResponseBody
    public String yunPay(@RequestBody PayInfoRequest payInfoRequest) throws Exception {

//    智慧易加
//    商户号码：845104816000034
//    终端号：18241101
//    密钥：23570b46a955484d92038f6a18d2b9d6
        Gson gson = new Gson();
        ResultData resultData = null;
        //根据订单号查询订单信息
        String ordNo = payInfoRequest.getOrdNo();
        PayOrder payOrder=payOrderService.selectOrderInfoByOrdNo(ordNo);
        if(payOrder !=null){
            if(payOrder.getStatus().equals("0")) {
                //String stationId = payInfoRequest.getStationId();
                Map<String, String> staPayChannelInfo = stationService.getStationAppIdAndAppSecret(Integer.valueOf(payInfoRequest.getStationId()));
                if(staPayChannelInfo !=null && staPayChannelInfo.containsKey("merchantNo") && staPayChannelInfo.containsKey("terminalId")
                        && staPayChannelInfo.containsKey("yunKey") && staPayChannelInfo.containsKey("appId")) {
                    //秘钥
                    String yunKey = staPayChannelInfo.get("yunKey");                //23570b46a955484d92038f6a18d2b9d6
                    logger.info("==============================云闪付 小程序支付油品 拉起支付 ** 开始 **============================================");
                    DefaultSaobeiApiClient defaultSaobeiApiClient = new DefaultSaobeiApiClient(yunKey); //2ef428f4f76c414282e831baea9e4b0e
                    SaobeiMiniPayRequest requst = new SaobeiMiniPayRequest();
                    requst.setPay_ver("100");
                    requst.setPay_type("010");
                    requst.setService_id("015");
                    requst.setMerchant_no(staPayChannelInfo.get("merchantNo"));                 //商户号   845104816000034
                    requst.setTerminal_id(staPayChannelInfo.get("terminalId"));                 //终端号   18241101
                    requst.setTerminal_trace(payOrder.getOrderNo());                            //订单号   202003252204310000 6683315853083916109905
                    requst.setTerminal_time(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));      //"20200325220431"
                    //云闪付单位为分
                    BigDecimal totalFee = new BigDecimal(payOrder.getAmt().toString()).multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_DOWN);
                    logger.info("该订单金额：" + payOrder.getAmt().toString()+"; 拉起云闪付上送金额（单位：分)：" + totalFee.toString());
                    requst.setTotal_fee(totalFee.toString());
                    String openId = payInfoRequest.getOpenId();
                    requst.setOpen_id(openId);  // oRwjv4iHjSUgxNxOJOQ_60Ln7cno   obnG9jhDLvom5fGwuhYysmQTW4qQ

                    //订单内容
                    String orderBody = payOrder.getOilName()+ " - " + payOrder.getOilGun() + "号枪 - " +payOrder.getStationName();
                    requst.setOrder_body(orderBody);
                    //回调地址
                    String notifyUrl = "https://" + this.domainName + "/" + this.globalPrefix + "/getYunPayCallback";
                    logger.info("回调地址：" + notifyUrl);
                    requst.setNotify_url(notifyUrl);
                    //小程序appId
                    requst.setSub_appid(staPayChannelInfo.get("appId"));          //  wxe1135cd390b38a54    wxe568c727d466aef9        智慧易加公众号：wxc8189d3b3a7283e0

                    System.out.println("请求报文：" + JSON.toJSONString(requst));
                    SaobeiMiniPayResponse response = (SaobeiMiniPayResponse) defaultSaobeiApiClient.execute(requst);
                    System.out.println("返回报文：" + JSON.toJSONString(response));
                    resultData = ResultData.success(response);
                    logger.info("==============================云闪付 小程序支付油品 拉起支付 ** 结束 **============================================");
                }else {
                    resultData = ResultData.error(CodeMsg.STATION_NULL_INFO);
                }
            }else {
                resultData = ResultData.error(CodeMsg.ALREADY_PAY);
            }
        }else {
            resultData = ResultData.error(CodeMsg.NO_ORDER);
        }
        return gson.toJson(resultData);
    }

//    /***
//     * 小程序云闪付扫呗回调
//     * @param jsonObject
//     * @return
//     */
//    @RequestMapping(value = "/getYunPayCallback", consumes = "application/json", method = RequestMethod.POST)
//    @ResponseBody
//    @Transactional
//    public JSONObject getYunPayCallback(@RequestBody JSONObject jsonObject){
//        JSONObject result = new JSONObject();       //返回给扫呗状态码
//        logger.info("扫呗调用回调接口返回参数：" + jsonObject);
//        if(jsonObject.containsKey("result_code") && jsonObject.get("result_code").toString().equals("01")){
//
//            //业务逻辑
//
//            //返给扫呗状态码
//            result.put("return_code", "01");
//            result.put("return_msg", "success");
//        }else {
//            result.put("return_code", "02");
//            result.put("return_msg", "fail");
//        }
//        return result;
//    }

//===========================================================  以下为测试接口   =================================================================================//

    /***
     * 小程序云闪付拉起支付
     * @param payInfoRequest
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/yunPayTest"}, consumes = {"application/json"}, method = {RequestMethod.POST})
    @ResponseBody
    public String yunPayTest(@RequestBody PayInfoRequest payInfoRequest) throws Exception {

//    智慧易加
//    商户号码：845104816000034
//    终端号：18241101
//    密钥：23570b46a955484d92038f6a18d2b9d6
        Gson gson = new Gson();
        ResultData resultData = null;
        DefaultSaobeiApiClient defaultSaobeiApiClient = new DefaultSaobeiApiClient("23570b46a955484d92038f6a18d2b9d6"); //2ef428f4f76c414282e831baea9e4b0e
        SaobeiMiniPayRequest requst = new SaobeiMiniPayRequest();
        requst.setPay_ver("110");
        requst.setPay_type("010");
        requst.setService_id("015");
        requst.setMerchant_no("845104816000034");   //852105942000011
        requst.setTerminal_id("18241101");          //18237172

        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo_1 = System.nanoTime() + result;
        requst.setTerminal_trace(ordNo_1);     //202003252204310000

        requst.setTerminal_time(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));      //"20200325220431"
        String amt = payInfoRequest.getAmt();
        requst.setTotal_fee("1");
        String openId = payInfoRequest.getOpenId();
        requst.setOpen_id("oRwjv4iHjSUgxNxOJOQ_60Ln7cno");  // oRwjv4iHjSUgxNxOJOQ_60Ln7cno   obnG9jhDLvom5fGwuhYysmQTW4qQ
        requst.setOrder_body("sdk测试");
        String notifyUrl = "https://" + this.domainName + "/" + this.globalPrefix + "/getYunPayCallback";
        logger.info("回调地址"+ notifyUrl);
        requst.setNotify_url(notifyUrl);
        requst.setSub_appid("wxe1135cd390b38a54");          //  智慧易加小程序: wxe1135cd390b38a54    wxe568c727d466aef9        智慧易加公众号：wxc8189d3b3a7283e0
        System.out.println("请求报文"+ JSON.toJSONString(requst));
        SaobeiMiniPayResponse response = (SaobeiMiniPayResponse)defaultSaobeiApiClient.execute(requst);
        System.out.println("返回报文"+ JSON.toJSONString(response));
        resultData = ResultData.success(response);
        return gson.toJson(resultData);
    }


    /***
     * 测试
     * 公众号云闪付拉起支付
     * @param payInfoRequest
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/yunPayGzhTest"}, consumes = {"application/json"}, method = {RequestMethod.POST})
    @ResponseBody
    public String yunPayGzhTest(@RequestBody PayInfoRequest payInfoRequest) throws Exception {
        //智慧易加
//    商户号码：845104816000034
//    终端号：18241101
//    密钥：23570b46a955484d92038f6a18d2b9d6
        Gson gson = new Gson();
        ResultData resultData = null;
        //创建client
        SaobeiApiClient<SaobeiJsPayRequest, SaobeiJsPayResponse> client = new DefaultSaobeiApiClient<>("23570b46a955484d92038f6a18d2b9d6");
        //创建requst
        SaobeiJsPayRequest requst = new SaobeiJsPayRequest();
        requst.setPay_ver("110");
        requst.setPay_type("010");
        requst.setService_id("012");
        requst.setMerchant_no("845104816000034");
        requst.setTerminal_id("18241101");
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo_1 = System.nanoTime() + result;
        requst.setTerminal_trace(ordNo_1);     //202003252204310000
        requst.setTerminal_time(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
        requst.setTotal_fee("1");
        requst.setSub_appid("wxc8189d3b3a7283e0");
        requst.setOpen_id("oJR5R6r4EJhaORFcPap70r_mtFZo");                      //oJR5R6r4EJhaORFcPap70r_mtFZo   //oRwjv4iHjSUgxNxOJOQ_60Ln7cno
        requst.setOrder_body("sdk测试");
        String notifyUrl = "https://" + this.domainName + "/" + this.globalPrefix + "/getYunPayGzhCallback";
        logger.info("回调地址："+ notifyUrl);
        requst.setNotify_url(notifyUrl);
        //发送请求
        System.out.println("请求报文:"+JSON.toJSONString(requst));
        SaobeiJsPayResponse response = client.execute(requst);
        System.out.println("返回报文:"+JSON.toJSONString(response));
        resultData = ResultData.success(response);
        return gson.toJson(resultData);
    }


}
