package com.icloud.server.payutils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.icloud.server.payutils.dto.PayNotifyDataDTO;
import com.icloud.server.payutils.dto.PayOrderDO;
import com.icloud.server.scala.pay.Alipay1;
import com.icloud.server.scala.pay.Alipay1Repository;
import com.icloud.server.scala.paynotify.PayNotifyEntity;
import com.icloud.server.scala.paynotify.PayNotifyLogEntity;
import com.icloud.server.scala.paynotify.PayNotifyLogRepository;
import com.icloud.server.scala.paynotify.PayNotifyRepository;
import com.icloud.server.scala.payorder.PayOrderRepository;
import com.icloud.server.utils.JsonUtils;
import com.icloud.server.utils.log.Logs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.alipay.api.internal.util.AlipaySignature;

/**
 * 微信
 *
 * @Author : yang
 * @Date : 2022-07-26 01:09
 * @Version : 2.1.2
 */

@Api(tags = "支付宝回传")
//@ApiIgnore
@RestController
@RequestMapping("/pay/aliorder")
@Validated
@Slf4j
@AllArgsConstructor
public class AliPayNotify {

    @Resource
    private PayClientFactory payClientFactory;
    @Resource
    private PayNotifyRepository pnr;
    @Resource
    private Alipay1Repository ar;
    @Resource
    private PayOrderRepository por;
    @Resource
    private PayNotifyLogRepository pnlr;

    static Logger logger = LoggerFactory.getLogger("alirepay");



    public String alyPayNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("支付宝支付成功回调");
        //这里拿到支付宝通知数据
        Map<String, Object> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
        String paramsJson = JSON.toJSONString(params);
        log.info("支付宝回调，{}"+ paramsJson);
        Map<String, String> map = JSON.parseObject(paramsJson, new TypeReference<Map<String, String>>(){});
        return  "";

    }

    // 将request中的参数转换成Map
    private static Map<String, Object> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        Map<String,String[]> map = new HashMap<String,String[]>();
        map = request.getParameterMap();
        Iterator entries = map.entrySet().iterator();
        Map.Entry entry;
        String name ="";
        String value=null;
        while (entries.hasNext()){
            entry=(Map.Entry)entries.next();
            name = (String) entry.getKey();
            Object objvalue = entry.getValue();
            if(objvalue == null){
                value = null;
            }else if(objvalue instanceof String[]){
                /**条件如果成立，objvalue就是一个数组，需要将它转换成为字符串，并拼接上逗号，并吧末尾的逗号去掉*/
                String[] values = (String[]) objvalue;
                for(int i=0;i<values.length;i++){
                    value = values[i]+",";//这里我拼接的是英文的逗号。
                }
                value = value.substring(0,value.length()-1);//截掉最后一个逗号。
            }else{
                value = objvalue.toString();
            }
            log.info("key:"+name);
            log.info("value:"+value);
            returnMap.put(name , value);
        }
        Iterator it = returnMap.keySet().iterator();
        while (it.hasNext()){
            Object key = it.next();
            if(returnMap.get(key) == null || "".equals (((String)returnMap.get(key)).trim())){
                returnMap.put((String) key, null);
            }
        }
        return returnMap;

    }
























    public Map<String, String> request_pay(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

    private Map<String, String>  parseAliPayReq(HttpServletRequest request){
        // 构造传入参数
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {

            }
            params.put(name, valueStr);
        }


        return params;
    }



    @PostMapping(value = "/alinotify/{channelId}")
    @ApiOperation("渠道统一的支付成功,或退款成功 通知url")
    public String aa(@PathVariable("channelId") Long channelId,HttpServletRequest request, HttpServletResponse response){
        System.out.println("=======支付域名:alinotify========");
        System.out.println("channelId:" + channelId);
        System.out.println("=======request:"+request);
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        HashMap<String, String> map = new HashMap<>();
        for(Object str:requestParams.keySet()){
            String parameter = request.getParameter(str.toString());
            map.put(str.toString(),parameter);
            System.out.println("key======"+str+":"+parameter);
        }
        String req = JsonUtils.toJsonString(map);
        //out_trade_no
        String out_trade_no = request.getParameter("out_trade_no");
        System.out.println("out_trade_no:"+out_trade_no);
        PayOrderDO byMerchantorderid = por.findByMerchantorderid(out_trade_no);
        Optional<Alipay1> alipay1 = ar.findById(byMerchantorderid.getAppid());
        String alipaypublickey = alipay1.get().getAlipaypublickey();

        try {
            boolean verify_result = AlipaySignature.rsaCheckV1(params,alipaypublickey,"UTF-8","RSA2");
            System.out.println("verify_result:"+verify_result);
            if(verify_result){
                System.out.println("订单支付成功");

                List<PayNotifyEntity> pnes = pnr.findByMerchantorderidAndStatus(out_trade_no,0);
                if(!pnes.isEmpty()){
                    PayNotifyLogEntity paynotifylogentity = new PayNotifyLogEntity().toEntity(out_trade_no, req, "ali", "ali", byMerchantorderid.getAppid().toString());
                    //mysql 记录
                    pnlr.save(paynotifylogentity);
                    //log 日志----输出
                    new Logs(logger).toLog( req);
                    PayNotifyEntity entity = pnes.get(0);
                    String merchantorderid = entity.getMerchantorderid();
                    entity.setStatus(1);
                    pnr.save(entity);
                    PayOrderDO por1 = por.findByMerchantorderid(merchantorderid);
                    por1.setStatus(1);
                    //mysql --修改订单状态
                    por.save(por1);
                }
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


        return "success";
    }



}
