package com.cweb.notify;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.LaKaLaLedgerService;
import com.hfkj.channel.lakala.LaKaLaWalletService;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * 拉卡拉通知
 * @author hurui
 */
@Controller
@Api(value = "拉卡拉通知")
@RequestMapping(value = "/laKaLaNotify")
public class LaKaLaController {

    private static Logger log = LoggerFactory.getLogger(LaKaLaController.class);

    @Resource
    private BsTradeOrderService tradeOrderService;

    @Resource
    private BsTradeOrderMsgService tradeOrderMsgService;
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerLedgerApplyService merLedgerApplyService;
    @Resource
    private BsMerLedgerReceiverService merLedgerReceiverService;
    @Resource
    private BsMerLedgerReceiverApplyService merLedgerReceiverApplyService;
    @Resource
    private LaKaLaLedgerService laKaLaLedgerService;
    @Resource
    private LaKaLaWalletService laKaLaWalletService;

    @RequestMapping(value="/microPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "交易【被扫】通知")
    public void microPay(@RequestBody String reqBody, HttpServletResponse response) {
        try {
            log.info("交易【被扫】通知", reqBody);
            System.out.println(reqBody);

            JSONObject body = JSONObject.parseObject(reqBody);
            // 请求记录
            BsTradeOrderMsg orderMsg = new BsTradeOrderMsg();
            orderMsg.setOutTradeNo(body.getString("out_trade_no"));
            orderMsg.setType(TradeOrderMsgTypeEnum.type2.getNumber());
            orderMsg.setResponseContent(reqBody);
            tradeOrderMsgService.editTradeOrderMsg(orderMsg);

            // 查询订单
            BsTradeOrder order = tradeOrderService.getOrderByOutTradeNo(body.getString("out_trade_no"));
            if (order != null) {
                Map<String,Object> other = new HashMap<>();
                other.put("log_no", body.getString("log_no"));
                other.put("acc_trade_no", body.getString("acc_trade_no"));
                other.put("card_type", body.getString("card_type"));

                if (body.getString("acc_settle_amount") != null) {
                    other.put("acc_settle_amount", body.getBigDecimal("acc_settle_amount").divide(new BigDecimal("100")));
                }
                if (body.getString("acc_discount_amount") != null) {
                    other.put("acc_discount_amount", body.getBigDecimal("acc_discount_amount").divide(new BigDecimal("100")));
                }
                if (body.getString("acc_mdiscount_amount") != null) {
                    other.put("acc_mdiscount_amount", body.getBigDecimal("acc_mdiscount_amount").divide(new BigDecimal("100")));
                }

                tradeOrderService.paySuccess(
                        body.getString("out_trade_no"),
                        body.getString("trade_no"),
                        PlatformTypeEnum.type1,
                        TradeOrderPayModeEnum.getNameByCode(body.getString("account_type")),
                        body.getBigDecimal("total_amount").divide(new BigDecimal("100")),
                        body.getString("merchant_no"),
                        other
                );

/*                order.setPayMode(body.getString("account_type"));
                order.setPlatformType(PlatformTypeEnum.type1.getNumber());
                order.setPlatformTradeNo(body.getString("trade_no"));
                order.setPlatformLogNo(body.getString("log_no"));
                order.setAccTradeNo(body.getString("acc_trade_no"));
                order.setTradeActualAmount(body.getBigDecimal("payer_amount").divide(new BigDecimal("100")));
                order.setCardType(body.getString("card_type"));
                order.setStatus(TradeOrderStatusEnum.status3.getNumber());
                order.setPayTime(new Date());
                if (body.getString("acc_discount_amount") != null) {
                    order.setAccDiscountAmount(body.getBigDecimal("acc_discount_amount").divide(new BigDecimal("100")));
                }
                if (body.getString("acc_mdiscount_amount") != null) {
                    order.setAccMdiscountAmount(body.getBigDecimal("acc_mdiscount_amount").divide(new BigDecimal("100")));
                }
                tradeOrderService.editOrder(order);*/
            }

        } catch (Exception e) {
            log.error("login error!",e);
        } finally {
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                JSONObject result = new JSONObject();
                result.put("code", "SUCCESS");
                result.put("message", "执行成功");
                out.write(result.toJSONString().getBytes());
                out.flush();
                out.close();
            } catch (Exception e) {

            }

        }
    }

    @RequestMapping(value="/applyLedgerMer",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "开通分账业务通知")
    public void applyLedgerMer(@RequestBody String reqBody) {
        try {
            log.info("开通分账业务通知", reqBody);
            System.out.println(reqBody);

            JSONObject respData = JSONObject.parseObject(reqBody);

            BsMerLedgerApply ledgerApply = merLedgerApplyService.getApplyByApplyId(respData.getString("applyId"));
            if (ledgerApply != null) {
                ledgerApply.setNotifyBody(reqBody);
                merLedgerApplyService.editMerLedgerApply(ledgerApply);

                // 查询商户分账信息
                BsMerLedger merLedger = merLedgerService.getMerLedgerById(ledgerApply.getMerLedgerId());
                if (merLedger != null) {
                    // 审核状态	1:通过，2拒绝
                    if (respData.getString("auditStatus").equals("1")) {
                        merLedger.setStatus(MerLedgerStatusEnum.status1.getNumber());
                        merLedgerService.editMerLedger(merLedger);
                        // 延迟3秒
                        Thread.sleep(3000);

                        // 提现通知地址
                        String notifyUrl = CommonSysConst.getSysConfig().getDomainName()+"/crest/merWithdrawal/notify?cupNo="+merLedger.getCupNo();

                        // 配置账户自动结算
                        laKaLaWalletService.ewalletSettleProfile(1,merLedger.getCupNo(), "02", "06", notifyUrl);

                        // 配置分账接收方账户自动结算
                        laKaLaWalletService.ewalletSettleProfile(2,merLedger.getReceiverNo(), "02", "06", notifyUrl);

                    } else {
                        merLedger.setStatus(MerLedgerStatusEnum.status3.getNumber());
                        merLedger.setRejectReason(respData.getString("remark"));
                        merLedgerService.editMerLedger(merLedger);
                    }
                }
            }

        } catch (Exception e) {
            log.error("login error!",e);
        }

    }

    @RequestMapping(value="/applyBindReceiver",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分账关系绑定申请")
    public void applyBindReceiver(@RequestBody String reqBody) {
        try {
            log.info("分账关系绑定申请通知", reqBody);
            System.out.println(reqBody);

            JSONObject respData = JSONObject.parseObject(reqBody);

            // 分手接收方申请记录
            BsMerLedgerReceiverApply receiverApply = merLedgerReceiverApplyService.getReceiverApplyByApplyId(respData.getString("applyId"));
            if (receiverApply != null) {
                receiverApply.setNotifyBody(reqBody);
                // 	1:通过，2拒绝
                receiverApply.setStatus(
                        respData.getString("auditStatus").equals("1")
                        ?MerLedgerReceiverApplyStatusEnum.status2.getNumber()
                        :MerLedgerReceiverApplyStatusEnum.status3.getNumber());
                receiverApply.setRejectReason(respData.getString("remark"));
                merLedgerReceiverApplyService.editReceiverApply(receiverApply);

                // 分账接收方
                BsMerLedgerReceiver ledgerReceiver = merLedgerReceiverService.getMerLedgerReceiver(receiverApply.getMerId(), receiverApply.getReceiverNo());
                if (ledgerReceiver != null) {
                    ledgerReceiver.setStatus(
                            receiverApply.getStatus().equals(
                                    MerLedgerReceiverApplyStatusEnum.status2.getNumber())
                                    ?MerLedgerReceiverStatusEnum.status1.getNumber()
                                    :MerLedgerReceiverStatusEnum.status2.getNumber()
                    );
                    ledgerReceiver.setAuditStatus(
                            receiverApply.getStatus().equals(MerLedgerReceiverApplyStatusEnum.status2.getNumber())
                            ?MerLedgerReceiverAuditStatusEnum.status2.getNumber()
                            :MerLedgerReceiverAuditStatusEnum.status3.getNumber()
                    );
                    ledgerReceiver.setRejectReason(receiverApply.getRejectReason());
                    merLedgerReceiverService.editMerLedgerReceiver(ledgerReceiver);
                }
            }

        } catch (Exception e) {
            log.error("login error!",e);
        }

    }

    @RequestMapping(value="/applyBindUnReceiver",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分账关系绑定申请")
    public void applyBindUnReceiver(@RequestBody String reqBody) {
        try {
            log.info("分账关系绑定申请通知", reqBody);
            System.out.println(reqBody);

            JSONObject respData = JSONObject.parseObject(reqBody);

            // 分手接收方申请记录
            BsMerLedgerReceiverApply receiverApply = merLedgerReceiverApplyService.getReceiverApplyByApplyId(respData.getString("applyId"));
            if (receiverApply != null) {
                receiverApply.setNotifyBody(reqBody);
                // 	1:通过，2拒绝
                receiverApply.setStatus(
                        respData.getString("auditStatus").equals("1")
                                ?MerLedgerReceiverApplyStatusEnum.status2.getNumber()
                                :MerLedgerReceiverApplyStatusEnum.status3.getNumber());
                receiverApply.setRejectReason(respData.getString("auditStatusText"));
                merLedgerReceiverApplyService.editReceiverApply(receiverApply);

                // 分账接收方
                BsMerLedgerReceiver ledgerReceiver = merLedgerReceiverService.getMerLedgerReceiver(receiverApply.getMerId(), receiverApply.getReceiverNo());
                if (ledgerReceiver != null) {
                    ledgerReceiver.setStatus(
                            receiverApply.getStatus().equals(
                                    MerLedgerReceiverApplyStatusEnum.status2.getNumber())
                                    ?MerLedgerReceiverStatusEnum.status0.getNumber()
                                    :MerLedgerReceiverStatusEnum.status2.getNumber()
                    );
                    ledgerReceiver.setAuditStatus(
                            receiverApply.getStatus().equals(MerLedgerReceiverApplyStatusEnum.status2.getNumber())
                                    ?MerLedgerReceiverAuditStatusEnum.status2.getNumber()
                                    :MerLedgerReceiverAuditStatusEnum.status5.getNumber()
                    );
                    ledgerReceiver.setRejectReason(receiverApply.getRejectReason());
                    merLedgerReceiverService.editMerLedgerReceiver(ledgerReceiver);
                }
            }

        } catch (Exception e) {
            log.error("login error!",e);
        }

    }

}
