package com.iamberry.wechat.handles.reserve;

import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.core.entity.rent.ChannelAccess;
import com.iamberry.wechat.core.entity.rent.ReserveOrder;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.reserve.ReserveService;
import com.iamberry.wechat.tools.*;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 献
 * @company 深圳爱贝源科技有限公司
 * @date 2017/7/10 9:11
 * @tel 18271840547
 * @website www.iamberry.com
 */
@Controller
@RequestMapping("/wechat/rent")
public class ReserveController {

    @Autowired
    private ReserveService reserveService;

    @Autowired
    private PayService payService;

    @ResponseBody
    @RequestMapping("/log_access")
    public ResponseJson accessLog(@RequestParam("channel_id") String channelId, HttpServletRequest request) {
        Member member = WechatUtils.getUserBySession(request);
        // 解析用户User-Agent
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 浏览器名称
        Browser browser = userAgent.getBrowser();
        // 访问的系统
        OperatingSystem os = userAgent.getOperatingSystem();
        // 创建访问对象
        ChannelAccess access = new ChannelAccess();
        access.setAccessDeviceModel(os.getName());
        access.setAccessIsMobile(os.isMobileDevice() ? 1 : 2);
        access.setAccessDeviceType(os.getDeviceType().getName());
        access.setAccessBrowser(browser.getName());
        access.setUserOpenid(member.getUserOpenid());
//        access.setUserOpenid("hexiugang");
        access.setAccessCreateTime(new Date());
        String tempId = com.iamberry.jwt.AES.decrypt(StringUtils.replace(channelId, "*", "\\"));
        access.setChannelId(Integer.parseInt(tempId == null ? "0" : tempId));

        reserveService.addAccess(access);

        return ResponseJson.SUCCESS;
    }

    @ResponseBody
    @RequestMapping("/sub_order")
    public ResponseJson subOrder(ReserveOrder order, HttpServletRequest request) {
        Member member = WechatUtils.getUserBySession(request);
        order.setReserveOpenid(member.getUserOpenid());
//        order.setReserveOpenid("o3G6nw_3cxE7CINzCT1or2f6dxL4");
        order.setReserveStatus(1);
        order.setReservePayMoney(9900);

        // 校验参数
        ValidationResult result = ValidationUtils.validateEntity(order);
        if (result.isHasErrors()) {
            return new ResponseJson(200, "FAILURE", 500).addResponseKeyValue("pay_error", result.getErrorMsgList().get(0));
        }

        reserveService.addOrder(order);
        if (order.getReserveOrderid() == null) {
            return ResponseJson.FAILURE.addResponseKeyValue("pay_error", "支付失败，请重试!");
        }

        PayResult res = payService.requestPay(order.getReserveOpenid(),
                "YD-000000" + order.getReserveOrderid(), Integer.parseInt(NameUtils.getConfig("reserve_pay_money")), "美国WaterO净水机", NameUtils.getConfig("RESERVE_PAY_CALLBACK"));
        if (res.isPaySuccess()) {
            return ResponseJson.SUCCESS.addResponseKeyValue("pay_data", res.getPayData()).addResponseKeyValue("order_id", order.getReserveOrderid());
        } else {
            return ResponseJson.FAILURE.addResponseKeyValue("pay_error", res.getPayData());
        }
    }

    @ResponseBody
    @RequestMapping("/check_order_pay")
    public ResponseJson checkOrderPay(@RequestParam("order_id")Integer id) {
        ReserveOrder order = reserveService.getOrder(id);
        if (order == null) {
            return ResponseJson.FAILURE;
        }
        if (order.getReserveStatus() != 2) {
            // 支付失败
            return ResponseJson.FAILURE;
        }
        return ResponseJson.SUCCESS;
    }
}
