package com.liquidnet.service.dragon.channel.strategy.biz;

import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.dragon.biz.DragonServiceCommonBiz;
import com.liquidnet.service.dragon.bo.PayNotifyReqBo;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonOrdersDto;
import com.liquidnet.service.dragon.dto.DragonPayOrderQueryRespDto;
import com.liquidnet.service.dragon.dto.PayNotifyDto;
import com.liquidnet.service.dragon.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: DragonPayBiz
 * @Package com.liquidnet.service.dragon.channel.strategy.biz
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/14 14:12
 */
@Slf4j
@Component
public class DragonPayBiz {
    @Autowired
    private DragonServiceCommonBiz dragonServiceCommonBiz;


    public PayNotifyReqBo buildPayNotifyReqBo(DragonOrdersDto dragonOrdersDto) {
        PayNotifyReqBo payNotifyReqBo = new PayNotifyReqBo();
        payNotifyReqBo.setNotifyUrl(dragonOrdersDto.getNotifyUrl());
        PayNotifyDto payNotifyDto = new PayNotifyDto();
        payNotifyDto.setStatus(dragonOrdersDto.getStatus());
        payNotifyDto.setType(dragonOrdersDto.getType());
        payNotifyDto.setCode(dragonOrdersDto.getCode());
        payNotifyDto.setPaymentId(dragonOrdersDto.getPaymentId());
        payNotifyDto.setOrderCode(dragonOrdersDto.getOrderCode());
        payNotifyDto.setOrderCodeId(dragonOrdersDto.getOrderCodeId());
        payNotifyDto.setPrice(dragonOrdersDto.getPrice());
        payNotifyDto.setPaymentType(dragonOrdersDto.getPaymentType());
        if (StringUtil.isNotNull(dragonOrdersDto.getPaymentAt())) {
            payNotifyDto.setPaymentAt(DateUtil.Formatter.yyyyMMddHHmmss.format(dragonOrdersDto.getPaymentAt()));
        } else {
            payNotifyDto.setPaymentAt("");
        }
        payNotifyReqBo.setPayNotifyDto(payNotifyDto);
        return payNotifyReqBo;
    }

    public DragonPayOrderQueryRespDto buildPayOrderQueryRespDto(DragonOrdersDto ordersDto) {
        DragonPayOrderQueryRespDto queryRespDto = new DragonPayOrderQueryRespDto();
        queryRespDto.setStatus(ordersDto.getStatus());
        queryRespDto.setType(ordersDto.getType());
        queryRespDto.setCode(ordersDto.getCode());
        queryRespDto.setPaymentId(ordersDto.getPaymentId());
        queryRespDto.setOrderCode(ordersDto.getOrderCode());
        queryRespDto.setOrderCodeId(ordersDto.getOrderCodeId());
        queryRespDto.setPrice(ordersDto.getPrice());
        queryRespDto.setPaymentType(ordersDto.getPaymentType());
        if (StringUtil.isNotNull(ordersDto.getPaymentAt())) {
            queryRespDto.setPaymentAt(DateUtil.Formatter.yyyyMMddHHmmss.format(ordersDto.getPaymentAt()));
        } else {
            queryRespDto.setPaymentAt("");
        }
        return queryRespDto;
    }


    public boolean sendNotify(PayNotifyReqBo payNotifyReqBo) {
        PayNotifyDto payNotifyDto = payNotifyReqBo.getPayNotifyDto();
        LocalDateTime nowTime = LocalDateTime.now();

        String jsonData = "";
        try {
            MultiValueMap<String, String> params = ObjectUtil.cloneLinkedMultiValueMapStringAndString();
            params.add("status", payNotifyDto.getStatus().toString());
            params.add("type", payNotifyDto.getType());
            params.add("code", payNotifyDto.getCode());
            params.add("paymentId", payNotifyDto.getPaymentId());
            params.add("orderCode", payNotifyDto.getOrderCode());
            params.add("orderCodeId", payNotifyDto.getOrderCodeId());
            params.add("price", payNotifyDto.getPrice().toString());
            params.add("paymentType", payNotifyDto.getPaymentType());
            params.add("paymentAt", payNotifyDto.getPaymentAt());
            jsonData = JsonUtils.toJson(covertNVPS2Params(params));
            log.info("dragon:notify:post url:{}", payNotifyReqBo.getNotifyUrl());
            log.info("dragon:notify:post data:{}", jsonData);

            //执行post请求
            String response = HttpUtil.post(payNotifyReqBo.getNotifyUrl(), params);
            log.debug("PAY RESPONSE=" + response);
            if (response.equalsIgnoreCase("success")) {
                dragonServiceCommonBiz.createDragonPayNotify(payNotifyReqBo, jsonData);
                //更新通知状态-通知成功
                dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(), Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_SUCCESS.getCode()));
                return true;
            } else {
                dragonServiceCommonBiz.createDragonPayNotifyFail(payNotifyReqBo, jsonData);
                //更新通知状态-通知失败
                dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(), Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_FAIL.getCode()));
                return false;
            }

        }
//        catch (ConnectTimeoutException e) {
//            log.error("dragon:sendNotify 请求超时",e);
//            dragonServiceCommonBiz.createDragonPayNotifyFail(payNotifyReqBo,jsonData);
//            //更新通知状态-通知失败
//            dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_EXPIRE.getCode()));
//            return false;
//        }
        catch (Exception e) {
            log.error("dragon:sendNotify 请求失败", e);
            dragonServiceCommonBiz.createDragonPayNotifyFail(payNotifyReqBo, jsonData);
            //更新通知状态-通知失败
            dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(), Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_FAIL.getCode()));
            return false;
        }
    }
//    public boolean sendNotifyBackup(PayNotifyReqBo payNotifyReqBo){
//        PayNotifyDto payNotifyDto = payNotifyReqBo.getPayNotifyDto();
//        LocalDateTime nowTime = LocalDateTime.now();
//
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        String jsonData = "";
//        try {
//            HttpPost httpPost = new HttpPost(payNotifyReqBo.getNotifyUrl());
//            //配置超时
//            RequestConfig requestConfig = RequestConfig.custom()
//                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
//                    .setSocketTimeout(5000).build();
//            httpPost.setConfig(requestConfig);
//
//            //设置post请求参数
//            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//            nvps.add(new BasicNameValuePair("status", payNotifyDto.getStatus().toString()));
//            nvps.add(new BasicNameValuePair("type", payNotifyDto.getType()));
//            nvps.add(new BasicNameValuePair("code", payNotifyDto.getCode()));
//            nvps.add(new BasicNameValuePair("paymentId", payNotifyDto.getPaymentId()));
//            nvps.add(new BasicNameValuePair("orderCode", payNotifyDto.getOrderCode()));
//            nvps.add(new BasicNameValuePair("price", payNotifyDto.getPrice().toString()));
//            nvps.add(new BasicNameValuePair("paymentType", payNotifyDto.getPaymentType()));
//            nvps.add(new BasicNameValuePair("paymentAt", payNotifyDto.getPaymentAt()));
//            jsonData = JsonUtils.toJson(covertNVPS2Params(nvps));
//            log.info("dragon:notify:post url:{}",payNotifyReqBo.getNotifyUrl());
//            log.info("dragon:notify:post data:{}",jsonData);
//            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
//
//            //执行post请求
//            CloseableHttpResponse responseObj = httpclient.execute(httpPost);
//            String response = EntityUtils.toString(responseObj.getEntity(), "utf-8");
//            log.debug("PAY RESPONSE=" + response);
//            if (response.equalsIgnoreCase("success")) {
//                dragonServiceCommonBiz.createDragonPayNotify(payNotifyReqBo,jsonData);
//                //更新通知状态-通知成功
//                dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_SUCCESS.getCode()));
//                return true;
//            } else {
//                dragonServiceCommonBiz.createDragonPayNotifyFail(payNotifyReqBo,jsonData);
//                //更新通知状态-通知失败
//                dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_FAIL.getCode()));
//                return false;
//            }
//
//        } catch (ConnectTimeoutException e) {
//            log.error("dragon:sendNotify 请求超时",e);
//            dragonServiceCommonBiz.createDragonPayNotifyFail(payNotifyReqBo,jsonData);
//            //更新通知状态-通知失败
//            dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_EXPIRE.getCode()));
//            return false;
//        } catch (Exception e) {
//            log.error("dragon:sendNotify 请求失败",e);
//            dragonServiceCommonBiz.createDragonPayNotifyFail(payNotifyReqBo,jsonData);
//            //更新通知状态-通知失败
//            dragonServiceCommonBiz.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayNotifyStatusEnum.NOTIFY_FAIL.getCode()));
//            return false;
//        }finally {
//            //释放连接
//            try {
//                if (httpclient != null) {
//                    httpclient.close();
//                }
//            } catch (IOException e) {
//                log.error("连接无法关闭",e);
//            }
//        }
//    }

    public String getPaymentType(String payType, String deviceFrom) {
        return (deviceFrom + payType).toUpperCase();
    }

    private static Map<String, Object> covertNVPS2Params(List<NameValuePair> nvpList) {
        Map<String, Object> rsMap = ObjectUtil.cloneHashMapStringAndObj();
        for (NameValuePair nameValuePair : nvpList) {
            rsMap.put(nameValuePair.getName(), nameValuePair.getValue());
        }
        return rsMap;
    }

    private static Map<String, Object> covertNVPS2Params(MultiValueMap<String, String> params) {
        Map<String, Object> rsMap = new HashMap<>();
        for (Map.Entry<String, List<String>> param : params.entrySet()) {
            rsMap.put(param.getKey(), param.getValue().get(0));
        }
        return rsMap;
    }
}
