package cn.pluss.platform.controller.home;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.appletInfo.AppletInfoService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.SubAppLetInfo;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.notify.NotifyMessageService;
import cn.pluss.platform.pay.ApiPayService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.wechat.WxConstants;
import cn.pluss.platform.wx.WxAccessTokenRequest;
import cn.pluss.platform.wx.WxCommonService;
import cn.pluss.platform.wx.WxOpenidResponse;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 下游上送订单接口类
 */
@Controller
@RequestMapping(value = "/api")
public class ApiPayController {

    /**
     * 日志打印 log
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private MerchantOrderService merchantOrderService;


    @Autowired
    private NotifyMessageService notifyMessageService;

    @Autowired
    private ApiPayService apiPayService;

    @Autowired
    private MerchantStoreService merchantStoreService;

    @Autowired
    private MerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    private WxCommonService wxCommonService;

    @Autowired
    private AppletInfoService appletInfoService;


    @RequestMapping(value = "/trans/pay",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject apiPay(@RequestBody String json, HttpServletRequest request){
        logger.info("============>交易接口下单，请求交易数据:{}<============",json);
        try {
            String ip = IpUtils.getIpAddr(request);
            return apiPayService.pay(json,ip);
        }catch (Exception e){
            return ResultGenerator.genFailJsonResult(e.getMessage());
        }
    }

    /**
     * 小程序退款接口
     * @param params
     * @return
     */
    @RequestMapping(value = "/trans/refund",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> refund(@RequestBody JSONObject params){
        return apiPayService.refund(params);
    }

    /**
     * api退款接口
     * @param params
     * @return
     */
    @RequestMapping(value = "/trans/refund.do",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> apiRefund(@RequestBody JSONObject params){
        return apiPayService.apiRefund(params);
    }


    /**
     * 小程序订单查询
     * @param params
     * @return
     */
    @RequestMapping(value = "/refund/query",method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> refundQuery(@RequestBody JSONObject params){
        return apiPayService.refundQuery(params);
    }

    /**
     * 小程序取消支付
     * @param params
     * @return
     */
    @RequestMapping(value = "/mqtt/pay/cancel",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> cancel(@RequestBody JSONObject params){
        String storeId = Optional.ofNullable(params.getString("storeId")).orElseThrow(() -> new MsgException("店铺ID不能为空"));
        String money = params.getString("money");
        MerchantStore store = merchantStoreService.queryMerchantStore(new MerchantStore().setId(Integer.valueOf(storeId)));
        if(store != null){
            QueryWrapper<MerchantBaseInfo> queryWrapper = new QueryWrapper<MerchantBaseInfo>().eq("merchantCode",store.getMerchantCode());
            List<MerchantBaseInfo> list = merchantBaseInfoService.list(queryWrapper);
            if(!list.isEmpty()){
                params.put("mercId",list.get(0).getId());
                params.put("money",money);
                params.put("userId",list.get(0).getUserId());
                notifyMessageService.sendCancelPayMessage(params);
                return ResultGenerator.genSuccessResult("推送成功！",null);
            }
        }
        return ResultGenerator.genFailResult("推送失败！",null);
    }

    /**
     * @description:小程序获取openid
     * @date: 2021/10/13 13:46
     * @param params:
     * @return cn.pluss.platform.api.Result<com.alibaba.fastjson.JSONObject>
     */
    @RequestMapping(value = "/wxapp/getOpenId",method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> getOpenId(@RequestBody JSONObject params){
        String code = params.getString("code");
        if(StringUtil.isEmpty(code)){
            return ResultGenerator.genFailResult("缺失参数！");
        }
        String appid = StringUtil.isNotEmpty(params.getString("appid")) ? params.getString("appid") : SubAppLetInfo.SYB.getAppid();
        AppletInfo applet = appletInfoService.getAppletInfoByAppId(appid);
        MsgException.checkNull(applet,"小程序配置信息异常！");
        String appSecret = applet.getSecret();
        try {
            WxAccessTokenRequest request = WxAccessTokenRequest.buidWxToken(appid,appSecret,code, WxConstants.WX_APPLET_OPENID_URL);
            WxOpenidResponse wxOpenId = wxCommonService.getWxOpenId(request);
            return ResultGenerator.genSuccessResult("获取成功！",wxOpenId);
        }catch (Exception e){
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * @description:小程序获取订单
     * @date: 2021/10/13 13:46
     * @param params:
     * @return cn.pluss.platform.api.Result<com.alibaba.fastjson.JSONObject>
     */
    @RequestMapping(value = "/wxapp/getOrder",method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> getOrder(@RequestBody JSONObject params){
        String openid = params.getString("openid");
        if(StringUtil.isEmpty(openid)){
            return ResultGenerator.genFailResult("缺失参数！");
        }
        QueryWrapper<MerchantOrder> queryWrapper = new QueryWrapper<MerchantOrder>()
                .eq("mercUserId",openid).eq("status","1");
        List<MerchantOrder> list = merchantOrderService.list(queryWrapper);
        return ResultGenerator.genSuccessResult("获取成功",list);
    }

    /**
     *内部微信小程序支付
     * @date: 2021/12/24 13:32
     * @param params:
     * @return cn.pluss.platform.api.Result<java.lang.Object>
     */
    @RequestMapping(value = "/wxapp/pay",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject wxappPay(@RequestBody JSONObject params){
        try {
            return apiPayService.wxappPay(params);
        }catch (Exception e){
            return ResultGenerator.genFailJsonResult(e.getMessage());
        }
    }

    @PostMapping("/applet/orderPay")
    @ResponseBody
    public Result<Object> orderPay(@RequestBody JSONObject params) {
        String userId = params.getString("userId");
        String orderNumber = params.getString("orderNumber");
        return apiPayService.orderPay(userId,orderNumber);
    }

    public static void main(String[] args) {
//        String openid = "oPhYX5BsUDxDgGOQ8GNLhanMR3f8";
        String key = "5d7d4c33067b4489bcca25f034f46551";
        String merchantCode = "M800202206280ff7f1";
        String method = "trans_pay";
        String notifyUrl = "https://www.shouyinbei.net/wap/notify/sxfCallBack";
//        String returnUrl = "https://www.baidu.com";
        String mercOrderNo = StringUtil.generateMixStr(3).toUpperCase(Locale.ROOT) + StringUtil.getBillno();
        JSONObject params = new JSONObject(10);
        params.put("merchantCode",merchantCode);
        params.put("method",method);
        params.put("mercOrderNo",mercOrderNo);
        params.put("payAmt","0.20");
        params.put("notifyUrl",notifyUrl);
        params.put("payWay","WXZF");
        params.put("payType","02");
        params.put("subject","测试订单");
//        params.put("userId",openid);
        String signContent = SignUtils.getSignContent(params) + "&key="+key;
        String sign = MD5Util.MD5Encode(signContent, "UTF-8");
        params.put("sign",sign);
        System.out.println("param==>" + params.toJSONString());
    }
}
