package com.cweb.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.RandomUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsGasChannelConfig;
import com.hfkj.entity.BsMerchant;
import com.hfkj.entity.BsMerchantPayConfig;
import com.hfkj.entity.BsOrderSettle;
import com.hfkj.model.ResponseData;
import com.hfkj.model.order.OrderModel;
import com.hfkj.pay.HuiPayService;
import com.hfkj.service.merchant.BsMerchantPayConfigService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.order.BsGasChannelConfigService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.service.order.BsOrderSettleService;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
import com.hfkj.sysenum.order.OrderSettleLedgerStatusEnum;
import com.hfkj.sysenum.order.OrderStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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 java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @className: OrderController
 * @author: HuRui
 * @date: 2024/4/30
 **/
@Controller
@RequestMapping(value="/pay")
@Api(value="支付业务")
public class OrderPayController {

    Logger log = LoggerFactory.getLogger(OrderPayController.class);
    @Resource
    private BsOrderService orderService;
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private BsMerchantPayConfigService merPayConfigService;
    @Resource
    private BsOrderSettleService orderSettleService;
    @Resource
    private BsGasChannelConfigService gasChannelConfigService;

    @RequestMapping(value="/wechat",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "微信")
    public ResponseData wechat(@RequestBody JSONObject body) {
        try {
            if (body == null
                || StringUtils.isBlank(body.getString("orderNo"))
                || StringUtils.isBlank(body.getString("openId"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询订单
            OrderModel order = orderService.getDetail(body.getString("orderNo"));
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
            }
            if (!order.getOrderStatus().equals(OrderStatusEnum.status1.getCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易订单不处于待支付");
            }
            String merNo = order.getOrderChildList().get(0).getMerNo();
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(merNo);
            if (merchant == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }

            String payMerNo = "";
            String payMerKey = "";
            Boolean ledgerAccountFlag = false;

            if (merchant.getSourceType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                // 查询平台
                BsMerchantPayConfig merPay = merPayConfigService.getConfig(merNo);
                if (merPay == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
                }
                payMerNo = merPay.getChannelMerNo();
                payMerKey = merPay.getChannelMerKey();
                ledgerAccountFlag = merPay.getLedgerAccountFlag();

            } else if (merchant.getSourceType().equals(MerchantSourceTypeEnum.type2.getNumber())
                || merchant.getSourceType().equals(MerchantSourceTypeEnum.type3.getNumber())
                || merchant.getSourceType().equals(MerchantSourceTypeEnum.type4.getNumber())
            ) {
                // 查询渠道支付配置
                BsGasChannelConfig payConfig = gasChannelConfigService.getDetail(MerchantSourceTypeEnum.getDataByType(merchant.getSourceType()));
                if (payConfig == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
                }
                if (payConfig.getTradeStatus().equals(false)) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "油站维护中暂停交易！");
                }
                payMerNo = payConfig.getChannelMerNo();
                payMerKey = payConfig.getChannelMerKey();
                ledgerAccountFlag = payConfig.getLedgerAccountFlag();
            }
            order.setPayType(OrderPayTypeEnum.type2.getCode());

            // appIdType  1: 公众号   2：小程序
            if (body.getInteger("appIdType") != null && body.getInteger("appIdType") == 2) {
                body.put("appId", CommonSysConst.getSysConfig().getWxMaAppId());
            }
            // 请求支付渠道
            Map<Object, Object> preorder = HuiPayService.preorder(payMerNo, payMerKey, body.getString("appId"), body.getString("openId"), ledgerAccountFlag, order);
            // 交易入账
            BsOrderSettle orderSettle = orderSettleService.getData(order.getOrderNo());
            if (orderSettle == null) {
                orderSettle = new BsOrderSettle();
            }
            orderSettle.setMerNo(merNo);
            orderSettle.setOrderNo(order.getOrderNo());
            orderSettle.setSettleMerNo(payMerNo);
            orderSettle.setSettleMerKey(payMerKey);
            orderSettle.setSettleAmount(order.getPayRealPrice());
            orderSettle.setLedgerFlag(ledgerAccountFlag);
            if (orderSettle.getLedgerFlag()) {
                orderSettle.setLedgerAmount(new BigDecimal("0"));
                orderSettle.setLedgerOrderNo("L"+ DateUtil.date2String(new Date(), "yyMMddHHmmss") + RandomUtils.number(3, false));
                orderSettle.setLedgerStatus(OrderSettleLedgerStatusEnum.status0.getCode());
            }
            orderSettleService.editData(orderSettle);

            return ResponseMsgUtil.success(preorder);

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/alipay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "支付宝")
    public ResponseData alipay(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("orderNo"))
                    || StringUtils.isBlank(body.getString("userId"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询订单
            OrderModel order = orderService.getDetail(body.getString("orderNo"));
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
            }
            if (order.getOrderStatus().equals(OrderStatusEnum.status2.getCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易订单不处于待支付");
            }
            String merNo = order.getOrderChildList().get(0).getMerNo();
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(merNo);
            if (merchant == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }

            String payMerNo = "";
            String payMerKey = "";
            Boolean ledgerAccountFlag = false;

            if (merchant.getSourceType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                // 查询平台
                BsMerchantPayConfig merPay = merPayConfigService.getConfig(merNo);
                if (merPay == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
                }
                payMerNo = merPay.getChannelMerNo();
                payMerKey = merPay.getChannelMerKey();
                ledgerAccountFlag = merPay.getLedgerAccountFlag();

            } else if (merchant.getSourceType().equals(MerchantSourceTypeEnum.type2.getNumber())) {
                // 查询渠道支付配置
                BsGasChannelConfig payConfig = gasChannelConfigService.getDetail(MerchantSourceTypeEnum.type2);
                if (payConfig == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
                }
                if (payConfig.getTradeStatus().equals(false)) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "油站维护中暂停交易！");
                }
                payMerNo = payConfig.getChannelMerNo();
                payMerKey = payConfig.getChannelMerKey();
                ledgerAccountFlag = payConfig.getLedgerAccountFlag();
            }
            order.setPayType(OrderPayTypeEnum.type1.getCode());
            // 请求支付渠道
            Map<Object, Object> preorder = HuiPayService.preorder(payMerNo, payMerKey, null, body.getString("userId"), ledgerAccountFlag, order);

            // 交易入账
            BsOrderSettle orderSettle = orderSettleService.getData(order.getOrderNo());
            if (orderSettle == null) {
                orderSettle = new BsOrderSettle();
            }
            orderSettle.setMerNo(merNo);
            orderSettle.setOrderNo(order.getOrderNo());
            orderSettle.setSettleMerNo(payMerNo);
            orderSettle.setSettleMerKey(payMerKey);
            orderSettle.setSettleAmount(order.getPayRealPrice());
            orderSettle.setLedgerFlag(ledgerAccountFlag);
            if (orderSettle.getLedgerFlag()) {
                orderSettle.setLedgerAmount(order.getPayRealPrice());
                orderSettle.setLedgerOrderNo("L"+ DateUtil.date2String(new Date(), "yyMMddHHmmss") + RandomUtils.number(3, false));
                orderSettle.setLedgerStatus(OrderSettleLedgerStatusEnum.status0.getCode());
            }
            orderSettleService.editData(orderSettle);

            return ResponseMsgUtil.success(preorder);
        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
