package com.yunniu.farming.app;

import com.yunniu.farming.webadmin.model.Result;
import com.yunniu.farming.webadmin.service.WxService;
import com.yunniu.farming.webadmin.service.impl.OrderMainServiceImpl;
import com.yunniu.farming.webadmin.service.impl.WxServiceImpl;
import org.jdom.JDOMException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/wx/")
public class WxController {

    @Resource
    private WxService wxService;

    @Resource
    private WxServiceImpl wxServiceImpl;


    @Resource
    private OrderMainServiceImpl orderMainServiceImpl;


    /**
     * 短信登录
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(String code) {
        return wxService.login(code);
    }


    /**
     * 微信支付
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxPay", method = RequestMethod.POST)
    public Result wxPay(Integer userId, Integer orderId, HttpServletRequest request) {
        try {
            return wxService.wxPay(userId, orderId, request);
        } catch (Exception e) {
            return new Result(103);
        }
    }

    /**
     * 微信异步通知
     */
    @RequestMapping(value = "/notify", method = {RequestMethod.POST, RequestMethod.GET})
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        wxService.notify(request, response);
    }


    /**
     * 回调测试
     */
    @RequestMapping(value = "/testNotifyOk/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String testNotifyOk(@PathVariable Integer id) {
        if (id == null) return null;

        this.wxServiceImpl.handleNotifyOk(id);

        return "ok";
    }

    /**
     * 微信退款回调
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxRefundNotify", method = RequestMethod.POST)
    public void wxRefundNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        wxService.wxRefundNotify(request, response);
    }

    /**
     * 微信退款
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/wxRefund", method = RequestMethod.POST)
    public Result wxRefund(Integer userId, Integer orderId, HttpServletRequest request) {
        try {
            return wxService.wxRefund(userId, orderId, "", request);
        } catch (Exception e) {
            return new Result(103);
        }
    }


//    @RequestMapping(value = "/asd", method = {RequestMethod.POST, RequestMethod.GET})
//    public void asd(String outTradeNo) throws IOException, JDOMException {
//        wxService.asd(outTradeNo);
//    }


}