package com.ruoyi.klk.notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lkl.laop.sdk.LKLSDK;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.frequency.klkaccount.entity.KlkAccount;
import com.ruoyi.frequency.klkaccount.mapper.KlkAccountMapper;
import com.ruoyi.frequency.klkwithdrawalrecord.entity.KlkWithdrawalRecord;
import com.ruoyi.frequency.klkwithdrawalrecord.mapper.KlkWithdrawalRecordMapper;
import com.ruoyi.frequency.withdrawalrecord.entity.WithdrawalRecord;
import com.ruoyi.frequency.withdrawalrecord.mapper.WithdrawalRecordMapper;
import com.ruoyi.klk.util.CommonService;
import com.ruoyi.klk.util.InitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api/notify")
@Slf4j
public class NotificationHandler {

    @Autowired
    private KlkAccountMapper klkAccountMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private InitUtil initUtil;

    /**
     * 分账关系绑定结果回调处理
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/bindAccount")
    public Map<String, String> messageHandle(HttpServletRequest request) throws Exception {
        log.info("分账关系绑定结果开始回调...");

        // 1. 配置初始化
        initUtil.doInit();

        //验签并解析请求
        String body = LKLSDK.notificationHandle(request);

        //业务处理
        JSONObject jsonObject = JSON.parseObject(body);
        String receiverNo = jsonObject.getString("receiverNo");
        if ("1".equals(jsonObject.getString("auditStatus"))) {
            // 绑定成功
            klkAccountMapper.update(null, new LambdaUpdateWrapper<KlkAccount>().set(KlkAccount::getBindStatus, 3)
                    .eq(KlkAccount::getReceiverNo, receiverNo));
        } else {
            // 绑定失败
            klkAccountMapper.update(null, new LambdaUpdateWrapper<KlkAccount>().set(KlkAccount::getBindStatus, 4)
                    .set(KlkAccount::getBindFailReason, jsonObject.getString("remark")).eq(KlkAccount::getReceiverNo, receiverNo));
        }

        return commonService.getKlkCommonResp();
    }

    @Autowired
    private KlkWithdrawalRecordMapper klkWithdrawalRecordMapper;

    @Autowired
    private WithdrawalRecordMapper withdrawalRecordMapper;

    public static void main(String[] args) {
        //验签并解析请求
        String body = "{\"ewalletId\":\"310031838650\",\"reqDate\":\"20240531\",\"payNo\":\"02001011010121915753\",\"payType\":\"04\",\"drawJnl\":\"240531154102568001176346\",\"drawAmt\":\"2.60\",\"drawFee\":\"0.00\",\"bankId\":\"392405317919539283\",\"acctNo\":\"621485******8533\",\"acctName\":\"*耀\",\"acctType\":\"2\",\"nbkName\":\"招商银行\",\"mercId\":\"SR2024000026603\",\"drawState\":\"DRAW.SUCCESS\",\"drawStateDesc\":\"提款成功\",\"drawMode\":\"D1\",\"batchAutoSettle\":\"01\",\"batchNo\":\"\",\"merOrgNo\":\"100012\",\"merOrderNo\":\"\",\"settleNo\":\"202406010602390002720722\",\"completeTime\":\"2024-06-01 06:02:58\",\"memo\":\"结算成功\",\"createdTime\":\"2024-05-31 15:41:02\",\"refund\":\"0\",\"bankNo\":\"03080000\",\"bankName\":\"招商银行\",\"clearingBankCode\":\"03080000\",\"remark\":\"\",\"summary\":\"\",\"skPrepayAmt\":\"2.60\",\"skDrawFee\":\"0.00\",\"zfPrepayAmt\":\"0.00\",\"zfDrawFee\":\"0.00\",\"zfPrepaySeq\":\"\",\"zfPayNo\":\"\"}";


        //业务处理
        JSONObject respData = JSON.parseObject(body);
        String drawJnl = respData.getString("drawJnl");
        System.out.println(drawJnl);
    }

    /**
     * 提现结果回调处理
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/withdrawal")
    public Map<String, String> withdrawal(HttpServletRequest request) throws Exception {
        log.info("提现结果开始回调...");

        // 1. 配置初始化
        initUtil.doInit();

        //验签并解析请求
        String body = LKLSDK.notificationHandle(request);

        //业务处理
        JSONObject respData = JSON.parseObject(body);
        String drawJnl = respData.getString("drawJnl");
        Integer withdrawalStatus = getWithdrawalStatus(respData.getString("drawState"));
        klkWithdrawalRecordMapper.update(null, new LambdaUpdateWrapper<KlkWithdrawalRecord>()
                .eq(KlkWithdrawalRecord::getDelFlag, PublicCommon.启用)
                .eq(KlkWithdrawalRecord::getDrawJnl, drawJnl)
                .set(KlkWithdrawalRecord::getWithdrawalStatus, withdrawalStatus)
                .set(KlkWithdrawalRecord::getWithdrawalRemark, respData.getString("memo")));
        // 如果提现成功则修改提现状态
        if (withdrawalStatus == 3) {
            klkWithdrawalRecordMapper.update(null, new LambdaUpdateWrapper<KlkWithdrawalRecord>()
                    .set(KlkWithdrawalRecord::getTransferFinishTime, new Date())
                    .eq(KlkWithdrawalRecord::getDrawJnl, drawJnl));
            KlkWithdrawalRecord klkWithdrawalRecord = klkWithdrawalRecordMapper.selectOne(new LambdaQueryWrapper<KlkWithdrawalRecord>()
                    .eq(KlkWithdrawalRecord::getDelFlag, PublicCommon.启用)
                    .eq(KlkWithdrawalRecord::getDrawJnl, drawJnl));
            withdrawalRecordMapper.update(null, new LambdaUpdateWrapper<WithdrawalRecord>()
                    .set(WithdrawalRecord::getStatus, 5)
                    .eq(WithdrawalRecord::getId, klkWithdrawalRecord.getWithdrawalRecordId()));
        }

        return commonService.getKlkCommonResp();
    }

    private Integer getWithdrawalStatus(String drawState) {
        //提现状态：1-处理中 2-已受理 3-成功 4-失败 5-冻结 -1-未关联卡拉卡平台
        if ("DRAW.PROCESSING".equals(drawState)) {
            return 1;
        } else if ("DRAW.ACCEPTED".equals(drawState)) {
            return 2;
        } else if ("DRAW.SUCCESS".equals(drawState)) {
            return 3;
        } else if ("DRAW.FAILED".equals(drawState)) {
            return 4;
        } else if ("DRAW.FREEZE".equals(drawState)) {
            return 5;
        } else {
            return -1;
        }
    }
}
