package com.supplier.controller;

import com.supplier.model.BuyOfferNum;
import com.supplier.model.SupplierRelease;
import com.supplier.model.TopUpRecord;
import com.supplier.model.WxPay;
import com.supplier.service.PersonalServce;
import com.supplier.service.SupplierReleaseService;
import com.supplier.service.WxPayService;
import com.supplier.util.ParsingToken;
import com.supplier.util.PayToolUtil;
import com.supplier.util.SnowflakeUtil;
import com.supplier.util.WXPayUtil;
import com.supplier.vx.pay.*;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.util.*;

/**
 * 微信扫码支付
 */
@RestController
@RequestMapping("/wxpay")
public class WxpayController extends WxPayUtils {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private PersonalServce personalServce;
    @Autowired
    private SupplierReleaseService supplierReleaseService;
    //雪花算法
    private SnowflakeUtil snowflakeUtil = new SnowflakeUtil(1, 1, 1);

    /**
     * 微信支付请求
     * @param price 金额
     */
    @GetMapping("qrcode")
    public Map<String, Object> wxpayPay(String price, String attach) throws ParseException {
        //当前时间
        String currTime = PayToolUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = String.valueOf(PayToolUtil.buildRandom(4));
        String nonce_str = strTime + strRandom;
        //订单号
        WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类
        PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类
        String out_trade_no = wxPayUtil.getOrderNo();
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        //获取订单金额
        SupplierRelease supplierRelease = new SupplierRelease().setUuid(attach);
        List<SupplierRelease> list = supplierReleaseService.getSupplierRelease(supplierRelease);

        packageParams.put("appid", APPID);//公众账号ID
        packageParams.put("attach", attach);//报价单编号
        packageParams.put("mch_id", MCHID);//商户号
        packageParams.put("body", "途丫-" + out_trade_no);//商品描述
        packageParams.put("out_trade_no", out_trade_no);//商户订单号
        packageParams.put("nonce_str", nonce_str);//随机字符串
        packageParams.put("total_fee", wxPayUtil.getMoney(list.get(0).getPriceAll())); //订单金额信息
        packageParams.put("spbill_create_ip", CREATE_IP);//终端IP APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
        packageParams.put("notify_url", NOTIFY_URL);//通知地址 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数
        packageParams.put("trade_type", "NATIVE");//交易类型 NATIVE 扫码支付

        // 签名
        String sign = payToolUtil.createSign("UTF-8", packageParams, KEY);
        packageParams.put("sign", sign);

        // 将请求参数转换为xml格式的string
        String requestXML = payToolUtil.getRequestXml(packageParams);


        // 调用微信支付统一下单接口
        String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
        // 解析微信支付结果
        Map map = null;
        try {
            map = doXMLParse.doXMLParse(resXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回前端生成二维码
        Map<String, Object> resultMap = new HashMap<>();

//        WxPay wxPay1 = wxPayService.getRefundVal(attach);//获取付该报价单付款的信息
//        if(null == wxPay1){
            //生成uuid
//            String uuid = UUID.randomUUID().toString().replace("-", "");
//            WxPay wxPay = new WxPay()
//                    .setUuid(uuid)
//                    .setMchId(MCHID)
//                    .setReleaseUuid(attach)
//                    .setCodeUrl((String) map.get("code_url"))
//                    .setOutTradeNo(out_trade_no)
//                    .setTotalFee(price)
//                    .setBody("途丫-" + out_trade_no);
//            wxPayService.pay(wxPay);
            resultMap.put("out_trade_no", out_trade_no);//订单编号
            resultMap.put("result_code", map.get("result_code"));//订单状态
            resultMap.put("code_url", map.get("code_url"));//支付路径
//        } else {
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date time = new Date();
//            Date dateStr = simpleDateFormat.parse(wxPay1.getJdrq());
//            long timeLag = timePoor(time.getTime(), dateStr.getTime());
//            if(timeLag >= 120){
//                SupplierRelease supplierRelease1 = new SupplierRelease()
//                        .setCode(list.get(0).getCode())
//                        .setDemandUuid(list.get(0).getDemandUuid())
//                        .setOrderType("11");
//                supplierReleaseService.updatePrivateType(supplierRelease1);
//                resultMap.put("msg", "500");
//                resultMap.put("errMsg", "该订单已超时");
//                return resultMap;
//            }
//            resultMap.put("out_trade_no", wxPay1.getOutTradeNo());//订单编号
//            resultMap.put("result_code", "SUCCESS");//订单状态
//            resultMap.put("code_url", wxPay1.getCodeUrl());//支付路径
//        }
        return resultMap;
    }

    /**
     * 计算时间差
     * @param start 开始时间
     * @param end 结束时间
     * @return 返回结果
     */
    public long timePoor(long start,long end){
        long timeLag = start - end;
        //天
        long day=timeLag/(24*60*60*1000);
        //小时
        long hour=(timeLag/(60*60*1000)-day*24);
        //分钟
        long minute=((timeLag/(60*1000))-day*24*60-hour*60);
        return minute;
    }

    /**
     * 供应商充值
     * @param price 金额
     */
    @GetMapping("wxpaySupplierBalance")
    public Map<String, Object> wxpaySupplierBalance(String price, HttpServletRequest request){
        //当前时间
        String currTime = PayToolUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = String.valueOf(PayToolUtil.buildRandom(4));
        String nonce_str = strTime + strRandom;
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        //订单号
        WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类
        PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类
        String out_trade_no = wxPayUtil.getOrderNo();
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        String uuid = snowflakeUtil.nextId() + "";//不重复编号
        packageParams.put("appid", APPID);//公众账号ID
        packageParams.put("attach", "gysTopUp" + "," + uuid + "," + userMap.get("code"));//自定义信息
        packageParams.put("mch_id", MCHID);//商户号
        packageParams.put("body", "途丫-" + out_trade_no);//商品描述
        packageParams.put("out_trade_no", out_trade_no);//商户订单号
        packageParams.put("nonce_str", nonce_str);//随机字符串
        packageParams.put("total_fee", wxPayUtil.getMoney(price)); //订单金额信息
        packageParams.put("spbill_create_ip", CREATE_IP);//终端IP APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
        packageParams.put("notify_url", NOTIFY_URL);//通知地址 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数
        packageParams.put("trade_type", "NATIVE");//交易类型 NATIVE 扫码支付
        // 签名
        String sign = payToolUtil.createSign("UTF-8", packageParams, KEY);
        packageParams.put("sign", sign);

        // 将请求参数转换为xml格式的string
        String requestXML = payToolUtil.getRequestXml(packageParams);


        // 调用微信支付统一下单接口
        String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
        // 解析微信支付结果
        Map map = null;
        try {
            map = doXMLParse.doXMLParse(resXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回前端生成二维码
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("out_trade_no", uuid);//订单编号
        resultMap.put("result_code", map.get("result_code"));//订单状态
        resultMap.put("code_url", map.get("code_url"));//支付路径
        //充值信息入库
//        WxPay wxPay = new WxPay().setCode((String) userMap.get("code")).setUuid(uuid);
//        wxPayService.buySupplierBalance(wxPay); //充值
        return resultMap;

    }

    /**
     * 供应商购买次数
     * @param offerNum 购买次数
     */
    @GetMapping("wxpaySupplierOfferNum")
    public Map<String, Object> wxpaySupplierOfferNum(String offerNum, HttpServletRequest request){
        //当前时间
        String currTime = PayToolUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = String.valueOf(PayToolUtil.buildRandom(4));
        String nonce_str = strTime + strRandom;
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        Map<String, Object> map1 = personalServce.getByNumber();//获取报价单单价
        Map<String, Object> map2 = (Map<String, Object>) map1.get("data");
        String price = (Integer.parseInt(offerNum) * Double.parseDouble(String.valueOf(map2.get("power_unit")))) + ""; //购买次数 * 报价单单价
        //订单号
        WXPayUtil wxPayUtil = new WXPayUtil(); //微信工具类
        PayToolUtil payToolUtil = new PayToolUtil();//数据转换工具类
        String out_trade_no = wxPayUtil.getOrderNo();
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        String uuid = snowflakeUtil.nextId() + "";//不重复编号
        packageParams.put("appid", APPID);//公众账号ID
        packageParams.put("attach", "gysOfferNum" + "," + uuid + "," + userMap.get("code") + "," + offerNum);//自定义信息
        packageParams.put("mch_id", MCHID);//商户号
        packageParams.put("body", "途丫-" + out_trade_no);//商品描述
        packageParams.put("out_trade_no", out_trade_no);//商户订单号
        packageParams.put("nonce_str", nonce_str);//随机字符串
        packageParams.put("total_fee", wxPayUtil.getMoney(price)); //订单金额信息
        packageParams.put("spbill_create_ip", CREATE_IP);//终端IP APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
        packageParams.put("notify_url", NOTIFY_URL);//通知地址 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数
        packageParams.put("trade_type", "NATIVE");//交易类型 NATIVE 扫码支付
        // 签名
        String sign = payToolUtil.createSign("UTF-8", packageParams, KEY);
        packageParams.put("sign", sign);

        // 将请求参数转换为xml格式的string
        String requestXML = payToolUtil.getRequestXml(packageParams);


        // 调用微信支付统一下单接口
        String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
        // 解析微信支付结果
        Map map = null;
        try {
            map = doXMLParse.doXMLParse(resXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回前端生成二维码
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("out_trade_no", uuid);//订单编号
        resultMap.put("result_code", map.get("result_code"));//订单状态
        resultMap.put("code_url", map.get("code_url"));//支付路径
        //购买次数信息入库
//        BuyOfferNum buyOfferNum = new BuyOfferNum().setUuid(uuid).setOfferNum(offerNum).setCode((String) userMap.get("code"));
//        personalServce.addBuyOfferNum(buyOfferNum); //充值
        return resultMap;

    }

    /**
     * 查询订单是否支付完毕
     * @param releUuid 参数
     * @return 返回结果
     */
    @GetMapping("getPolling")
    public Map<String ,Object> getPolling(String releUuid){
        Map<String, Object> map = new HashMap<>();
        try{
            map.put("msg", "200");
            map.put("data", wxPayService.getPolling(releUuid));
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    /**
     * 查询用户是否充值成功
     * @param wxPay 参数
     * @return 返回结果
     */
    @GetMapping("getTopUp")
    public Map<String ,Object> getTopUp(WxPay wxPay, HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        try{
            //获取token
            Map<String, Object> userMap = ParsingToken.tokenParsing(request);
            wxPay.setCode((String) userMap.get("code"));
            map.put("msg", "200");
            map.put("data", wxPayService.getTopUp(wxPay));
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "服务器请求异常，请稍后再试");
        }
        return map;
    }

    /**
     * 查询用户是否购买次数成功
     * @param buyOfferNum 参数
     * @param request 参数
     * @return 返回结果
     */
    @GetMapping("getOfferNum")
    public Map<String ,Object> getOfferNum(BuyOfferNum buyOfferNum, HttpServletRequest request){
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        buyOfferNum.setCode((String) userMap.get("code"));
        return wxPayService.getOfferNum(buyOfferNum);
    }

    /**
     * 查询充值记录
     * @param topUpRecord 参数
     * @param request 参数
     * @return 返回结果
     */
    @GetMapping("getTopUpRecord")
    public Map<String, Object> getTopUpRecord(TopUpRecord topUpRecord, HttpServletRequest request){
        //获取token
        Map<String, Object> userMap = ParsingToken.tokenParsing(request);
        topUpRecord.setCode((String) userMap.get("code"));
        return wxPayService.getTopUpRecord(topUpRecord);
    }
}
