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

import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.dragon.channel.strategy.biz.DragonPayBiz;
import com.liquidnet.service.dragon.channel.unionpay.biz.UnionpayBiz;
import com.liquidnet.service.dragon.channel.unionpay.constant.UnionpayConstant;
import com.liquidnet.service.dragon.channel.unionpay.req.UnionpayTradePayReq;
import com.liquidnet.service.dragon.channel.unionpay.sdk.SDKConfig;
import com.liquidnet.service.dragon.channel.unionpay.strategy.annotation.StrategyUnionpayHandler;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: UnionpayStrategyWapImpl
 * @Package com.liquidnet.service.dragon.channel.unionpay.strategy.impl
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/10 14:34
 */
@Slf4j
@Service
@StrategyUnionpayHandler(DragonConstant.DeviceFromEnum.WAP)
public class UnionpayStrategyWapImpl extends AbstractUnionPayStrategy {
    @Value("${liquidnet.dragon.url}")
    private String notifyUrl;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UnionpayBiz unionpayBiz;

    @Autowired
    private SDKConfig sdkConfig;
    @Autowired
    private DragonPayBiz dragonPayBiz;
    @Autowired
    private DataUtils dataUtils;

    @Override
    protected Map<String, String> executePay(UnionpayTradePayReq payReq) {
        return unionpayBiz.tradeWapPay(payReq);
    }

    @Override
    protected String getNotifyUrl() {
        return notifyUrl + "/notify/unionpay/wap";
    }

    @Override
    UnionpayTradePayReq appendRequestParam(UnionpayTradePayReq payReq, DragonPayBaseReqDto dragonPayBaseReqDto) {
        //设置订单过期时间
        String timeExpire = DateUtil.format(DateUtil.Formatter.yyyyMMddHHmmss.parse(dragonPayBaseReqDto.getCreateDate()).plusMinutes(Long.parseLong(dragonPayBaseReqDto.getExpireTime())),DateUtil.Formatter.yyyyMMddHHmmssTrim);
        payReq.setChannelType("07");
        payReq.setRiskRateInfo(dragonPayBaseReqDto.getName());
        payReq.setFrontUrl(dragonPayBaseReqDto.getReturnUrl());
        payReq.setPayTimeout(timeExpire);
        return payReq;
    }

    @Override
    public DragonPayOrderQueryRespDto checkOrderStatus(String code) {
        DragonOrdersDto ordersDto = dataUtils.getPayOrderByCode(code);
        if(null==ordersDto){
            throw new LiquidnetServiceException(DragonErrorCodeEnum.TRADE_UNIONPAY_QUERY_ERROR.getCode(),DragonErrorCodeEnum.TRADE_UNIONPAY_QUERY_ERROR.getMessage());
        }
        DragonPayOrderQueryRespDto respDto = dragonPayBiz.buildPayOrderQueryRespDto(ordersDto);
        //wap类型查询订单
        Map<String, String> resultMap = unionpayBiz.tradeQuery(code);
        if(("00").equals(resultMap.get("respCode"))){//如果查询交易成功
            String origRespCode = resultMap.get("origRespCode");
            if((UnionpayConstant.UnionTradeStateEnum.TRADE_SUCCESS).equals(origRespCode)||UnionpayConstant.UnionTradeStateEnum.TRADE_DEFECTIVENESS_SUCCESS.equals(origRespCode)){
                //交易成功
                respDto.setStatus(Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_PAID.getCode()));
            }else if(("03").equals(origRespCode)||
                    ("04").equals(origRespCode)||
                    ("05").equals(origRespCode)){
                //订单处理中或交易状态未明，需稍后发起交易状态查询交易 【如果最终尚未确定交易是否成功请以对账文件为准】
                respDto.setStatus(Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_UNPAID.getCode()));
            }else{
                //其他应答码为交易失败
                //TODO
                respDto.setStatus(Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_PAY_FAIL.getCode()));
            }
        }


        return respDto;
    }

    @Override
    DragonPayBaseRespDto buildResponseDto(DragonPayBaseRespDto payBaseRespDto, Map<String, String> respResult) {

        payBaseRespDto.getPayData().setRedirectUrl(sdkConfig.getFrontTransUrl());
        if(StringUtil.isNotNull(respResult)){
            payBaseRespDto.getPayData().setOrderStr(JsonUtils.toJson(respResult));
        }
        return payBaseRespDto;
    }
}
