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

import com.alibaba.fastjson.JSON;
import com.liquidnet.commons.lang.util.DateUtil;
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 lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @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.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.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 void sendNotifyBackup(PayNotifyReqBo payNotifyReqBo){
//        PayNotifyDto payNotifyDto = payNotifyReqBo.getPayNotifyDto();
//        LocalDateTime nowTime = LocalDateTime.now();
//        MultiValueMap<String, String> params = new LinkedMultiValueMap();
//        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("price", payNotifyDto.getPrice().toString());
//        params.add("paymentType", payNotifyDto.getPaymentType());
//        String jsonData = JSON.toJSONString(params);
//        log.info("dragon:notify:post url:{}",payNotifyReqBo.getNotifyUrl());
//        log.info("dragon:notify:post data:{}",jsonData);
//        try {
//            String response = HttpUtil.post(payNotifyReqBo.getNotifyUrl(), params);
//            log.debug("PAY RESPONSE=" + response);
//            if (response.equals("success")) {
//                this.createDragonPayNotify(payNotifyReqBo,jsonData);
//                //更新通知状态-通知成功
//                this.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_SUCCESS.getCode()));
//            } else {
//                this.createDragonPayNotifyFail(payNotifyReqBo,jsonData);
//                //更新通知状态-通知失败
//                this.updateNotifyStatus(payNotifyDto.getCode(),Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_FAIL.getCode()));
//            }
//
//            if(true){
//                throw new ConnectTimeoutException();
//            }
//        } catch (ConnectTimeoutException e) {
//            System.out.println("请求超时");
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
    public boolean sendNotify(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 = JSON.toJSONString(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.equals("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();
    }
}
