package com.pj.api.wx.api;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONUtil;
import com.pj.api.wx.bo.Attach;
import com.pj.api.wx.bo.NotifyBO;
import com.pj.api.wx.bo.PrePayBO;
import com.pj.api.wx.service.WxService;
import com.pj.utils.sg.AjaxJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("wx")
@RestController
@Slf4j
public class WxController {
    @Resource
    private WxService wxService;

    @RequestMapping(value = "notify")
    public void notify(@RequestBody NotifyBO notifyBO, HttpServletResponse response) throws Exception{
        log.info("wx pay notify;{}", JSONUtil.toJsonStr(notifyBO));
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Writer writer = response.getWriter();
        Map<String,String>result=new HashMap<>();
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");
        wxService.WxNotify(notifyBO);
        writer.write(XmlUtil.mapToXmlStr(result));
        writer.flush();
        writer.close();
    }

    /**
     * 统一下单接口
     *
     * @param
     * @return
     */
    @RequestMapping(value = "pre-pay")
    public AjaxJson prePay( HttpServletRequest request) throws Exception {
        return AjaxJson.getSuccessData(wxService.prePay(request));
    }

    @GetMapping(value = "getRedirectUrl")
    public AjaxJson getRedirectUrl(String path,@RequestParam(required = false) String state){
        return AjaxJson.getSuccessData(wxService.getRedirectUrl(path,state));
    }
    @GetMapping(value = "getOpenidByCode")
    public AjaxJson getOpenidByCode(String code,@RequestParam(required = false) String openid){
        return AjaxJson.getSuccessData(wxService.getOpenidByCode(code,openid));
    }
    @GetMapping(value = "getWxConfig")
    public AjaxJson getWxConfig(String url){
        return AjaxJson.getSuccessData(wxService.getWxConfig(url));
    }
}
