package com.org.hktshop.controller.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.org.hktshop.Interface.product.IHktGoodsService;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.entity.order.HktOrder;
import com.org.hktshop.entity.order.HktOrderRefund;
import com.org.hktshop.entity.pay.AlipayVo;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.service.order.HktOrderRefundService;
import com.org.hktshop.service.order.HktOrderService;
import com.org.hktshop.service.user.HktUserService;
import com.org.hktshop.service.user.HktUsersScoreService;
import com.org.hktshop.utils.DateUtil;
import com.org.hktshop.utils.HttpCode;
import com.org.hktshop.utils.StringUtils;
import com.org.hktshop.utils.pay.PayMessageTips;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 支付宝扫码支付
 *
 * @author owen
 */
@RestController
@RequestMapping(value = "/alipay")
public class AlipayController extends PayBaseController {

    private static Logger logger = LoggerFactory.getLogger(AlipayController.class);

    @Autowired
    private HktOrderService hktOrderService;

    @Autowired
    private HktOrderRefundService hktOrderRefundService;

    @Autowired
    private PayMessageTips payMessageTips;

    @Autowired
    private IHktGoodsService hktGoodsService;

    @Autowired
    private HktUsersScoreService scoreService;

    @Autowired
    private HktUserService userService;

    /**
     * 支付网站扫码支付接口-统一下单支付接口
     *
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("/pay")
    private Object alipayPay(HttpServletResponse response, HttpServletRequest request) throws AlipayApiException {

//        HktUser user = (HktUser) request.getSession().getAttribute("OpUser");

        //这个应该是从前端端传过来的，这里为了测试就从后台写死了
        BaseResult<Object> objectBaseResult = new BaseResult<>();
        AlipayVo vo = new AlipayVo();
        String tradeNo = request.getParameter("tradeNo");
        if (StringUtils.isNull(tradeNo)) {
            objectBaseResult.setHttpCode(HttpCode.BAD_REQUEST.getCode());
            objectBaseResult.setMessage("缺少必填参数");
            return objectBaseResult;
        }

        HktOrder findOrder = new HktOrder();
        findOrder.setOrderSn(tradeNo);
//        findOrder.setUserId(user.getId());
        HktOrder hktOrder = hktOrderService.getHktOrder(findOrder);
        if (hktOrder == null) {
            objectBaseResult.setHttpCode(HttpCode.BAD_REQUEST.getCode());
            objectBaseResult.setMessage("订单号不存在");
            return objectBaseResult;
        }
        vo.setOut_trade_no(tradeNo + "_" + System.currentTimeMillis());
        vo.setTotal_amount(hktOrder.getTotalAmount());
        if (!"0".equals(hktOrder.getOrderStatus())) {
            objectBaseResult.setHttpCode(HttpCode.MULTI_STATUS.getCode());
            objectBaseResult.setMessage("无效订单");
            return objectBaseResult;
        }
       /* String createTime = hktOrder.getCreateTime();
        Date date = DateUtil.StringToDate1(createTime);
        long creTime = date.getTime();
        Date date1 = new Date();
        long curTime = date1.getTime();
        if ((curTime - creTime) / (1000 * 60) > 30) {
            objectBaseResult.setHttpCode(HttpCode.MULTI_STATUS.getCode());
            objectBaseResult.setMessage("订单已失效，无法支付");
            return objectBaseResult;
        }*/
        vo.setSubject("pay");
        //这个是固定的
        vo.setProduct_code("FAST_INSTANT_TRADE_PAY");
        String json = JSON.toJSONString(vo);

        AlipayClient alipayClient = new DefaultAlipayClient(gateway_url, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        alipayRequest.setBizContent(json);
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        /*AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(alipayRequest);
        String result = alipayTradePagePayResponse.getBody();*/
        logger.info("result: {}", result);
        //这里生成一个表单，会自动提交
        return result;
    }

    /**
     * 支付宝服务器异步通知页面
     *
     * @return
     * @throws AlipayApiException
     */
    @PostMapping("/notify")
    public String alipayNotify(HttpServletRequest request) throws AlipayApiException {
        System.out.print("##############支付宝回调地址#############");
        Map<String, String> params = getParamsMap(request);
        logger.info("notify params: {}", JSONObject.toJSON(params));
        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type);
        if (signVerified) {
            String out_trade_no = params.get("out_trade_no");
            HktOrder hktOrder = new HktOrder();
            hktOrder.setOrderSn(out_trade_no.substring(0, out_trade_no.indexOf("_")));
            hktOrder.setOutTrandeNo(out_trade_no);
            hktOrder.setOrderStatus("1");
            hktOrder.setPayTime(DateUtil.getDateTime());
            hktOrder.setPayStatus("2");
            hktOrder.setPayCode(params.get("trade_no"));
            hktOrder.setPayName("支付宝");
            String sql = "select id,order_sn as orderSn,give_type as giveType,mobile from hkt_order where order_sn = " + out_trade_no.substring(0, out_trade_no.indexOf("_"));
            HktOrder hktOrderByNo = hktOrderService.getHktOrderByNo(sql);
            hktOrder.setId(hktOrderByNo.getId());
            hktOrderService.updateHktOrder(hktOrder);
            logger.info("################订单付款成功################");
           /* try{
                HktUser hktUser = userService.getHktUserById(hktOrderByNo.getUserId());
                scoreService.AddUserScore(hktUser,2,Integer.parseInt(hktOrderByNo.getTotalAmount()));
                hktGoodsService.subtractStock(hktOrderByNo.getOrderSn());
            }catch (Exception e){
                logger.info("########去除库存异常####### error={}",e.toString());
            }*/
            if(2 == hktOrderByNo.getGiveType()){
                payMessageTips.sendMsg(hktOrderByNo);
            }

            return ("success");
        } else {
            logger.info("验证失败,不去更新状态");
            return ("fail");
        }
    }

    /**
     * 支付宝服务器同步通知页面
     *
     * @param request
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("/return")
    public void alipayReturn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> params = getParamsMap(request);
        logger.info("return params: {}", JSONObject.toJSON(params));

        // 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type);
        logger.info("return signVerified: {}", signVerified);

        if (signVerified) {
            try{
                String out_trade_no = params.get("out_trade_no");
                HktOrder hktOrder = new HktOrder();
                hktOrder.setOutTrandeNo(out_trade_no);
                HktOrder hktOrderById = hktOrderService.getHktOrder(hktOrder);
                HktUser hktUser = userService.getHktUserById(hktOrderById.getUserId());
                scoreService.AddUserScore(hktUser,2,(-1) *(Integer.parseInt(hktOrderById.getTotalAmount())));
            }catch (Exception e){
                e.printStackTrace();
            }
            String out_trade_no = params.get("out_trade_no");
            String total_amount = params.get("total_amount");
            response.sendRedirect("https://www.hotking.com/order/pay-alipay?no=" + out_trade_no.substring(0, out_trade_no.indexOf("_")) + "&m=" + total_amount.replace(".", "_"));
        } else {
            logger.info("验证失败,不去更新状态");
        }
    }

    private Map<String, String> getParamsMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return params;
    }


    /**
     * 支付宝退款
     */
    public void appliyRefund(HktOrderRefund hktOrderRefund) throws Exception{

        AlipayClient alipayClient = new DefaultAlipayClient(gateway_url, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);

        AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
        refundModel.setOutTradeNo(hktOrderRefund.getOutTrandeNo()+"");
        refundModel.setRefundAmount(hktOrderRefund.getRefundAmount()+"");
        refundModel.setRefundReason("商品退款");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizModel(refundModel);

            AlipayTradeRefundResponse response = alipayClient.execute(request);
            logger.info("支付宝退款返回消息："+response.getMsg());
            if("10000".equals(response.getCode())){
                HktOrder hktOrder = new HktOrder();
                hktOrder.setId(hktOrderRefund.getOrderId());
                hktOrder.setReturnStatus("1");
                hktOrder.setOrderStatus("4");
                hktOrderService.updateHktOrder(hktOrder);
                hktOrderRefund.setOrderStatus("1");
                hktOrderRefund.setUserId(hktOrderRefund.getUserId());
                hktOrderRefundService.updateOrderRefund(hktOrderRefund);
            } else {
                hktOrderRefund.setOrderStatus("0");
                hktOrderRefund.setFailMsg(response.getMsg());
                hktOrderRefundService.updateOrderRefund(hktOrderRefund);
            }
    }


    @GetMapping("/pay1")
    private Object alipayPay1(HttpServletResponse response, HttpServletRequest request) throws AlipayApiException {

//        HktUser user = (HktUser) request.getSession().getAttribute("OpUser");

        //这个应该是从前端端传过来的，这里为了测试就从后台写死了
        BaseResult<Object> objectBaseResult = new BaseResult<>();
        AlipayVo vo = new AlipayVo();
        String tradeNo = request.getParameter("tradeNo");
        if (StringUtils.isNull(tradeNo)) {
            objectBaseResult.setHttpCode(HttpCode.BAD_REQUEST.getCode());
            objectBaseResult.setMessage("缺少必填参数");
            return objectBaseResult;
        }

        HktOrder findOrder = new HktOrder();
        findOrder.setOrderSn(tradeNo);
//        findOrder.setUserId(user.getId());
        HktOrder hktOrder = hktOrderService.getHktOrder(findOrder);
        if (hktOrder == null) {
            objectBaseResult.setHttpCode(HttpCode.BAD_REQUEST.getCode());
            objectBaseResult.setMessage("订单号不存在");
            return objectBaseResult;
        }
        vo.setOut_trade_no(tradeNo + "_" + System.currentTimeMillis());
        vo.setTotal_amount(hktOrder.getTotalAmount());
        if (!"0".equals(hktOrder.getOrderStatus())) {
            objectBaseResult.setHttpCode(HttpCode.MULTI_STATUS.getCode());
            objectBaseResult.setMessage("无效订单");
            return objectBaseResult;
        }
        String createTime = hktOrder.getCreateTime();
        Date date = DateUtil.StringToDate1(createTime);
        long creTime = date.getTime();
        Date date1 = new Date();
        long curTime = date1.getTime();
        if ((curTime - creTime) / (1000 * 60) > 30) {
            objectBaseResult.setHttpCode(HttpCode.MULTI_STATUS.getCode());
            objectBaseResult.setMessage("订单已失效，无法支付");
            return objectBaseResult;
        }
        vo.setSubject("pay");
        //这个是固定的
        vo.setProduct_code("FAST_INSTANT_TRADE_PAY");
        String json = JSON.toJSONString(vo);

        AlipayClient alipayClient = new DefaultAlipayClient(gateway_url, app_id, merchant_private_key, "json", charset, alipay_public_key, sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        alipayRequest.setBizContent(json);
//        String result = alipayClient.pageExecute(alipayRequest).getBody();
        String result = alipayClient.sdkExecute(alipayRequest).getBody();
        try{
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        objectBaseResult.setHttpCode(500);
        return objectBaseResult;
        /*AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(alipayRequest);
        String result = alipayTradePagePayResponse.getBody();*/
//        logger.info("result: {}", result);
        //这里生成一个表单，会自动提交
//        return result;
    }
}