package com.order.controller;

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.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsMerPayConfig;
import com.hfkj.entity.BsOrderOutside;
import com.hfkj.entity.BsUserCard;
import com.hfkj.entity.BsUserLoginLog;
import com.hfkj.mer.BsMerPayConfigService;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.card.BsUserCardService;
import com.hfkj.service.order.BsOrderChildService;
import com.hfkj.service.order.BsOrderOutsideService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.service.order.OrderPayService;
import com.hfkj.service.pay.HuiPayService;
import com.hfkj.service.pay.huift.TradeService;
import com.hfkj.service.pay.huift.config.HuiftConfig;
import com.hfkj.service.user.BsUserLoginLogService;
import com.hfkj.sysenum.UserCardTypeEnum;
import com.hfkj.sysenum.mer.PayPlatformEnum;
import com.hfkj.sysenum.order.OrderPayChannelEnum;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
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.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @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 BsOrderChildService orderChildService;
    @Resource
    private OrderPayService orderPayService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private BsUserCardService userCardService;
    @Resource
    private TradeService huiftTradeService;
    @Resource
    private BsMerPayConfigService merPayConfigService;

    @Resource
    private BsOrderOutsideService bsOrderOutsideService;

    @Resource
    private BsUserLoginLogService bsUserLoginLogService;

    @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, "交易订单不处于待支付");
            }
            order.setPayType(OrderPayTypeEnum.type1.getCode());
            Long merId = order.getOrderChildList().get(0).getMerId();
            // 查询平台
            BsMerPayConfig merPay = merPayConfigService.getMerPay(merId, PayPlatformEnum.type1);
            if (merPay == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
            }
            // appIdType  1: 公众号   2：小程序
            if (body.getInteger("appIdType") != null && body.getInteger("appIdType") == 2) {
                body.put("appId", CommonSysConst.getSysConfig().getWechatMaAppid());
            }

            // 请求支付渠道
            Map<Object, Object> preorder = HuiPayService.preorder(merPay.getPayMerNo(), merPay.getPayMerKey(), body.getString("appId"), body.getString("openId"), order);
            for (OrderChildModel orderChild : order.getOrderChildList()) {
                orderChild.setSettleAccount(merPay.getPayMerNo());
                orderChild.setSettleAccountKey(merPay.getPayMerKey());
                orderChildService.editData(orderChild);
            }
            orderService.cacheDelete(order.getOrderNo());
            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, "交易订单不处于待支付");
            }
            order.setPayType(OrderPayTypeEnum.type2.getCode());
            Long merId = order.getOrderChildList().get(0).getMerId();
            // 查询平台
            BsMerPayConfig merPay = merPayConfigService.getMerPay(merId, PayPlatformEnum.type1);
            if (merPay == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
            }
            // 请求支付渠道
            Map<Object, Object> preorder = HuiPayService.preorder(merPay.getPayMerNo(), merPay.getPayMerKey(), null, body.getString("openId"), order);
            for (OrderChildModel orderChild : order.getOrderChildList()) {
                orderChild.setSettleAccount(merPay.getPayMerNo());
                orderChild.setSettleAccountKey(merPay.getPayMerKey());
                orderChildService.editData(orderChild);
            }
            orderService.cacheDelete(order.getOrderNo());
            return ResponseMsgUtil.success(preorder);
        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/huiftPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "贵行V家园支付")
    public ResponseData huiftPay(@RequestBody JSONObject body) {
        try {
            if (body == null|| StringUtils.isBlank(body.getString("orderNo"))) {
                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, "交易订单不处于待支付");
            }
            order.setPayChannel(OrderPayChannelEnum.type3.getCode());
            order.setPayType(OrderPayTypeEnum.type3.getCode());
            /*Long merId = order.getOrderChildList().get(0).getMerId();
            // 查询平台
            BsMerPayConfig merPay = merPayConfigService.getMerPay(merId, PayPlatformEnum.type3);
            if (merPay == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
            }*/

            if (order.getOrderChildList().stream().collect(Collectors.groupingBy(OrderChildModel::getProductType, Collectors.toList())).size() > 1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂不支持合并下单");
            }

            String shopCode = HuiftConfig.shopcode98;
            String signSecret = HuiftConfig.signSecret98;

            if (order.getOrderChildList().get(0).getProductType() == 1) {
                shopCode = HuiftConfig.shopcode95;
                signSecret = HuiftConfig.signSecret95;
            }

            // 请求支付渠道
            JSONObject thirdPreOrder = huiftTradeService.thirdPreOrder(order , shopCode , signSecret);
            for (OrderChildModel orderChild : order.getOrderChildList()) {
                orderChild.setSettleAccount(HuiftConfig.shopcode);
                orderChild.setSettleAccountKey(HuiftConfig.signSecret);
                orderChildService.editData(orderChild);
            }

            order.setPayChannelOrderNo(thirdPreOrder.getString("preOrderNo"));
            orderService.editData(order);

            orderService.cacheDelete(order.getOrderNo());
            return ResponseMsgUtil.success(thirdPreOrder);
        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/cardPay", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "卡支付")
    public ResponseData cardPay(@RequestBody JSONObject body) {
        try {
            // 用户
            UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);
            if (userSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            if (body == null
                    || StringUtils.isBlank(body.getString("orderNo"))
                    || StringUtils.isBlank(body.getString("cardNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询用户与卡号的关系
            BsUserCard card = userCardService.getCard(userSessionObject.getUser().getId(), body.getString("cardNo"));
            if (card == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未绑定卡号");
            }
            // 查询订单
            OrderModel order = orderService.getDetail(body.getString("orderNo"));
            if (!order.getOrderStatus().equals(OrderStatusEnum.status1.getCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付失败！交易订单不处于待支付状态");
            }
            Long merId = order.getOrderChildList().get(0).getMerId();

            if (UserCardTypeEnum.type1.getCode() == card.getType()) {
                // 查询平台
                BsMerPayConfig merPay = merPayConfigService.getMerPay(merId, PayPlatformEnum.type2);
                if (merPay == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户未配置支付");
                }
                for (OrderChildModel orderChild : order.getOrderChildList()) {
                    orderChild.setSettleAccount(merPay.getPayMerNo());
                    orderChild.setSettleAccountKey(merPay.getPayMerKey());
                    orderChildService.editData(orderChild);
                }
                orderService.cacheDelete(order.getOrderNo());
                return ResponseMsgUtil.success(orderPayService.hltCardPay(merPay.getHltInstCode(),order, card));

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的卡号类型");
            }

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

}
