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

import com.alibaba.fastjson.JSONObject;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.strategy.annotation.StrategyPayChannelHandler;
import com.liquidnet.service.dragon.channel.strategy.biz.DragonPayBiz;
import com.liquidnet.service.dragon.constant.DragonConstant;
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.service.impl.DragonOrdersServiceImpl;
import com.liquidnet.service.dragon.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: PayChannelStrategyAlipayImpl
 * @Package com.liquidnet.service.dragon.channel.strategy.impl
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/13 13:06
 */
@Slf4j
@Component
@StrategyPayChannelHandler(DragonConstant.PayChannelEnum.APPLEPAY)
public class ApplepayImpl extends AbstractPayChannelStrategyImpl {

    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private DragonOrdersServiceImpl dragonOrdersService;

    @Autowired
    private DragonPayBiz dragonPayBiz;

    public void completeSuccessOrder(DragonOrdersDto dragonOrdersDto,String code,String result){
        this.completeSuccessOrderNoNotify(dragonOrdersDto, code, LocalDateTime.now(), result);
    }

    @Override
    public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
        return null;
    }

    @Override
    public String dragonNotify(HttpServletRequest request, String payType, String deviceFrom) {
        return null;
    }

    @Override
    public DragonPayOrderQueryRespDto checkOrderStatus(String code) {
        DragonOrdersDto ordersDto = dataUtils.getPayOrderByCode(code);
        //调用  苹果效验
        String verifyResult=dragonOrdersService.buyAppVerify(ordersDto.getReceiptData());
        if (verifyResult == null) {
            // 苹果服务器没有返回验证结果
            log.info("苹果支付查询（checkOrderStatus），查不到订单信息");
            return null;
        } else {
            JSONObject job = JSONObject.parseObject(verifyResult);
            String states = job.getString("status");
            if (states.equals("0")) { // 前端所提供的收据是有效的    验证成功
                DragonPayOrderQueryRespDto respDto = dragonPayBiz.buildPayOrderQueryRespDto(ordersDto);
                respDto.setStatus(Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_PAID.getCode()));
                return respDto;
            }
        }
        return null;
    }
}
