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

import com.thinkgem.jeesite.common.baseBean.Response;
import com.thinkgem.jeesite.common.constant.ComCode;
import com.thinkgem.jeesite.modules.commonError.MyException;
import com.thinkgem.jeesite.modules.pay.entity.OrderEntity;
import com.thinkgem.jeesite.modules.pay.juhezhong.dto.PayBackDto;
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.BelongBankEntity;
import com.thinkgem.jeesite.modules.user.entity.CardEntity;
import com.thinkgem.jeesite.modules.user.entity.CardSwpaccidEntity;
import com.thinkgem.jeesite.modules.user.service.UserApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
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.util.*;

/**
 * 支付相关
 */
@RestController
@RequestMapping("/api/pay")
public class PayApiController {
    @Autowired
    private PayApiService payService;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserApiService userApiService;

    /**
     * 快捷支付
     *
     * @param request
     * @return
     */
    @PostMapping("/quickPay")
    public Response quickPay(JuHeZhongPayRequest request) {
        Response resp = new Response();
        try {

            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);
                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 {

            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;
    }
    /**
     * 开卡
     *
     * @param request
     * @return
     */
    @PostMapping("/openCard")
    public Response openCard(UserRequest request) {
        Response resp = new Response();
        if(ComCode.PAYCHANNEL_HL2.equals(request.getPayChannel())){
            return payService.openCardJFen(request);
        }
        resp.setMessage("没有该渠道");
        resp.setStatus(ComCode.STATUS_CODE_9998);
        return resp;
    }

    /**
     * 发送验证码
     *
     * @param request
     * @return
     */
    @PostMapping("/sendMessagePay")
    public Response sendMessagePay(JuHeZhongPayRequest request) {
        Response resp = new Response();
        if(ComCode.PAYCHANNEL_HL2.equals(request.getPayChannel())){
            return payService.sendMessageJFen(request);
        }
        resp.setMessage("没有该渠道");
        resp.setStatus(ComCode.STATUS_CODE_9998);
        return resp;
    }

    /**
     * 回调
     * @param request
     * @param response
     */
    @RequestMapping("/notifyPay")
    public void notifyPay(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("。。。。。。回调。。。。。");
        Response responseRetrun = new Response();
        Map map=request.getParameterMap();
        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");
        if("0000".equals(code)){
            System.out.println("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();
        }


    }

    /**
     * 回调
     * @param request
     * @param response
     */
    @RequestMapping("/notifyHuanqiuhuijuPay")
    public void notifyHuanqiuhuijuPay(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("。。。。。。回调。。。。。");
        Response responseRetrun = new Response();
        Map map=request.getParameterMap();
        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)){
            System.out.println("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) {
        System.out.println("。。。。。。openCardCallback回调。。。。。");
        Map map=request.getParameterMap();
        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) {
        System.out.println("。。。。。。支付宝回调。。。。。");
        Response responseRetrun = new Response();
        Map map=request.getParameterMap();
        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)){
            System.out.println("orderId:"+orderId);
            OrderEntity orderEntity = new OrderEntity();

            orderEntity.setPayCode(orderId);

            try {
                orderEntity = payService.aliPayNotifyPay(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 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;

    }


    @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;
    }
}
