package com.cweb.controller.pay;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
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.OrderType;
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.SessionObject;
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.QianZhuConfig;
import com.hai.config.UnionPayConfig;
import com.hai.entity.*;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.HighOrderService;
import com.hai.service.HighUserCardService;
import com.hai.service.HighUserPayPasswordService;
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;

@Controller
@RequestMapping(value = "/thirdOrder")
@Api(value = "第三方订单支付接口")
public class ThirdOrderController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private WechatPayUtil wechatPayUtil;

    @Resource
    private HighUserCardService highUserCardService;

    @Resource
    private UnionPayConfig unionPayConfig;

    @Resource
    private HighUserPayPasswordService highUserPayPasswordService;

    @RequestMapping(value="/orderToPayByWx",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "微信订单支付发起支付")
    public ResponseData orderToPayByWx(@RequestBody String reqBodyStr) {
        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");
            Integer openIdType = jsonObject.getInteger("openIdType"); // openId类型 1：小程序  2：公众号
            String openId = jsonObject.getString("openId");       // openId
            if (orderId == null || StringUtils.isBlank(openId)) {
                log.error("orderToPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 订单
            HighOrder order = highOrderService.getOrderById(jsonObject.getLong("orderId"));

            if (order == null) {
                log.error("orderToPay error!", "未找到订单信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单信息");
            }

            // 订单状态 ： 订单支付状态 ： 101.待支付 102.已支付 100.已完成 104.已取消 105.已退款
            if (order.getOrderStatus() != 1) {
                log.error("orderToPayByWx error!", "无法支付，订单不处于待支付状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法支付，订单不处于待支付状态");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("orderNo", order.getOrderNo());
            map.put("payPrice", order.getPayRealPrice());
            if (order.getHighChildOrderList().get(0).getGoodsType() == 4) {
                map.put("orderScene", OrderType.KFC_ORDER.getModuleCode());
            } else if (order.getHighChildOrderList().get(0).getGoodsType() == 9) {
                map.put("orderScene", OrderType.STARBUCKS_ORDER.getModuleCode());
            } else if (order.getHighChildOrderList().get(0).getGoodsType() == 10) {
                map.put("orderScene", OrderType.THIRD_ORDER.getModuleCode());
            }

            // 肯德基订单  星巴克订单
            map.put("body", "购买第三方产品");
            map.put("subject","购买第三方产品");

            //微信支付
            String nonce_str = MD5Util.MD5Encode(String.valueOf(ThreadLocalRandom.current().nextInt(10000)), "UTF-8");
            int total_fee = MathUtils.objectConvertBigDecimal(map.get("payPrice")).multiply(new BigDecimal("100")).intValue();
            WeChatPayReqInfo weChatPayReqInfo = new WeChatPayReqInfo();
            weChatPayReqInfo.setAppid(SysConst.getSysConfig().getWxMchAppId());                                //公众号id
            weChatPayReqInfo.setMch_id(SysConst.getSysConfig().getWxMchId());                               //商户号
            if (openIdType != null && openIdType.equals(2)) {
                weChatPayReqInfo.setSub_appid("wxa075e8509802f826"); //商户号公众号
            } else {
                weChatPayReqInfo.setSub_appid(SysConst.getSysConfig().getWxSubAppId());//小程序
            }
            weChatPayReqInfo.setSub_mch_id("1614670195");
            weChatPayReqInfo.setSub_openid(openId);
            weChatPayReqInfo.setNonce_str(nonce_str);                                                   //随机字符串
            weChatPayReqInfo.setBody(map.get("body").toString());                                           	//商品描述
            weChatPayReqInfo.setOut_trade_no(map.get("orderNo").toString());                			//商户订单号
            weChatPayReqInfo.setTotal_fee(total_fee);                                           //总金额
            weChatPayReqInfo.setSpbill_create_ip("139.159.177.244");                              //终端ip
            weChatPayReqInfo.setNotify_url(SysConst.getSysConfig().getNotifyUrl());                       //通知url
            weChatPayReqInfo.setTrade_type("JSAPI");                                              //交易类型
            weChatPayReqInfo.setAttach(map.get("orderScene").toString());
            weChatPayReqInfo.setProfit_sharing("N");
            //附加数据，区分订单类型
            Map<String,String> payMap = new HashMap<>();

            payMap.put("app_id", weChatPayReqInfo.getSub_appid());
            payMap.put("api_key",SysConst.getSysConfig().getWxApiKey());
            payMap.put("unified_order_url",SysConst.getSysConfig().getWxUnifiedOrderUrl());
            SortedMap<Object, Object> sortedMap = wechatPayUtil.goWechatPay(weChatPayReqInfo,payMap);
            return ResponseMsgUtil.success(sortedMap);
        } catch (Exception e) {
            log.error("orderToPay error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/hltUnionCardPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "工会卡支付")
    public ResponseData hltUnionCardPay(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (body == null
                    || body.getLong("orderId") == null
                    || StringUtils.isBlank(body.getString("password"))
                    || StringUtils.isBlank(body.getString("cardNo"))
            ) {
                log.error("orderToPay error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询用户与卡号的关系
            HighUserCard userCard = highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), body.getString("cardNo"));
            if (userCard == null) {
                log.error("hltUnionCardPay() ERROR", "未绑定卡号");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未绑定卡号");
            }

            // 订单
            HighOrder order = highOrderService.getOrderById(body.getLong("orderId"));

            if (order == null) {
                log.error("hltUnionCardPay error!", "未找到订单信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单信息");
            }

            // 订单状态 ： 订单支付状态 ： 1.待支付 2.已支付 3.已完成 4.已取消 5.已退款
            if (order.getOrderStatus() != 1) {
                log.error("hltUnionCardPay error!", "无法支付，订单不处于待支付状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法支付，订单不处于待支付状态");
            }

            // 查询用户支付密码
            HighUserPayPassword userPayPassword = highUserPayPasswordService.getDetailByUser(order.getMemId());

            if (userPayPassword == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
            }
            if (StringUtils.isBlank(body.getString("password"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_ENTER_USER_PAY_PWD, "");
            }
            // 校验支付密码
            if (!AESEncodeUtil.aesEncrypt(body.getString("password")).equals(userPayPassword.getPassword())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USER_PAY_PWD_ERROR, "");
            }

            highOrderService.hltUnionCardPayByThirdProduct(userCard, order.getId());

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

    @RequestMapping(value="/orderToUnionPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "订单支付发起银联支付")
    public ResponseData orderToUnionPay(@RequestBody String reqBodyStr,HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            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("hltUnionCardPay error!", "未找到订单信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单信息");
            }

            // 订单状态 ： 订单支付状态 ： 101.待支付 102.已支付 100.已完成 104.已取消 105.已退款
            if (order.getOrderStatus() != 1) {
                log.error("hltUnionCardPay error!", "无法支付，订单不处于待支付状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法支付，订单不处于待支付状态");
            }

            return ResponseMsgUtil.success(unionPayConfig.upPreOrder(UnionPayConfig.MER_ID2, UnionPayConfig.TERM_ID2, order.getOrderNo(), order.getPayRealPrice(), "购买第三方产品", CommonSysConst.getSysConfig().getUnionPayNotifyUrl(), request));

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

}
