package cn.pluss.platform.sxf;

import cn.pluss.platform.CallbackDataService;
import cn.pluss.platform.channel.BaseMakeMoneyService;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.BackDataErrorException;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.service.UnknownExceptionService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@RequiredArgsConstructor
@Service("sxfMakeMoneyService")
public class SxfMakeMoneyServiceImpl extends BaseMakeMoneyService {

    private final SxfService sxfService;

    private final CallbackDataService callbackDataService;

    private final UserAppService userAppService;

    private final MerchantChannelStatusService merchantChannelStatusService;

    private final AccountService accountService;

    private final UnknownExceptionService unknownExceptionService;

    private final MerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    private GeneralPushUtil generalPushUtil;


    /**
     * @param data
     *  http://doc.tianquetech.com/web/#/3?page_id=312
     *  orgId - 机构编号
     *  mno - 商户编号
     *  serialNo - 结算流水
     *  amount - 结算金额
     *  settleStatus - 结算状态
     *  fee - 手续费
     *  settleAccountType - 结算账户类型
     *  settleAccountNm - 结算账户名
     *  settleBankNm - 结算银行
     *  settleBankNo - 联行号
     *  settleDt - 结算时间
     *  settleTime - 结算完成时时间
     *  refReason - 结算失败理由
     *  timeStamp - 时间戳
     *  sign - 签名
     */
    @Override
    public void dealCallbackData(JSONObject data) {
        boolean sign;
        try {
            sign = sxfService.checkSign(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BackDataErrorException("随行付结算信息验签失败");
        }

        if (!sign) {
            throw new BackDataErrorException("随行付结算信息验签失败");
        }


        try {
            // 暂时保存回调数据
            CallbackData callbackData = new CallbackData().setOrigin(data.toString());
            callbackData.setTable("tb_pluss_make_money");
            callbackDataService.save(callbackData);

            saveData(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * {
     * 	"refReason": "付款成功",
     * 	"amount": "11243.38",
     * 	"settleTime": "20200915100626",
     * 	"settleBnkNo": "622848****1477",
     * 	"settleStatus": "S",
     * 	"fee": "0.0",
     * 	"sign": "AfAjiUE6U4SnZKUJ4N218pEUaZmHKHjaBuARWM/Onk6LeiBPUIJHshUOT7FefX1wPyuU6+5QKaEBAt57ZG50J6YdEkv3xSYH9V5xZefBVHVrcWodYzOtI9jApfbNXjR08qSMIcHl0vKVyAYHvOZAiKEmyuo2NZKYmeJ8kA2EOUJpzAl10By33jGS1VY7n6gqyJ/2Y3wYlxQvM1gEaxYNWUpRUMSqZA8a8lsR5/ZMel+rqBxjrg/1q1gCZTa1PbIhy9kofDfdVLAflUlCok2NA0Lwy4pnVzTwa8KPn2AjWxW2Gf4ccHMf4YoNfpWEisHTBQZGY7qJ1u32HWkIyDrsDA==",
     * 	"orgId": "56964586",
     * 	"mno": "399200831263640",
     * 	"serialNo": "OSX2020091527777098",
     * 	"timeStamp": "20200915100627",
     * 	"settleBankNm": "中国农业银行",
     * 	"settleBankNo": "103541073242",
     * 	"settleDt": "20200915"
     * }
     * @param data
     */
    private void saveData(JSONObject data) {
        MakeMoney makeMoney = new MakeMoney();
        makeMoney.setChannelId("1");
        makeMoney.setBillId(data.getString("serialNo"));
        makeMoney.setMerchantId(data.getString("mno"));
        makeMoney.setRealAmount(new BigDecimal(data.getString("amount")).multiply(BigDecimal.valueOf(100)).doubleValue());
        makeMoney.setPlanAmount(makeMoney.getRealAmount());
        makeMoney.setSuspendAmount(0d);
        String settleStatus = data.getString("settleStatus");
        makeMoney.setThirdStatus(settleStatus);
        makeMoney.setBankHolder(data.getString("settleAccountNm"));
        makeMoney.setBankAccount(data.getString("settleBnkNo"));

        switch (settleStatus) {
            case "S":
                // 打款成功
                makeMoney.setState("1");
                // 结算完成时间
                String settleTimeStr = data.getString("settleTime");
                Date  settleTime = DateUtils.parse(settleTimeStr, "yyyyMMddHHmmss");
                makeMoney.setBankretTime(DateUtils.formatDateDefault(settleTime, "yyyy-MM-dd HH:mm:ss"));
                break;
            case "P":
                // 打款中
                makeMoney.setState("0");
                break;
            case "F":
                makeMoney.setState("-1");
            case "R":
                // 打款退票
                makeMoney.setState("2");
                break;
            default:
                break;
        }

        MerchantChannelStatus merchantChannelStatus = new MerchantChannelStatus().setMerchantId(makeMoney.getMerchantId());
        merchantChannelStatus = merchantChannelStatusService.getOne(new QueryWrapper<>(merchantChannelStatus));
        if (merchantChannelStatus == null) {
            throw new MsgException("无法找到对应商户");
        }

        UserApp userApp = new UserApp().setMerchantCode(merchantChannelStatus.getMerchantCode()).setUserType("promoter");
        userApp = userAppService.queryUserApp(userApp);
        if (userApp == null) {
            throw new MsgException("无法找到对应商户");
        }

        AccountDTO account = accountService.getAccount(userApp.getUserId() + "");
        BankCard bankCard = account.getBankCard();

        if (bankCard == null) {
            String msg = "用户【" + userApp.getUserId() + "】未找到结算卡信息";
            BackDataErrorException backDataErrorException = new BackDataErrorException(msg);
            unknownExceptionService.save(backDataErrorException);
            throw new MsgException("未找到商户对应的结算银行卡信息");
        } else {
            makeMoney.setBankHolder(hiddenBankCertName(bankCard.getBankHolder()));
        }

        String settleDt = data.getString("settleDt");
        Date settleDate = DateUtils.parse(settleDt, "yyyyMMdd");
        makeMoney.setSettDate(DateUtils.formatDateDefault(settleDate, "yyyy-MM-dd"));

        String timeStamp = data.getString("timeStamp");
        Date createTime = DateUtils.parse(timeStamp, "yyyyMMddHHmmss");
        makeMoney.setCreateTime(DateUtils.formatDateDefault(createTime, "yyyy-MM-dd HH:mm:ss"));

        makeMoney.setFailReason(data.getString("refReason"));
        makeMoney.setSettType("D1");

        save(makeMoney);

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(userApp.getUserId() + "");
        List<String> userIds = Collections.singletonList(userApp.getUserId() + "");
        String title = "自动提现成功";
        String content = "到账金额" + (makeMoney.getRealAmount() / 100) + "元，提现门店【" + merchantBaseInfo.getAlias() + "】";
        generalPushUtil.sendAllPlatByAlias(userIds, title, content, "1");
    }

    private static String hiddenBankCertName(String bankCertName) {
        if (bankCertName.length() <= 1) {
            return "*";
        }
        return "*" + bankCertName.substring(1);
    }

}
