package com.miaxis.app.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.miaxis.common.config.WxpayConfig;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.controller.BaseController;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.domain.entity.SysUser;
import com.miaxis.common.core.domain.entity.UserInfo;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.common.utils.uuid.CommonUtils;
import com.miaxis.system.service.ISysDictDataService;
import com.miaxis.system.service.ISysUserService;
import com.miaxis.wx.domain.WxOrder;
import com.miaxis.wx.service.IWxOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;

import static com.miaxis.common.utils.OrderCodeFactory.getOrderCode;

/**
 * 【小程序-微信支付】Controller
 *
 * @author miaxis
 * @date 2021-03-10
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(Constants.STUDENT_PREFIX+"/wx")
@Api(tags = {"【app-微信支付】"})
@Slf4j
public class WxController extends BaseController {

    @Autowired
    private HttpClient httpClient;

    @Autowired
    private WxpayConfig wxpayConfig;

    @Autowired
    private IWxOrderService wxOrderService;


    @Autowired
    private ISysUserService sysUserService;

    @Value("${app.appid}")
    private String appid;
    @Value("${wxpay.notifyUrl}")
    private  String notifyUrl ;






//    @GetMapping("/order/list")
//    @ApiOperation("查询订单列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum",value = "当前页码" ,dataType = "int", paramType = "query", required = false),
//            @ApiImplicitParam(name = "pageSize",value = "每页数据量" , dataType = "int", paramType = "query", required = false),
//    })
//    public ResponsePageInfo<WxOrder> list(@ModelAttribute WxOrderListDTO wxOrderListDTO){
//
//        String openid = SecurityUtils.getLoginUser().getStudent().getAppOpenid()();
//        startPage();
//        wxOrderListDTO.setOpenid(openid);
//        List<WxOrder> list = wxOrderService.selectOrderList(wxOrderListDTO);
//        return toResponsePageInfo(list);
//    }

    /**
     * 微信支付获取预订单id
     */
    @PostMapping(value = "/prepareOrder")
    @ApiOperation("app端微信支付下单")
    public Response<WxParamEntity> getPrepareOrder(String referralCode) throws Exception{

        //创建本地微信订单
        WxOrder order = new WxOrder();
        UserInfo student = SecurityUtils.getLoginUser().getStudent();
        String orderCode = getOrderCode(student.getId());
        order.setOutTradeNo(orderCode);
        order.setAppOpenid(student.getAppOpenid());
        order.setUnionId(student.getUnionId());
        order.setGoodsType("1");
        SysUser sysUser = sysUserService.selectUserByReferralCode(referralCode);
        if (sysUser != null){
            order.setReferralUserId(sysUser.getUserId());
        }
        wxOrderService.createVipOrder(order);
        wxOrderService.save(order);
        return Response.success(placeWxOrder(order, "学车vip充值"));


    }


    /**
     * 查询是否存在推荐码
     */
    @GetMapping(value = "/{referralCode}")
    @ApiOperation("查询是否存在推荐码")
    public Response<Boolean> getInfo(
            @ApiParam(name = "referralCode", value = "推荐码", required = true)
            @PathVariable("referralCode") String referralCode
    ){

        return Response.success(sysUserService.selectUserByReferralCode(referralCode)!= null ? true :false);
    }


    //下单
    private WxParamEntity placeWxOrder(WxOrder order, String goodsName) throws Exception {
        HttpPost httpPost = initHttpPost();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("mchid",wxpayConfig.getMerchantId())
                .put("appid", appid)
                .put("description", goodsName)
                .put("notify_url", notifyUrl)
                .put("out_trade_no", order.getOutTradeNo());
        rootNode.putObject("amount")
                .put("total", order.getTotal());
        objectMapper.writeValue(bos, rootNode);
        httpPost.setEntity(new StringEntity(rootNode.toString(), "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        String bodyAsString = EntityUtils.toString(response.getEntity());
        if (JSONObject.parseObject(bodyAsString).get("prepay_id") == null){
            throw new CustomException(JSONObject.parseObject(bodyAsString).get("message").toString());
        }
        return getWxParamJson(bodyAsString,order.getOutTradeNo());

    }

    // 生成调用调起微信支付所需参数
    private WxParamEntity getWxParamJson(String bodyAsString, String orderCode) throws Exception {
        WxParamEntity wxParamEntity = new WxParamEntity();
        wxParamEntity.setAppId(appid);
        wxParamEntity.setPartnerId(wxpayConfig.getMerchantId());
        String  prepayId = JSONObject.parseObject(bodyAsString).getString("prepay_id");
        wxParamEntity.setPrepayId(prepayId);
        wxParamEntity.setPackageValue("Sign=WXPay");
        String nonce_str = RandomStringUtils.randomAlphanumeric(32);
        wxParamEntity.setNonceStr(nonce_str);
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        wxParamEntity.setTimeStamp(timestamp);

        StringBuffer sb = new StringBuffer();
        sb.append(appid + "\n");
        sb.append(timestamp + "\n");
        sb.append(nonce_str + "\n");
        sb.append(prepayId+ "\n");


        File file = new ClassPathResource("wechatpay/apiclient_key.pem").getFile();
        String realPath =file.getAbsolutePath();
        PrivateKey privateKey = CommonUtils.getPrivateKey(realPath);
        // 进行签名服务
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(sb.toString().getBytes("UTF-8"));
        byte[] signedData = signature.sign();
        String base64Str =  Base64.getEncoder().encodeToString(signedData);
        wxParamEntity.setSign(base64Str);

        return wxParamEntity;
    }

    private HttpPost initHttpPost() {
        HttpPost httpPost = new HttpPost(wxpayConfig.getV3url());
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        return httpPost;
    }

    @Data
    class  WxParamEntity{
        String appId;
        String partnerId;
        String prepayId;
        String packageValue;
        String nonceStr;
        String timeStamp;
        String sign;

    }










}
