package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.channel.weixin.entity.WeChatPayReqInfo;
import com.hfkj.channel.weixin.utils.MD5Util;
import com.hfkj.channel.weixin.utils.WechatPayUtil;
import com.hfkj.common.WeChatMerNo;
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.MathUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsRebateMerAccount;
import com.hfkj.entity.BsRebateMerAccountOrder;
import com.hfkj.model.ResponseData;
import com.hfkj.service.rebate.BsRebateMerAccountOrderServer;
import com.hfkj.service.rebate.BsRebateMerAccountService;
import com.hfkj.sysenum.*;
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.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ThreadLocalRandom;

@Controller
@Api(value = "返利金商户账户订单")
@RequestMapping(value = "/rebateMerAccountOrder")
public class BsRebateMerAccountOrderController {

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

    @Resource
    private BsRebateMerAccountService rebateMerAccountService;
    @Resource
    private BsRebateMerAccountOrderServer rebateMerAccountOrderServer;
    @Resource
    private WechatPayUtil wechatPayUtil;

    @RequestMapping(value="/create",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建订单")
    public ResponseData create(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getLong("accountNumber") == null
                    || body.getInteger("orderType") == null
                    || StringUtils.isBlank(body.getString("payType"))
                    || body.getBigDecimal("tradePrice") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询账户
            BsRebateMerAccount account = rebateMerAccountService.getAccountByNumber(body.getLong("accountNumber"));
            if (account == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到账户信息");
            }
            if (account.getStatus().equals(RebateMerAccountStatus.status2.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "账户已被冻结，暂时无法充值");
            }
            // 订单类型
            RebateMerAccountOrderType orderType = RebateMerAccountOrderType.getDataByNumber(body.getInteger("orderType"));
            if (orderType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单类型");
            }
            // 支付类型
            TradeOrderPayModeEnum payType = TradeOrderPayModeEnum.getNameByCode(body.getString("payType"));
            if (payType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的支付类型");
            }
            BsRebateMerAccountOrder order = new BsRebateMerAccountOrder();
            order.setAccountNumber(account.getAccountNumber());
            order.setMerId(account.getMerId());
            order.setMerNo(account.getMerNo());
            order.setMerName(account.getMerName());
            order.setMerAbbreviate(account.getMerAbbreviate());
            order.setOrderType(orderType.getNumber());
            order.setOrderNo(DateUtil.date2String(new Date(System.currentTimeMillis()),"yyyyMMddHHmmssS"));
            order.setTradePrice(body.getBigDecimal("tradePrice"));
            order.setPayType(payType.getCode());
            order.setStatus(RebateMerAccountOrderStatus.status1.getNumber());
            rebateMerAccountOrderServer.editData(order);

            Map<String,Object> param = new HashMap<>();
            param.put("order", order);

            if (payType.getCode().equals(TradeOrderPayModeEnum.WECHAT.getCode())) {
                if (StringUtils.isBlank(body.getString("openId"))) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "openId不能为空");
                }
                // 微信支付【直连】
                WeChatPayReqInfo weChatPayReqInfo = new WeChatPayReqInfo();
                weChatPayReqInfo.setAppid(SysConst.getSysConfig().getWxMchAppId());               // 公众号id
                weChatPayReqInfo.setMch_id(SysConst.getSysConfig().getWxMchId());                 // 商户号
                weChatPayReqInfo.setSub_appid("wxa075e8509802f826");                              // 商户号公众号
                weChatPayReqInfo.setSub_mch_id(WeChatMerNo.MCH_ID_1614670195);                    // 子商户号
                weChatPayReqInfo.setSub_openid(body.getString("openId"));
                weChatPayReqInfo.setNonce_str(MD5Util.MD5Encode(String.valueOf(ThreadLocalRandom.current().nextInt(10000)), "UTF-8"));                                                     // 随机字符串
                weChatPayReqInfo.setBody("充值");                                                  // 商品描述
                weChatPayReqInfo.setOut_trade_no(order.getOrderNo());                			  // 商户订单号
                weChatPayReqInfo.setTotal_fee(order.getTradePrice().multiply(new BigDecimal("100")).intValue());                                                     // 总金额
                weChatPayReqInfo.setSpbill_create_ip("122.9.135.148");                            // 终端ip
                weChatPayReqInfo.setNotify_url(CommonSysConst.getSysConfig().getDomainName()+"/crest/weiXinNotify/rebateMerAccountOrder");                       // 通知url
                weChatPayReqInfo.setTrade_type("JSAPI");                                          // 交易类型
                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());
                param.put("payParam", wechatPayUtil.goWechatPay(weChatPayReqInfo,payMap));
            }
            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value="/queryOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单列表")
    public ResponseData queryOrderList(@RequestParam(name = "accountNumber", required = true) String accountNumber,
                                     @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("accountNumber", accountNumber);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(rebateMerAccountOrderServer.getOrderList(param)));

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

    @RequestMapping(value="/queryOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单详情")
    public ResponseData queryOrderDetail(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            return ResponseMsgUtil.success(rebateMerAccountOrderServer.getDetailByOrderNo(orderNo));

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

}
