package com.zbkj.service.wangshang.notify.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.dto.HuifuWalletAccountDto;
import com.zbkj.common.model.huifu.HuifuWalletTrade;
import com.zbkj.common.model.huifu.HuifuWalletTranslog;
import com.zbkj.service.config.PaymentChannel;
import com.zbkj.service.dao.HuifuWalletAccountDao;
import com.zbkj.service.dao.HuifuWalletTradeDao;
import com.zbkj.service.dao.HuifuWalletTranslogDao;
import com.zbkj.service.service.TransactionLogService;
import com.zbkj.service.wangshang.api.domain.RequestHead;
import com.zbkj.service.wangshang.api.domain.model.notify.BkcloudfundsRefundNotifyModel;
import com.zbkj.service.wangshang.api.domain.model.notify.BkcloudfundsWithdrawNotifyModel;
import com.zbkj.service.wangshang.api.internal.parser.xml.XmlConverter;
import com.zbkj.service.wangshang.api.service.notify.BkcloudfundsRefundNotifyRequest;
import com.zbkj.service.wangshang.handle.CommomRequstHandle;
import com.zbkj.service.wangshang.notify.service.MybankNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 支付退回通知接口（异步接口）
 * ant.mybank.bkcloudfunds.refund.notify
 **/
@Service(value = "bkcloudfundsRefundNotifyService")
public class BkcloudfundsRefundNotifyServiceImpl implements MybankNotifyService {

    @Autowired
    private CommomRequstHandle commomRequstHandle;

    @Resource
    private HuifuWalletTradeDao huifuWalletTradeDao;
    @Resource
    private HuifuWalletTranslogDao huifuWalletTranslogDao;

    @Resource
    private HuifuWalletAccountDao huifuWalletAccountDao;

    @Autowired
    TransactionLogService transactionLogService;

    @Override
    public String notifyHandle(String xmlContext, String function) throws Exception {
        //通知内容转换
        BkcloudfundsRefundNotifyRequest refundNotifyRequest =
                XmlConverter.getInstance().toResponse(xmlContext, BkcloudfundsRefundNotifyRequest.class);
        RequestHead head = refundNotifyRequest.getBkcloudfundsRefundNotify().getRequestHead();
        //保存通知内容
        boolean flag = saveNotify(refundNotifyRequest.getBkcloudfundsRefundNotify().getBkcloudfundsRefundNotifyModel());
        //响应结果根据执行结果统一处理
        String response = commomRequstHandle.getSignResult(flag, head);
        transactionLogService.save("支付退回通知接口（异步接口）：ant.mybank.bkcloudfunds.refund.notify", Constants.Y, xmlContext,response, PaymentChannel.WANGSHANG.toString());
        return response;
    }

    private boolean saveNotify(BkcloudfundsRefundNotifyModel model) {
        System.out.println("====== > 提现结果通知接口（异步接口）："+ JSONObject.toJSONString(model));
        HuifuWalletTrade trade = huifuWalletTradeDao.getHuifuWalletTradeByHfSeqId(model.getRefundOrderNo());
        //已经有结果了不继续往下走
        if(!Constants.TRADESTATUS_DJY.equals(trade.getTradeStatus())){
            return true;
        }
        if(trade != null){
            saveAccountDetail(trade, model);
        }
        HuifuWalletTranslog translog = huifuWalletTranslogDao.getByTransId(model.getRefundOrderNo());
        translog.setUpdateTime(new Date());
        translog.setTransDate(model.getRefundFinishDate().substring(0,8));
        String transStat = model.getStatus().equals("SUCCESS")?"成功":model.getStatus().equals("FAIL")?"失败":"处理中";
        translog.setTransStat(transStat);
        translog.setTransDesc(model.getErrorDesc());
        huifuWalletTranslogDao.updateById(translog);
        return true;
    }

    private void saveAccountDetail(HuifuWalletTrade trade, BkcloudfundsRefundNotifyModel model) {
        if("SUCCESS".equals(model.getStatus())){
            trade.setUpdateTime(new Date());
            if(StringUtil.isNotEmpty(model.getRefundFinishDate())){
                trade.setTransFinishTime(DateUtil.formatDateTime(DateUtil.parse(model.getRefundFinishDate(),  "yyyyMMddHHmmss")));
            }
            trade.setTradeStatus(Constants.tradeStatus(Constants.ACCTSTAT_CG));//成功
        }else if("FAIL".equals(model.getStatus())){
            if(StringUtil.isNotEmpty(model.getRefundFinishDate())){
                trade.setTransFinishTime(DateUtil.formatDateTime(DateUtil.parse(model.getRefundFinishDate(),  "yyyyMMddHHmmss")));
            }
            trade.setErrorMsg(model.getErrorDesc());
            trade.setUpdateTime(new Date());
            trade.setTradeStatus(Constants.tradeStatus(Constants.ACCTSTAT_SB));//处理中
        }
        huifuWalletTradeDao.updateById(trade);

    }

}
