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.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.model.huifu.HuifuWalletTranslog;
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.domain.model.notify.BkcloudfundsWithdrawNotifyModel;
import com.zbkj.service.wangshang.api.internal.parser.xml.XmlConverter;
import com.zbkj.service.wangshang.api.domain.RequestHead;
import com.zbkj.service.wangshang.api.service.notify.BkcloudfundsWithdrawNotifyRequest;
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.util.Date;
import java.util.List;

/**
 * 提现结果通知接口（异步接口）
 * ant.mybank.bkcloudfunds.withdraw.notify
 **/
@Service(value = "bkcloudfundsWithdrawNotifyService")
public class BkcloudfundsWithdrawNotifyServiceImpl implements MybankNotifyService {

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

    @Resource
    private HuifuWalletTradeDao huifuWalletTradeDao;

    @Resource
    private HuifuWalletAccountDetailDao huifuWalletAccountDetailDao;

    @Resource
    private HuifuWalletTranslogDao huifuWalletTranslogDao;

    @Resource
    private HuifuWalletAccountDao huifuWalletAccountDao;
    @Autowired
    TransactionLogService transactionLogService;

    @Override
    public String notifyHandle(String context, String function) throws Exception {
        logger.info("========= > 提现结果通知接口（异步接口）：ant.mybank.bkcloudfunds.withdraw.notify");
        logger.info("========= > 请求报文："+context);
        //通知内容转换
        BkcloudfundsWithdrawNotifyRequest withdrawNotifyRequest =
                XmlConverter.getInstance().toResponse(context, BkcloudfundsWithdrawNotifyRequest.class);
        RequestHead head = withdrawNotifyRequest.getBkcloudfundsWithdrawNotify().getRequestHead();
        boolean flag = false;
        try {
            //通知内容保存
            flag = saveNotify(withdrawNotifyRequest.getBkcloudfundsWithdrawNotify().getBkcloudfundsWithdrawNotifyModel());
        }catch (Exception e){
            logger.error("========= > 提现结果通知接口（异步接口）：ant.mybank.bkcloudfunds.withdraw.notify:"+e.getMessage());
        }
        //响应结果根据执行结果统一处理
        String response = commomRequstHandle.getSignResult(flag, head);
        transactionLogService.save("提现结果通知接口（异步接口）：ant.mybank.bkcloudfunds.withdraw.notify", Constants.Y, context,response, PaymentChannel.WANGSHANG.toString());
        return response;
    }

    private boolean saveNotify(BkcloudfundsWithdrawNotifyModel model) {
        System.out.println("====== > 提现结果通知接口（异步接口）："+ JSONObject.toJSONString(model));
        HuifuWalletTrade trade = huifuWalletTradeDao.getHuifuWalletTradeByHfSeqId(model.getOrderNo());
        //已经有结果了不继续往下走
        if(!Constants.TRADESTATUS_DJY.equals(trade.getTradeStatus())){
            return true;
        }
        if(trade != null){
            saveAccountDetail(trade, model);
        }
        HuifuWalletTrade tradeFee = huifuWalletTradeDao.getHuifuWalletTradeByHfSeqId(model.getOrderNo()+"FEE");
        if(tradeFee != null){
            saveAccountDetail(tradeFee, model);
        }
        /*** 解析返回的列表数据 ***/
        HuifuWalletTranslog translog = new HuifuWalletTranslog();
        translog.setUniId(trade.getUniId());
        translog.setCreateTime(new Date());
        translog.setTransId(trade.getHfSeqId());
        translog.setTransDate(model.getWithdrawFinishDate().substring(0,8));
        translog.setTransAmt(trade.getAmount().toString());
        String transStat = model.getStatus().equals("SUCCESS")?"成功":model.getStatus().equals("FAIL")?"失败":"处理中";
        translog.setTransStat(transStat);
        translog.setCardNo(model.getBankCardNo());
        translog.setCardName(model.getBankCertName());
        HuifuWalletAccountDto account = huifuWalletAccountDao.getHuifuWalletAccountByWalletNo(trade.getExpendAccountNo());
        translog.setBankCode(account.getBankCode());
        translog.setFeeAmt(tradeFee.getAmount().toString());
        translog.setTransDesc(model.getErrorDesc());
        translog.setTransType("取现");
        translog.setPayChannel(PaymentChannel.WANGSHANG.toString());
        huifuWalletTranslogDao.insert(translog);
        return true;
    }

    private void saveAccountDetail(HuifuWalletTrade trade, BkcloudfundsWithdrawNotifyModel model) {
        if("SUCCESS".equals(model.getStatus())){
            trade.setUpdateTime(new Date());
            if(StringUtil.isNotEmpty(model.getWithdrawFinishDate())){
                trade.setTransFinishTime(DateUtil.formatDateTime(DateUtil.parse(model.getWithdrawFinishDate(),  "yyyyMMddHHmmss")));
            }
            trade.setTradeStatus(Constants.tradeStatus(Constants.ACCTSTAT_CG));//成功
        }else if("FAIL".equals(model.getStatus())){
            if(StringUtil.isNotEmpty(model.getWithdrawFinishDate())){
                trade.setTransFinishTime(DateUtil.formatDateTime(DateUtil.parse(model.getWithdrawFinishDate(),  "yyyyMMddHHmmss")));
            }
            trade.setErrorMsg(model.getErrorDesc());
            trade.setUpdateTime(new Date());
            trade.setTradeStatus(Constants.tradeStatus(Constants.ACCTSTAT_SB));//处理中
        }
        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.getOrderNo()); // 交易流水号
        detail.setFlowNo(model.getOutTradeNo()); // 汇付交易订单号
        detail.setAccountsDealType("内部户处理"); //账务处理类型
        detail.setAccountsDealDate(DateUtil.formatDateTime(DateUtil.parse(model.getWithdrawFinishDate(),  "yyyyMMddHHmmss")));// 账务处理时间
        detail.setAmount(trade.getAmount().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(model.getErrorDesc()); // 备注
        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);
        }*/
    }
}
