package com.thinkgem.jeesite.modules.pay.api;

import com.thinkgem.jeesite.common.baseBean.Request;
import com.thinkgem.jeesite.common.baseBean.Response;
import com.thinkgem.jeesite.common.constant.ComCode;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.commonError.MyException;
import com.thinkgem.jeesite.modules.pay.entity.BalanceEntity;
import com.thinkgem.jeesite.modules.pay.entity.OrderEntity;
import com.thinkgem.jeesite.modules.pay.juhezhong.dto.PayBackDto;
import com.thinkgem.jeesite.modules.pay.juhezhong.utils.DateUtil;
import com.thinkgem.jeesite.modules.pay.service.PayApiService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.DictPayChannel;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.user.bean.JuHeZhongPayRequest;
import com.thinkgem.jeesite.modules.user.bean.UserRequest;
import com.thinkgem.jeesite.modules.user.entity.CardEntity;
import com.thinkgem.jeesite.modules.user.entity.CardSwpaccidEntity;
import com.thinkgem.jeesite.modules.user.entity.UserEntity;
import com.thinkgem.jeesite.modules.user.service.UserApiService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 支付相关
 */
@RestController
@RequestMapping("/api/pay")
public class PayApiController {
    /**
     * log
     */
    private static Logger logger = LoggerFactory.getLogger(PayApiController.class);
    @Autowired
    private PayApiService payService;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserApiService userApiService;

    /**
     * 快捷支付 分不同得通道 根据payChannel来判断支付通道
     *
     * @param request
     * @return
     */
    @PostMapping("/quickPay")
    public Response quickPay(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {
            //非交易时间直接返回
            if (!DateUtil.checkTimeIsDuration()) {
                throw new MyException(ComCode.STATUS_CODE_6002_DESC);
            }
            PayBackDto payBackDto = payService.quickPay(request);
            if ((payBackDto.getUrl() != null && !"".equals(payBackDto.getUrl())) || "0".equals(payBackDto.getIsUrl())) {
                resp.setStatus(ComCode.STATUS_CODE_2000);
                resp.setMessage(ComCode.STATUS_CODE_2000_DESC);
                logger.debug("快捷支付返回URL: {}", payBackDto.getUrl());
                resp.setData(payBackDto);
            } else {
                resp.setStatus(ComCode.STATUS_CODE_9998);
                resp.setMessage(payBackDto.getMessage());
                resp.setData(payBackDto);
            }

        } catch (MyException e) {
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setMessage(e.getMessage());
            resp.setError(e.getMessage());

        } catch (Exception e) {
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setMessage(ComCode.STATUS_CODE_9998_DESC);
            resp.setError(e.getMessage());
            e.printStackTrace();
        }
        return resp;
    }


    /**
     * 支付宝支付 目前仅仅用来用户升级支付
     *
     * @param request
     * @return
     */
    @PostMapping("/aliPay")
    public Response aliPay(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {
            logger.debug("支付宝升级等级level: {}", request.getLevel());
            if ("B".equals(request.getLevel())) {
                if (StringUtils.isBlank(request.getAfterMobile())) {
                    resp.setStatus(ComCode.STATUS_CODE_4001);
                    resp.setMessage(ComCode.STATUS_CODE_4001_DESC);
                    return resp;
                }
                UserEntity userEntity = userApiService.checkMobile(request.getAfterMobile());
                if (userEntity != null) {
                    resp.setStatus(ComCode.STATUS_CODE_4007);
                    resp.setMessage(ComCode.STATUS_CODE_4007_DESC);
                    return resp;
                }
            }
            PayBackDto payBackDto = payService.aliPay(request);
            resp.setStatus(ComCode.STATUS_CODE_2000);
            resp.setMessage(ComCode.STATUS_CODE_2000_DESC);
            resp.setData(payBackDto);
        } catch (Exception e) {
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setMessage(ComCode.STATUS_CODE_9998_DESC);
            resp.setError(e.getMessage());
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 开卡 目前仅仅jfen通道需要请求这个接口  如果还有其他通道开卡请加上通道另外的判断
     *
     * @param request
     * @return
     */
    @PostMapping("/openCard")
    public Response openCard(UserRequest request) {
        Response resp = new Response();
        if (ComCode.PAYCHANNEL_HL2.equals(request.getPayChannel())) { // 目前仅仅jfen通道需要请求这个接口  如果还有其他通道开卡请加上通道的判断
            return payService.openCardJFen(request);
        }
        resp.setMessage("没有该渠道");
        resp.setStatus(ComCode.STATUS_CODE_9998);
        return resp;
    }

    /**
     * 发送验证码 目前仅仅jfen通道需要请求这个接口  如果还有其他通道发送验证码请加上另外通道的判断
     *
     * @param request
     * @return
     */
    @PostMapping("/sendMessagePay")
    public Response sendMessagePay(JuHeZhongPayRequest request) {
        Response resp = new Response();
        if (ComCode.PAYCHANNEL_HL2.equals(request.getPayChannel())) { // 目前仅仅jfen通道需要请求这个接口  如果还有其他通道发送验证码请加上通道的判断
            try {
                return payService.sendMessageJFen(request);
            } catch (MyException e) {
                resp.setMessage(e.getMessage());
                resp.setStatus(ComCode.STATUS_CODE_9998);
            }
        }
        resp.setMessage("没有该渠道");
        resp.setStatus(ComCode.STATUS_CODE_9998);
        return resp;
    }


    /**
     * 提现
     *
     * @param request
     * @return
     */
    @PostMapping("/putForward")
    public Response putForward(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {
            return payService.putForward(request);
        } catch (Exception e) {
            resp.setMessage(ComCode.STATUS_CODE_9998_DESC);
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setError(e.getMessage());
        }

        return resp;
    }

    /**
     * 查询提现结果
     *
     * @param request
     * @return
     */
    @PostMapping("/queryForward")
    public Response queryForward(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {
            resp.setData(payService.queryForward(request.getPayNo()));
            resp.setStatus(ComCode.STATUS_CODE_2000);
        } catch (Exception e) {
            resp.setMessage(ComCode.STATUS_CODE_9998_DESC);
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setError(e.getMessage());
        }

        return resp;
    }


    /**
     * juhezhong快捷支付的回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/notifyPay")
    public void notifyPay(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("HL2回调开始");
        Response responseRetrun = new Response();
        Map map = request.getParameterMap();
        printNotifyParam(map);
//        Set keSet=map.entrySet();
//        for(Iterator itr = keSet.iterator(); itr.hasNext();){
//            Map.Entry me=(Map.Entry)itr.next();
//            Object ok=me.getKey(); //获取参数名
//            Object ov=me.getValue(); //获取参数值
//            System.out.println(ok+"="+ok.toString());
//            System.out.println(ov+"="+ov.toString());
//            String[] value=new String[1];
//            if(ov instanceof String[]){
//                value=(String[])ov;
//            }else{
//                value[0]=ov.toString();
//            }
//            for(int k=0;k <value.length;k++){
//                System.out.println(ok+"="+value[k]);
//            }
//        }
        //设置编码
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        String orderId = request.getParameter("orderId");
        String code = request.getParameter("code");
        logger.debug("HL2回调信息, 订单ID : {} , code:{}", orderId, code);
        if ("0000".equals(code)) {
            logger.debug("orderId: {}", orderId);
            OrderEntity orderEntity = new OrderEntity();

            orderEntity.setPayCode(orderId);

            try {
                orderEntity = payService.notifyPay(orderEntity);
            } catch (Exception e) {
                e.printStackTrace();

            }
            //返回true 收到请求，停止通知
            PrintWriter write = null;
            try {
                write = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            write.print("true");

            responseRetrun.setMessage("ok");
            responseRetrun.setStatus(ComCode.STATUS_CODE_9998);
            responseRetrun.setData(orderEntity);
            write.flush();
            write.close();
        }


    }

    /**
     * juhezhongHL4快捷支付的回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/notifyQuickPay")
    public void notifyQuickPay(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("H4通道：quickPay支付回调");
        Response responseRetrun = new Response();
        Map map = request.getParameterMap();
        printNotifyParam(map);
//        Set keSet=map.entrySet();
//        for(Iterator itr = keSet.iterator(); itr.hasNext();){
//            Map.Entry me=(Map.Entry)itr.next();
//            Object ok=me.getKey(); //获取参数名
//            Object ov=me.getValue(); //获取参数值
//            System.out.println(ok+"="+ok.toString());
//            System.out.println(ov+"="+ov.toString());
//            String[] value=new String[1];
//            if(ov instanceof String[]){
//                value=(String[])ov;
//            }else{
//                value[0]=ov.toString();
//            }
//            for(int k=0;k <value.length;k++){
//                System.out.println(ok+"="+value[k]);
//            }
//        }
        //设置编码
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        String orderId = request.getParameter("orderId");
        String code = request.getParameter("code");
        logger.debug("HL4回调信息, 订单ID : {} , code:{}", orderId, code);
        if ("0000".equals(code)) {
            logger.debug("quick pay orderId: {}", orderId);
            OrderEntity orderEntity = new OrderEntity();

            orderEntity.setPayCode(orderId);

            try {
                orderEntity = payService.notifyPay(orderEntity);
            } catch (Exception e) {
                e.printStackTrace();

            }
            //返回true 收到请求，停止通知
            PrintWriter write = null;
            try {
                write = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            write.print("true");

            responseRetrun.setMessage("ok");
            responseRetrun.setStatus(ComCode.STATUS_CODE_9998);
            responseRetrun.setData(orderEntity);
            write.flush();
            write.close();
        }


    }

    /**
     * Huanqiuhuiju快捷支付的回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/notifyHuanqiuhuijuPay")
    public void notifyHuanqiuhuijuPay(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("Huanqiuhuiju快捷支付的回调开始");
        Response responseRetrun = new Response();
        Map map = request.getParameterMap();
        printNotifyParam(map);
//        Set keSet=map.entrySet();
//        for(Iterator itr = keSet.iterator(); itr.hasNext();){
//            Map.Entry me=(Map.Entry)itr.next();
//            Object ok=me.getKey(); //获取参数名
//            Object ov=me.getValue(); //获取参数值
//            System.out.println(ok+"="+ok.toString());
//            System.out.println(ov+"="+ov.toString());
//            String[] value=new String[1];
//            if(ov instanceof String[]){
//                value=(String[])ov;
//            }else{
//                value[0]=ov.toString();
//            }
//            for(int k=0;k <value.length;k++){
//                System.out.println(ok+"="+value[k]);
//            }
//        }
        //设置编码
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        String orderId = request.getParameter("dsorderid");
        String code = request.getParameter("respCode");
        if ("00".equals(code)) {
            logger.debug("orderId: {}", orderId);
            OrderEntity orderEntity = new OrderEntity();

            orderEntity.setPayCode(orderId);

            try {
                orderEntity = payService.notifyPay(orderEntity);
            } catch (Exception e) {
                e.printStackTrace();

            }
            //返回true 收到请求，停止通知
            PrintWriter write = null;
            try {
                write = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            write.print("success");

            responseRetrun.setMessage("ok");
            responseRetrun.setStatus(ComCode.STATUS_CODE_9998);
            responseRetrun.setData(orderEntity);
            write.flush();
            write.close();
        }


    }


    /**
     * 开卡的回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/openCardCallback")
    public void openCardCallback(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("。。。。。。openCardCallback回调。。。。。");
        Map map = request.getParameterMap();
        printNotifyParam(map);
//        Set keSet=map.entrySet();
//        for(Iterator itr = keSet.iterator(); itr.hasNext();){
//            Map.Entry me=(Map.Entry)itr.next();
//            Object ok=me.getKey(); //获取参数名
//            Object ov=me.getValue(); //获取参数值
//            System.out.println(ok+"="+ok.toString());
//            System.out.println(ov+"="+ov.toString());
//            String[] value=new String[1];
//            if(ov instanceof String[]){
//                value=(String[])ov;
//            }else{
//                value[0]=ov.toString();
//            }
//            for(int k=0;k <value.length;k++){
//                System.out.println(ok+"="+value[k]);
//            }
//        }
        //设置编码
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        String swpaccid = request.getParameter("swpaccid");
        String cardNo = request.getParameter("cardNo");
        String phone = request.getParameter("phone");
        String code = request.getParameter("code");
        if ("0000".equals(code)) {
            CardEntity cardEntity = new CardEntity();
            cardEntity.setCardNo(cardNo);
            cardEntity.setCardMobile(phone);
            cardEntity = userApiService.getCardByCardNo(cardNo);
            CardSwpaccidEntity cardSwpaccidEntity = new CardSwpaccidEntity();
            cardSwpaccidEntity.setPayMethod("quick");
            cardSwpaccidEntity.setPayChannel(ComCode.PAYCHANNEL_HL2);
            cardSwpaccidEntity.setSwpaccid(swpaccid);
            cardSwpaccidEntity.setCardCode(cardEntity.getCode());
            userApiService.addSwpaccid(cardSwpaccidEntity);
            //返回true 收到请求，停止通知
            PrintWriter write = null;
            try {
                write = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            write.print("true");

            write.flush();
            write.close();

        }


    }


    /**
     * 支付宝支付的回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/aliPayCallback")
    public void aliPayCallback(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("支付宝回调开始了！");
        Response responseRetrun = new Response();
        Map map = request.getParameterMap();
        printNotifyParam(map);
//        Set keSet=map.entrySet();
//        for(Iterator itr = keSet.iterator(); itr.hasNext();){
//            Map.Entry me=(Map.Entry)itr.next();
//            Object ok=me.getKey(); //获取参数名
//            Object ov=me.getValue(); //获取参数值
//            System.out.println(ok+"="+ok.toString());
//            System.out.println(ov+"="+ov.toString());
//            String[] value=new String[1];
//            if(ov instanceof String[]){
//                value=(String[])ov;
//            }else{
//                value[0]=ov.toString();
//            }
//            for(int k=0;k <value.length;k++){
//                System.out.println(ok+"="+value[k]);
//            }
//        }
        //设置编码
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        String orderId = request.getParameter("out_trade_no");
        String code = request.getParameter("trade_status");
        String total_amount = request.getParameter("total_amount");
        String trade_no = request.getParameter("trade_no");

        logger.debug("支付宝回调orderId: {}", orderId);
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setTradeNo(trade_no);
        orderEntity.setAmount(total_amount);
        orderEntity.setPayCode(orderId);

        try {
            orderEntity = payService.aliPayNotifyPay(orderEntity, code);
        } catch (Exception e) {
            e.printStackTrace();

        }
        //返回true 收到请求，停止通知
        PrintWriter write = null;
        try {
            write = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        write.print("success");

        responseRetrun.setMessage("ok");
        responseRetrun.setStatus(ComCode.STATUS_CODE_9998);
        responseRetrun.setData(orderEntity);
        write.flush();
        write.close();


    }


    /**
     * 打印支付回调信息
     *
     * @param map
     */
    private void printNotifyParam(Map map) {
        Set keSet = map.entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey(); //获取参数名
            Object ov = me.getValue(); //获取参数值
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }
            for (int k = 0; k < value.length; k++) {
                logger.debug("参数名: {} , 参数值: {}", ok, value[k]);
            }
        }
    }

    /**
     * 获取支付的结果
     *
     * @param orderEntity
     * @return
     */
    @RequestMapping("/payDetail")
    public Response payDetail(OrderEntity orderEntity) {

        Response responseRetrun = new Response();


        try {
            // 获取订单
            orderEntity = payService.getOrder(orderEntity);
            if (orderEntity == null) {
                responseRetrun.setMessage(ComCode.STATUS_CODE_6001_DESC);
                responseRetrun.setStatus(ComCode.STATUS_CODE_6001);
                return responseRetrun;
            }

            // 已经支付成功或者支付失败的直接返回结果
            if ("2".equals(orderEntity.getPayStatus()) || "3".equals(orderEntity.getPayStatus()) || "4".equals(orderEntity.getPayStatus())) {
                responseRetrun.setMessage("ok");
                responseRetrun.setStatus(ComCode.STATUS_CODE_2000);
                responseRetrun.setData(orderEntity);

                return responseRetrun;
            }

            // 未经过回调的 先进行juhezhong支付状态查询
            orderEntity = payService.notifyPay(orderEntity);
        } catch (Exception e) {
            e.printStackTrace();
            responseRetrun.setMessage(ComCode.STATUS_CODE_9998_DESC);
            responseRetrun.setStatus(ComCode.STATUS_CODE_9998);
            return responseRetrun;
        }
        responseRetrun.setMessage("ok");
        responseRetrun.setStatus(ComCode.STATUS_CODE_2000);
        responseRetrun.setData(orderEntity);

        return responseRetrun;

    }


    /**
     * 获取支付通道
     *
     * @param dict
     * @return
     */
    @RequestMapping("/getDict")
    public Response getDict(Dict dict) {
        Response response = new Response();

        if ("pay_channel".equals(dict.getType())) {
            List<DictPayChannel> list = dictService.findDictListPayChannel(dict);
            for (DictPayChannel dictList : list) {
                // 查询支持的银行
                dictList.setBankList(userApiService.getBelongBankByPayChannel(dictList.getValue()));
            }
            response.setStatus(ComCode.STATUS_CODE_2000);
            response.setData(list);
        } else {
            List<Dict> list = dictService.findDictList(dict);
            response.setStatus(ComCode.STATUS_CODE_2000);
            response.setData(list);
        }

        return response;
    }

    /**
     * 获取可提现额度
     *
     * @param request
     * @return
     */
    @PostMapping("/putForwardNum")
    public Response getPutForwardNum(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {
            BalanceEntity balance;
            UserEntity userInfo = userApiService.getUserInfo(request);
            if (userInfo.getLevel().equals("A") || userInfo.getLevel().equals("B")) {
                balance = payService.getPutForwardNumHighLevel(request);
            } else {
                balance = payService.getPutForwardNum(request);
            }
            String balanceNum = balance.getBalance();
            resp.setData(balanceNum);
            resp.setMessage(ComCode.STATUS_CODE_2000_DESC);
            resp.setStatus(ComCode.STATUS_CODE_2000);
        } catch (Exception e) {
            resp.setMessage(ComCode.STATUS_CODE_9998_DESC);
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setError(e.getMessage());
        }

        return resp;
    }

    /**
     * 测试分润
     *
     * @param request
     * @return
     */
    @PostMapping("/testBenefit")
    public Response testBenefit(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {
//            UserEntity userEntity, OrderEntity orderEntity, String code, JuHeZhongPayRequest request
            Request re = new Request();
            re.setSubMerchantCode(request.getSubMerchantCode());
            UserEntity userInfo = userApiService.getUserInfo(re);
            // 2. 创建支付订单信息，并保存
            String code = IdGen.randomBase62(64);
            String payNo = ComCode.YYYYMMDDHHMM.format(new Date()) + IdGen.randomBase62(8); // 订单号
            String payCode = IdGen.randomBase62(64);
            DecimalFormat df = new DecimalFormat("######0.00");
            String amount = df.format(Double.valueOf(request.getAmount()));
            // 4. JuHeZhong支付
            OrderEntity orderEntity = new OrderEntity(code, request.getSubMerchantCode(), payNo, payCode, "quick", request.getPayChannel(), "1", amount, request.getSubject(), "", "6", request.getCardCode());
            payService.addUserBenefits(userInfo, orderEntity, orderEntity.getCode(), request);
            resp.setMessage(ComCode.STATUS_CODE_2000_DESC);
            resp.setStatus(ComCode.STATUS_CODE_2000);
        } catch (Exception e) {
            resp.setMessage(ComCode.STATUS_CODE_9998_DESC);
            resp.setStatus(ComCode.STATUS_CODE_9998);
            resp.setError(e.getMessage());
        }
        return resp;
    }
}
