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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.dto.HuifuWalletAccountDetailDto;
import com.zbkj.common.dto.HuifuWalletAccountDto;
import com.zbkj.common.model.huifu.HuifuWalletTrade;
import com.zbkj.common.utils.DateUtils;
import com.zbkj.service.config.PaymentChannel;
import com.zbkj.service.dao.HuifuWalletAccountDao;
import com.zbkj.service.dao.HuifuWalletAccountDetailDao;
import com.zbkj.service.dao.HuifuWalletTradeDao;
import com.zbkj.service.dao.HuifuWalletTranslogDao;
import com.zbkj.service.service.TransactionLogService;
import com.zbkj.service.wangshang.api.WSApiRequest;
import com.zbkj.service.wangshang.api.domain.RequestHead;
import com.zbkj.service.wangshang.api.domain.model.notify.BkcloudfundsProtocolWithholdResultNotifyModel;
import com.zbkj.service.wangshang.api.internal.parser.xml.XmlConverter;
import com.zbkj.service.wangshang.api.service.notify.BkcloudfundsProtocolWithholdResultNotifyRequest;
import com.zbkj.service.wangshang.handle.CommomRequstHandle;
import com.zbkj.service.wangshang.notify.service.MybankNotifyService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * 协议授权代扣通知结果<ant.mybank.bkcloudfunds.protocol.withhold.result.notify>
 **/
@Service(value = "bkcloudfundsProtocolWithholdResultNotifyService")
public class BkcloudfundsProtocolWithholdResultNotifyServiceImpl implements MybankNotifyService {

    private static final Logger logger = LoggerFactory.getLogger(BkcloudfundsProtocolWithholdResultNotifyServiceImpl.class);
    @Autowired
    private CommomRequstHandle commomRequstHandle;

    @Resource
    private HuifuWalletTradeDao huifuWalletTradeDao;

    @Resource
    private HuifuWalletAccountDetailDao huifuWalletAccountDetailDao;

    @Resource
    private HuifuWalletAccountDao huifuWalletAccountDao;
    @Autowired
    TransactionLogService transactionLogService;

    @Override
    public String notifyHandle(String context, String function) throws Exception {
        System.out.println("========= > 协议授权代扣通知结果：ant.mybank.bkcloudfunds.protocol.withhold.result.notify");
        System.out.println("========= > 请求报文："+context);
        logger.info("========= > 协议授权代扣通知结果：ant.mybank.bkcloudfunds.protocol.withhold.result.notify");
        logger.info("========= > 请求报文："+context);
        //通知内容转换
        BkcloudfundsProtocolWithholdResultNotifyRequest protocolWithholdResultNotifyRequest =
                XmlConverter.getInstance().toResponse(context, BkcloudfundsProtocolWithholdResultNotifyRequest.class);
        RequestHead head = protocolWithholdResultNotifyRequest.getBkcloudfundsProtocolWithholdResultNotify().getRequestHead();
        boolean flag = false;
        try {
            //通知内容保存
            flag = saveNotify(protocolWithholdResultNotifyRequest.getBkcloudfundsProtocolWithholdResultNotify().getBkcloudfundsProtocolWithholdResultNotifyModel());
        }catch (Exception e){
            logger.error("========= > 协议授权代扣通知结果：ant.mybank.bkcloudfunds.protocol.withhold.result.notify:"+e.getMessage());
        }
        //响应结果根据执行结果统一处理
        String response = commomRequstHandle.getSignResult(flag, head);
        transactionLogService.save("协议授权代扣通知结果：ant.mybank.bkcloudfunds.protocol.withhold.result.notify", Constants.Y, context,response, PaymentChannel.WANGSHANG.toString());
        return response;
    }

    private boolean saveNotify(BkcloudfundsProtocolWithholdResultNotifyModel model) {
        //TODO
        HuifuWalletTrade trade = huifuWalletTradeDao.getHuifuWalletTradeByHfSeqId(model.getOperateNo());
        int cf = huifuWalletAccountDetailDao.checkFlowNo(trade.getReqSeqId(),trade.getUniId());
        if(cf>0){
            return true;
        }
        if("SUCCESS".equals(model.getStatus())){
            trade.setTradeStatus(Constants.tradeStatus(Constants.ACCTSTAT_CG)); // 交易成功
            trade.setOrderNo(model.getOrderNo());
        }else{
            trade.setTradeStatus(Constants.tradeStatus(Constants.ACCTSTAT_SB)); // 交易失败
            trade.setErrorMsg(model.getErrorDesc());
        }
        if(StringUtil.isNotEmpty(model.getFinishDate())){
            trade.setTransFinishTime(DateUtil.formatDateTime(DateUtil.parse(model.getFinishDate(),  "yyyyMMddHHmmss")));
        }
        trade.setUpdateTime(new Date());
        huifuWalletTradeDao.updateById(trade);
        List<HuifuWalletAccountDetailDto> detailList = Lists.newArrayList();
        HuifuWalletAccountDetailDto detail = new HuifuWalletAccountDetailDto();
        detail.setUniId(trade.getUniId());
        detail.setWalletAccountNo(trade.getExpendAccountNo());

        detail.setTradeDate(DateUtils.formatDate(trade.getCreateTime(), "yyyyMMdd")); // 交易时间
        detail.setTradeFlowNo(model.getOperateNo()); // 交易流水号
        detail.setFlowNo(model.getOutTradeNo()); // 汇付交易订单号
        detail.setAccountsDealType("内部户处理"); //账务处理类型
        detail.setAccountsDealDate(model.getFinishDate());// 账务处理时间
//        detail.setAmount(trade.getAmount().toString()); // 交易金额
        detail.setAmount((new BigDecimal(model.getTotalAmount())).divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP).toString()); // 交易金额
//                    detail.setBalance(response.get("balance_amt").toString()); // 交易后余额,工行没有交易后余额的数据
        detail.setDirection("出账"); // 资金流向
        String transStat = trade.getTradeStatus();
        transStat = transStat.equals("1")?"成功":transStat.equals("2")?"失败":"处理中";
        detail.setHandStatus(transStat); // 处理状态
        String tradeType = StringUtils.isNotEmpty(trade.getRemark())&&trade.getRemark().contains("退款")?"反向交易":"正向交易";
        detail.setTradeType(tradeType); // 交易类型
        detail.setCreateDate(DateUtils.formatDate(trade.getCreateTime(),"yyyy-MM-dd HH:mm:ss")); // 订单创建时间
        detail.setServiceType("实时"); // 服务类型
        detail.setAccountIn(trade.getIncomeAccountNo());// 收款方账户
        detail.setAccountOut(trade.getExpendAccountNo());// 付款方账户
        detail.setMemo(trade.getRemark()); // 备注
        detail.setPayChannel(PaymentChannel.WANGSHANG.toString());
        HuifuWalletAccountDto accountIn = null;
        HuifuWalletAccountDto accountOut = null;
        if (StringUtil.isEmpty(detail.getAccountIn())) {
            detail.setAccountInName("无");// 收款方账户
        } else {
            accountIn = huifuWalletAccountDao.getHuifuWalletAccountByWalletNo(detail.getAccountIn());
            detail.setAccountInName(StringUtils.isEmpty(accountIn.getComName()) ? "无" : accountIn.getComName()); // 收款方账户中文
        }
        if (StringUtil.isEmpty(detail.getAccountOut())) {
            detail.setAccountOutName("无"); // 付款方账户
        } else {
            accountOut = huifuWalletAccountDao.getHuifuWalletAccountByWalletNo(detail.getAccountOut());
            detail.setAccountOutName(StringUtils.isEmpty(accountOut.getComName()) ? "无" : accountOut.getComName()); // 付款方账户中文
        }

        if(accountOut!=null && accountIn!=null){//转账
            int count = huifuWalletAccountDetailDao.checkFlowNo(detail.getTradeFlowNo(),detail.getUniId());
            if(count==0){
                detailList.add(detail);
            }
            HuifuWalletAccountDetailDto detail2 = new HuifuWalletAccountDetailDto();
            BeanUtils.copyProperties(detail,detail2);
            detail2.setUniId(accountIn.getUniId());
            detail2.setWalletAccountNo(accountIn.getWalletAccountNo());
            detail2.setDirection("入账"); // 资金流向
            count = huifuWalletAccountDetailDao.checkFlowNo(detail2.getTradeFlowNo(),detail2.getUniId());
            if(count==0){
                detailList.add(detail2);
            }
        }else if(accountOut!=null && accountIn==null){//提现
            int count = huifuWalletAccountDetailDao.checkFlowNo(detail.getTradeFlowNo(),detail.getUniId());
            if(count==0){
                detailList.add(detail);
            }
        }else if(accountIn!=null && accountOut==null){//充值
            detail.setDirection("入账"); // 资金流向
            int count = huifuWalletAccountDetailDao.checkFlowNo(detail.getTradeFlowNo(),detail.getUniId());
            if(count==0){
                detailList.add(detail);
            }
        }
        if(detailList.size()>0){
            /* 批量插入数据 */
            huifuWalletAccountDetailDao.insertBatch(detailList);
        }

        return true;
    }

}
