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.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.DataUtilsDragon;
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.Component;

import java.util.Map;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: UnionpayStrategyAppImpl
 * @Package com.liquidnet.service.dragon.channel.unionpay.strategy.impl
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/11/08 18:34
 */
@Slf4j
@Component
@StrategyUnionpayHandler(DragonConstant.DeviceFromEnum.APP)
public class UnionpayStrategyAppImpl 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 DataUtilsDragon dataUtilsDragon;

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

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

    @Override
    UnionpayTradePayReq appendRequestParam(UnionpayTradePayReq payReq, DragonPayBaseReqDto dragonPayBaseReqDto) {
       /* payReq.setAccType("01");
        payReq.setChannelType("08");*/
        //设置订单过期时间
        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;
    }
    /**
     * @author zhangfuxin
     * @Description:  银联app查询
     * @date 2021/11/24 上午11:56
     */
    @Override
    public DragonPayOrderQueryRespDto checkOrderStatus(String code) {
        DragonOrdersDto ordersDto = dataUtilsDragon.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.tradeQueryApp(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) {
       /* if(StringUtil.isNotNull(respResult)&&respResult.get("tn")!=null){
            payBaseRespDto.getPayData().setPrepayId(respResult.get("tn"));
        }*/

        payBaseRespDto.getPayData().setRedirectUrl(sdkConfig.getFrontTransUrl());
        if(StringUtil.isNotNull(respResult)){
            payBaseRespDto.getPayData().setPrepayId(respResult.get("tn"));
        }

        return payBaseRespDto;
    }
}
