package com.icloud.server.payutils.order;

import com.icloud.server.payutils.PayClient;
import com.icloud.server.payutils.PayClientFactory;
import com.icloud.server.payutils.dto.PayNotifyDataDTO;
import com.icloud.server.payutils.dto.PayOrderDO;
import com.icloud.server.payutils.dto.PayOrderNotifyRespDTO;
import com.icloud.server.payutils.enums.PayTypeEnum;
import com.icloud.server.scala.payorder.PayOrderRepository;
import com.icloud.server.web.err.ServiceExceptionUtil;
import com.icloud.server.web.err.enums.ErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

@Service
@Validated
@Slf4j
public class PayOrderServiceImpl implements PayOrderService {

    @Resource
    @Lazy // 循环依赖，避免报错
    private PayOrderRepository payorderrepository;
    @Resource
    private PayClientFactory payClientFactory;

    @Override
    public void notifyPayOrder(PayTypeEnum paytype,Long channelId, PayNotifyDataDTO notifyData) throws Exception {
        log.info("[notifyPayOrder][channelId({}) 回调数据({})]", channelId, notifyData.getBody());
        System.out.println("--------------");
        System.out.println(channelId);
        System.out.println("--------");

        // 校验支付渠道是否有效
        PayOrderDO channel = payorderrepository.findByChannelid(channelId);
//        PayOrderDO channel = new PayOrderDO();
//        if (paytype == PayTypeEnum.WXPAY){
//
//        }
        // 校验支付客户端是否正确初始化
        PayClient client = payClientFactory.getPayClient(channel.getId());
        if(client==null){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.PAY_ORDER_EXTENSION_NOT_FOUND);
        }
        if (client == null) {
            log.error("[notifyPayOrder][渠道编号({}) 找不到对应的支付客户端]", channel.getId());
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.PAY_CHANNEL_CLIENT_NOT_FOUND);
        }

        // 解析支付结果
        PayOrderNotifyRespDTO notifyRespDTO = client.parseOrderNotify(notifyData);

        //保存订单 ---已经完成支付
        if (channel.getStatus()==1){
            log.info("[notifyPayOrder][支付拓展单({}) 更新为已支付]", channel.getId());
        }else {
            log.info("[notifyPayOrder][支付订单({}) 更新为已支付]", channel.getId());

            System.out.println("getChannelUserId"+notifyRespDTO.getChannelUserId());
            System.out.println("getChannelOrderNo"+notifyRespDTO.getChannelOrderNo());
            System.out.println("getSuccessTime"+notifyRespDTO.getSuccessTime());
            channel.setStatus(1);
            payorderrepository.save(channel);
        }
    }
}
