package com.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.WechatPayUtil;
import com.hai.common.pay.entity.WeChatPayReqInfo;
import com.hai.common.pay.util.MD5Util;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.MathUtils;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConst;
import com.hai.config.TuanYouConfig;
import com.hai.config.UnionPayConfig;
import com.hai.config.WxOrderConfig;
import com.hai.entity.*;
import com.hai.enum_type.GasChannel;
import com.hai.enum_type.GasChannelPayPlatformType;
import com.hai.enum_type.MerchantStoreSourceType;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.order.model.CreateOrderChildModel;
import com.hai.order.model.CreateOrderModel;
import com.hai.order.service.OrderService;
import com.hai.order.type.OrderChildGoodsType;
import com.hai.order.type.OrderProductType;
import com.hai.order.type.OrderStatus;
import com.hai.order.utils.OrderUtil;
import com.hai.service.*;
import com.web.config.SysConst;
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 javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 订单支付
 * @className: OrderPayController
 * @author: HuRui
 * @date: 2022/8/30
 **/
@Controller
@RequestMapping("/orderPay")
@Api(value = "订单支付")
public class OrderPayController {

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

    @Resource
    private OrderService orderService;

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighUserPayPasswordService userPayPasswordService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighGasService gasService;

    @Resource
    private HighGasChannelConfigService gasChannelConfigService;

    @Resource
    private HighMerchantTripartitePlatformService merTripartitePlatformService;

    @Resource
    private WechatPayUtil wechatPayUtil;

    @RequestMapping(value="/wxPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "微信支付")
    public ResponseData wxPay(@RequestBody JSONObject body) {
        try {

            if (body == null
                || StringUtils.isBlank(body.getString("orderNo"))
                // || body.getInteger("openIdType") == null
                || StringUtils.isBlank(body.getString("orderScene"))
                || StringUtils.isBlank(body.getString("openId"))
            ) {
                log.error("wxPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询订单
            HighOrder order = orderService.getOrderDetailByNo(body.getString("orderNo"));
            if(!order.getOrderStatus().equals(OrderStatus.STATUS1.getNumber())) {
                log.error("wxPay ERROR", "订单不处于待支付状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
            }

            Integer openIdType = body.getInteger("openIdType");
            // 是否分账
            String profitSharing = "N";
            // 订单标题
            String orderTitle = "购买商品";

            // 微信支付
            String nonce_str = MD5Util.MD5Encode(String.valueOf(ThreadLocalRandom.current().nextInt(10000)), "UTF-8");
            int total_fee = order.getPayPrice().multiply(new BigDecimal("100")).intValue();
            WeChatPayReqInfo weChatPayReqInfo = new WeChatPayReqInfo();
            weChatPayReqInfo.setAppid(SysConst.getSysConfig().getWxPayMchAppId());                                // 公众号id
            weChatPayReqInfo.setMch_id(SysConst.getSysConfig().getWxPayMchId());                                  // 商户号
            if (openIdType != null && openIdType.equals(2)) {
                weChatPayReqInfo.setSub_appid(WxOrderConfig.APPID_HSG_MP);   // 商户号公众号
            } else {
                weChatPayReqInfo.setSub_appid(WxOrderConfig.APPID_HSG_MINI); // 嗨森逛小程序
            }

            // 订单产品类型
            OrderProductType productType = OrderProductType.getDataByType(order.getProductType());
            if (productType != null) {
                orderTitle = productType.getName();
            }

            if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE6.getNumber())) {
                // 查询油站
                HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(order.getHighChildOrderList().get(0).getGoodsId());
                if (store == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的加油站");
                }
                if (order.getTotalPrice().compareTo(gasService.getMerPriceByMerId(store.getMerchantId())) == 1) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法进行支付，请联系平台客服");
                }

                if (store.getSourceType().equals(MerchantStoreSourceType.type1.getNumber())) {
                    // 查询支付配置
                    HighGasChannelConfig gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type1, GasChannelPayPlatformType.type1 );
                    if (gasChannelConfig == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置支付参数，请稍后重试！");
                    }
                    weChatPayReqInfo.setSub_mch_id(gasChannelConfig.getPayPlatformMerNo());
                    profitSharing = gasChannelConfig.getProfitSharingStatus().equals(true)?"Y":"N";

                    if (store.getSourceType().equals(1)) {
                        // 预存类型  0：非预存  1：预存门店
                        if (store.getPrestoreType().equals(0)) {
                            // 第三方平台
                            HighMerchantTripartitePlatform merTripartitePlatform = merTripartitePlatformService.getDetail(store.getMerchantId(), 1);
                            if (merTripartitePlatform != null) {
                                weChatPayReqInfo.setSub_mch_id(merTripartitePlatform.getPlatformMerNumber());
                                // 是否分账
                                profitSharing = merTripartitePlatform.getProfitSharingStatus().equals(true)?"Y":"N";
                            }
                        }
                    }

                } else if (store.getSourceType().equals(MerchantStoreSourceType.type2.getNumber())) {

                    // 查询支付配置
                    HighGasChannelConfig gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type2,GasChannelPayPlatformType.type1 );
                    if (gasChannelConfig == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置支付参数，请稍后重试！");
                    }
                    weChatPayReqInfo.setSub_mch_id(gasChannelConfig.getPayPlatformMerNo());
                    profitSharing = gasChannelConfig.getProfitSharingStatus().equals(true)?"Y":"N";

                } else if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {

                    // 查询支付配置
                    HighGasChannelConfig gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type3,GasChannelPayPlatformType.type1 );
                    if (gasChannelConfig == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置支付参数，请稍后重试！");
                    }
                    weChatPayReqInfo.setSub_mch_id(gasChannelConfig.getPayPlatformMerNo());
                    profitSharing = gasChannelConfig.getProfitSharingStatus().equals(true)?"Y":"N";

                } else if (store.getSourceType().equals(MerchantStoreSourceType.type4.getNumber())) {
                    // 查询支付配置
                    HighGasChannelConfig gasChannelConfig = gasChannelConfigService.getConfig(GasChannel.type4,GasChannelPayPlatformType.type1 );
                    if (gasChannelConfig == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置支付参数，请稍后重试！");
                    }
                    weChatPayReqInfo.setSub_mch_id(gasChannelConfig.getPayPlatformMerNo());
                    profitSharing = gasChannelConfig.getProfitSharingStatus().equals(true)?"Y":"N";

                } else {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置支付参数，请稍后重试！");
                }

            } else if (order.getProductType().equals(OrderProductType.PRODUCT_TYPE8.getNumber())) {
                weChatPayReqInfo.setSub_mch_id(WxOrderConfig.MCH_ID_1619676214);
            } else {
                weChatPayReqInfo.setSub_mch_id(WxOrderConfig.MCH_ID_1609882817);
            }

            // weChatPayReqInfo.setOpenid(openId);
            weChatPayReqInfo.setSub_openid(body.getString("openId"));
            weChatPayReqInfo.setNonce_str(nonce_str);                                           // 随机字符串
            weChatPayReqInfo.setBody(orderTitle);                                           	// 商品描述
            weChatPayReqInfo.setOut_trade_no(order.getOrderNo());                			    // 商户订单号
            weChatPayReqInfo.setTotal_fee(total_fee);                                           // 总金额
            weChatPayReqInfo.setSpbill_create_ip("122.9.135.148");                              // 终端ip
            weChatPayReqInfo.setNotify_url(SysConst.getSysConfig().getWxPayNotifyUrl());        // 通知url
            weChatPayReqInfo.setTrade_type("JSAPI");                                            // 交易类型
            weChatPayReqInfo.setAttach(body.getString("orderScene"));                       // 附件参数
            weChatPayReqInfo.setProfit_sharing(profitSharing);                                  // 是否分账 Y：是  N：否

            //附加数据，区分订单类型
            Map<String,String> payMap = new HashMap<>();
            payMap.put("app_id", weChatPayReqInfo.getSub_appid());
            payMap.put("api_key", SysConst.getSysConfig().getWxPayApiKey());
            payMap.put("unified_order_url", SysConst.getSysConfig().getWxPayUnifiedOrderUrl());
            SortedMap<Object, Object> sortedMap = wechatPayUtil.goWechatPay(weChatPayReqInfo,payMap);

            order.setAccountMerchantNum(weChatPayReqInfo.getSub_mch_id());
            order.setProfitSharingStatus(profitSharing.equals("Y")?true:false);
            orderService.updateOrderData(order);

            return ResponseMsgUtil.success(sortedMap);

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

    @RequestMapping(value="/oilCardPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "嗨森逛油卡支付")
    public ResponseData oilCardPay(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("orderNo"))
                    || StringUtils.isBlank(body.getString("cardNo"))
                    || StringUtils.isBlank(body.getString("password"))) {
                log.error("oilCardPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 获取当前操作人信息
            HighUserModel userInfoModel = userCenter.getSessionModel(HighUserModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            String password = body.getString("password");

            // 查询用户支付密码
            HighUserPayPassword userPayPassword = userPayPasswordService.getDetailByUser(userInfoModel.getHighUser().getId());
            if (userPayPassword == null) {
                log.error("orderToPay error!", "未设置支付密码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
            }
            if (StringUtils.isBlank(password)) {
                log.error("orderToPay error!", "未输入支付密码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_ENTER_USER_PAY_PWD, "");
            }
            // 支付密码是否正确
            if (!AESEncodeUtil.aesEncrypt(password).equals(userPayPassword.getPassword())) {
                log.error("orderToPay error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PAY_PWD_ERROR, "");
            }

            // 查询订单
            HighOrder order = orderService.getOrderDetailByNo(body.getString("orderNo"));
            if(!order.getOrderStatus().equals(OrderStatus.STATUS1.getNumber())) {
                log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
            }

            return ResponseMsgUtil.success(null);

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

    @RequestMapping(value="/hltCardPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "贵州汇联通工会卡支付")
    public ResponseData hltCardPay(@RequestBody JSONObject body) {
        try {

            if (body == null
                    || StringUtils.isBlank(body.getString("orderNo"))
                    // || body.getInteger("openIdType") == null
                    || StringUtils.isBlank(body.getString("orderScene"))
                    || StringUtils.isBlank(body.getString("openId"))
            ) {
                log.error("wxPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }


            return ResponseMsgUtil.success(null);

        } catch (Exception e) {
            log.error("OrderController -> create() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }
/*
    @RequestMapping(value="/unionPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "银联支付")
    public ResponseData unionPay(@RequestBody String reqBodyStr, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(reqBodyStr)) {
                log.error("orderToPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            JSONObject jsonObject = JSONObject.parseObject(reqBodyStr);
            Long orderId = jsonObject.getLong("orderId");
            if ( orderId == null) {
                log.error("orderToPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighOrder order = highOrderService.getOrderById(orderId);
            if(order == null) {
                log.error("OrderController --> orderToPay() ERROR", "未找到订单信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_ORDER, "");
            }
            //校验订单状态  订单状态：1 待支付  2 已支付  3.已完成  4. 已退款  5.已取消
            if(order.getOrderStatus() != 1) {
                log.error("OrderController --> orderToPay() ERROR", "订单不处于待支付状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_NO_STAY_PAY, "");
            }

            // 商品类型   1:卡卷  2:金币充值  3:加油站
            for (HighChildOrder childOrder : order.getHighChildOrderList()) {
                if (childOrder.getGiveawayType() == false && childOrder.getGoodsType() == 1) {
                    HighCoupon coupon = highCouponService.getCouponById(childOrder.getGoodsId());
                    // 支付类型：1.微信支付 2.金币支付
//                    if (coupon.getPayType() != 1) {
//                        log.error("OrderController --> orderToPay() ERROR", "只支持微信支持");
//                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + ",只支持微信支付");
//                    }
                }

                if (childOrder.getGoodsType() == 3) {
                    if (highOrderService.getGasTheDayOrderNum(order.getMemId()) >= 1) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已达到每日加油次数上限");
                    }
                    // 查询加油站
                    HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(childOrder.getGoodsId());
                    if (store == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已达到每日加油次数上限");
                    }
                    // 来源类型  1：平台自建   2：团油
                    if (store.getSourceType().equals(2)) {
                        // 查询账号余额
                        JSONObject accountInfo2JD = TuanYouConfig.queryCompanyAccountInfo2JD();
                        JSONArray result = accountInfo2JD.getJSONArray("result");
                        for (Object accountObject : result) {
                            JSONObject account = (JSONObject)accountObject;
*//*                            // 1:汽油:2:柴油;3:天然气
                            if (account.getInteger("energyType") == childOrder.getGasOilType()) {
                                // 支付金额 大于 团油账号余额
                                if(order.getPayPrice().compareTo(account.getBigDecimal("accountBalance")) == 1){
                                    log.error("OrderController --> orderToPay() ERROR", "无法进行支付，请联系平台客服");
                                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法进行支付，请联系平台客服");
                                }
                            }*//*
                        }
                    }
                    // 来源类型  1：平台自建   2：团油
                    if (store.getSourceType().equals(MerchantStoreSourceType.type3.getNumber())) {
                        BigDecimal account = new BigDecimal("0");
                        // 查询账号余额
                        HighMerchantAccount merAccount = merchantAccountService.getMerAccountDetail(store.getMerchantId());
                        if (merAccount != null) {
                            account = merAccount.getAmounts().subtract(merchantAccountService.countMerGasOilAmount(store.getMerchantId()));
                        }
                        // 客户加油金额 大于 商户账号余额
                        if(order.getTotalPrice().compareTo(account) == 1) {
                            log.error("OrderController --> orderToPay() ERROR", "暂时无法进行支付，请联系平台客服");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法进行支付，请联系平台客服");
                        }
                    }
                }
            }

            return ResponseMsgUtil.success(unionPayConfig.upPreOrder(UnionPayConfig.MER_ID3, UnionPayConfig.TERM_ID3, order.getOrderNo(), order.getPayPrice(), "购买商品", CommonSysConst.getSysConfig().getUnionPayNotifyUrl(), request));
        } catch (Exception e) {
            log.error("orderToPay error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }*/

}
