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


import com.zbkj.common.constants.Constants;
import com.zbkj.common.dto.HuifuWalletAccountDto;
import com.zbkj.common.model.huifu.HuifuWallet;
import com.zbkj.common.model.huifu.HuifuWalletAccount;
import com.zbkj.common.model.huifu.HuifuWalletProcess;
import com.zbkj.service.config.PaymentChannel;
import com.zbkj.service.dao.HuifuWalletAccountDao;
import com.zbkj.service.dao.HuifuWalletDao;
import com.zbkj.service.dao.HuifuWalletProcessDao;
import com.zbkj.service.huifu.constants.OpenProcess;
import com.zbkj.service.service.TransactionLogService;
import com.zbkj.service.wangshang.api.domain.RequestHead;
import com.zbkj.service.wangshang.api.domain.model.notify.MerchantprodMerchNotifyModel;
import com.zbkj.service.wangshang.api.internal.parser.xml.XmlConverter;
import com.zbkj.service.wangshang.api.service.notify.MerchantprodMerchNotifyRequest;
import com.zbkj.service.wangshang.handle.CommomRequstHandle;
import com.zbkj.service.wangshang.notify.service.MybankNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 商户入驻结果通知接口通知实现
 * ant.mybank.merchantprod.merch.notify
 **/
@Service(value = "bkMerchantprodMerchNotifyService")
public class BkMerchantprodMerchNotifyServiceImpl implements MybankNotifyService {

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

    @Resource
    private HuifuWalletAccountDao huifuWalletAccountDao;

    @Resource
    private HuifuWalletProcessDao huifuWalletProcessDao;

    @Resource
    private HuifuWalletDao huifuWalletDao;
    @Autowired
    TransactionLogService transactionLogService;

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

    private boolean saveNotify(MerchantprodMerchNotifyModel model) {
        //TODO
        HuifuWalletAccountDto dto = huifuWalletAccountDao.getHuifuWalletAccountByOutMerchantId(model.getOutMerchantId());
        if(dto == null){
            return false;
        }
        Date now = new Date();
        HuifuWalletAccount hwa = huifuWalletAccountDao.selectById(dto.getId());
        HuifuWallet huifuWallet = huifuWalletDao.getHuifuWalletByUniId(hwa.getUniId(), PaymentChannel.WANGSHANG.toString());
        HuifuWalletProcess hp = huifuWalletProcessDao.getLastStepProcess(dto.getUniId(), PaymentChannel.WANGSHANG.toString());
        String registerStatus = model.getRegisterStatus();
        if("1".equals(huifuWallet.getIsCompleteOpen())){
            return true;
        }
        if("1".equals(registerStatus)){
            hwa.setUpdateTime(now);
            hwa.setFailReason("");
            if(hp.getStep()==2 && "PRE_REGISTER_ASYNC_NOTIFY".equals(model.getAsyncNotifyType())){
                hwa.setWalletAccountNo(model.getMerchantId());
                huifuWalletAccountDao.updateById(hwa);
                hp.setUpdateTime(now);
                hp.setIsComplete(Constants.Y);
                huifuWalletProcessDao.updateById(hp);
                //增加业务入驻流程 等待入驻申请结果开始
                HuifuWalletProcess buildProcess = new HuifuWalletProcess();
                buildProcess.setUniId(hwa.getUniId());
                buildProcess.setCreateTime(now);
                buildProcess.setStep(OpenProcess.SHJHZ.getSort());
                buildProcess.setIsComplete(Constants.N);
                buildProcess.setDescription(OpenProcess.SHJHZ.getDesc());
                buildProcess.setPayChannel(PaymentChannel.WANGSHANG.toString());
                huifuWalletProcessDao.insert(buildProcess);
            }else if(hp.getStep()==3 && "PRE_REGISTER_ACTIVATE_ASYNC_NOTIFY".equals(model.getAsyncNotifyType())){
                hwa.setAcctStat("N");//如果激活通知状态为N正常
                huifuWalletAccountDao.updateById(hwa);
                hp.setUpdateTime(now);
                hp.setIsComplete(Constants.Y);
                huifuWalletProcessDao.updateById(hp);
                /*** 更新企业钱包服务为已完成 ***/
                huifuWallet.setUniId(hwa.getUniId());
                huifuWallet.setUpdateTime(now);
                huifuWallet.setIsCompleteOpen(Constants.Y);
                huifuWallet.setOpenTime(now);
                huifuWallet.setPayChannel(PaymentChannel.WANGSHANG.toString());
                huifuWalletDao.updateHuifuWallet(huifuWallet);
            }

        }else if("2".equals(registerStatus)){
            hwa.setFailReason(model.getFailReason());
            huifuWalletAccountDao.updateById(hwa);
            if(hp.getStep()==2){
                /*** 更新业务入驻流程 删除当前步骤 返回上个步骤 ***/
                huifuWalletProcessDao.deleteById(hp);
                HuifuWalletProcess huifuWalletProcess = huifuWalletProcessDao.getLastStepProcess(hwa.getUniId(),PaymentChannel.WANGSHANG.toString());
                huifuWalletProcess.setUpdateTime(now);
                huifuWalletProcess.setIsComplete(Constants.N);
                huifuWalletProcessDao.updateById(huifuWalletProcess);
            }else{
                //TODO 激活失败怎么办
            }

        }
        return true;
    }

}
