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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.biz.DragonServiceCommonBiz;
import com.liquidnet.service.dragon.channel.douyinpay.strategy.DouYinayStrategyContext;
import com.liquidnet.service.dragon.channel.strategy.annotation.StrategyPayChannelHandler;
import com.liquidnet.service.dragon.channel.strategy.biz.DragonPayBiz;
import com.liquidnet.service.dragon.channel.wepay.constant.WepayConstant;
import com.liquidnet.service.dragon.channel.wepay.strategy.WepayStrategyContext;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.constant.DragonErrorCodeEnum;
import com.liquidnet.service.dragon.dto.DragonOrdersDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import com.liquidnet.service.dragon.dto.DragonPayOrderQueryRespDto;
import com.liquidnet.service.dragon.utils.DataUtils;
import com.liquidnet.service.dragon.utils.PayDouYinpayUtils;
import com.liquidnet.service.dragon.utils.PayWepayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author zhangfuxin
 * @Description: 抖音
 * @date 2021/11/9 上午11:47
 */
@Slf4j
@Component
@StrategyPayChannelHandler(DragonConstant.PayChannelEnum.DOUYINPAY)
public class PayChannelStrategyDouYinImpl extends AbstractPayChannelStrategyImpl {

    @Autowired
    private DouYinayStrategyContext douYinayStrategyContext;

    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private DragonServiceCommonBiz dragonServiceCommonBiz;

    @Autowired
    private DragonPayBiz dragonPayBiz;

    @Override
    public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
        return douYinayStrategyContext.getStrategy(dragonPayBaseReqDto.getDeviceFrom()).dragonPay(dragonPayBaseReqDto);
    }

    @Override
    public String dragonNotify(HttpServletRequest request,String payType,String deviceFrom) {

        JSONObject jsonObject=PayDouYinpayUtils.getJsonObject(request);
        try {
            log.info("dragonNotify-->douYinPay json : {}", JSON.toJSONString(jsonObject));
            log.info("接收到{}支付结果{}", payType, JSON.toJSONString(jsonObject));
            if(!jsonObject.getString("type").equals("payment")){
                throw new LiquidnetServiceException(DragonErrorCodeEnum.TRADE_PARAM_ERROR.getCode(),DragonErrorCodeEnum.TRADE_PARAM_ERROR.getMessage());
            }
            JSONObject msg=jsonObject.getJSONObject("msg");
           // Map msg= (Map) map.get("msg");
            String code =msg.get("cp_orderno").toString();
            //持久化通知记录
            dragonServiceCommonBiz.createDragonOrderLogs(code,dragonPayBiz.getPaymentType(payType,deviceFrom),JSON.toJSONString(jsonObject));
            // 根据银行订单号获取支付信息
            DragonOrdersDto dragonOrdersDto = dataUtils.getPayOrderByCode(code);
            if (dragonOrdersDto == null) {
                throw new LiquidnetServiceException(DragonErrorCodeEnum.TRADE_ERROR_NOT_EXISTS.getCode(),DragonErrorCodeEnum.TRADE_ERROR_NOT_EXISTS.getMessage());
            }
            if (DragonConstant.PayStatusEnum.STATUS_PAID.getCode().equals(dragonOrdersDto.getStatus())) {
                throw new LiquidnetServiceException(DragonErrorCodeEnum.TRADE_ERROR_HAS_PAID.getCode(),DragonErrorCodeEnum.TRADE_ERROR_HAS_PAID.getMessage());
            }
            String sign = jsonObject.get("msg_signature").toString();
            boolean notifyResult = false;
            if (PayDouYinpayUtils.getInstance().notifySign( sign,jsonObject)) {// 根据配置信息验证签名
                //抖音回调 就代表成功了
                this.completeSuccessOrder(dragonOrdersDto,null, LocalDateTime.now(), JSON.toJSONString(jsonObject));
                /*if (WepayConstant.WeixinTradeStateEnum.SUCCESS.getCode().equals(notifyMap.get("result_code"))) {// 业务结果
                    // 成功
                    notifyResult = this.completeSuccessOrder(dragonOrdersDto, notifyMap.get("transaction_id"), timeEnd, notifyMap.toString());
                } else {
                    notifyResult = this.completeFailOrder(dragonOrdersDto, notifyMap.toString());
                }
                if(notifyResult){
                    returnStr = "<xml>\n" + "  <return_code><![CDATA[SUCCESS]]></return_code>\n" + "  <return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
                }*/
                return "{\"err_no\": 0,\"err_tips\": \"success\"}";
            } else {

                log.error("touyin notify fail code:{} msg:{} ",DragonErrorCodeEnum.TRADE_DOUYINPAY_SIGN_ERROR.getCode(),DragonErrorCodeEnum.TRADE_DOUYINPAY_SIGN_ERROR.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public DragonPayOrderQueryRespDto checkOrderStatus(String code) {
        DragonOrdersDto ordersDto = dataUtils.getPayOrderByCode(code);
        DragonPayOrderQueryRespDto respDto = douYinayStrategyContext.getStrategy(DragonConstant.PayTypeEnum.getEnumByCode(ordersDto.getPaymentType()).getDeviceFrom()).checkOrderStatus(code);
        return respDto;
    }
}
