package com.order.controller.notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.config.CommonSysConst;
import com.hfkj.meituan.MeiTuanService;
import com.meituan.sqt.utils.EncryptUtil;
import com.meituan.sqt.utils.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

@Controller
@RequestMapping(value = "/meiTuan")
@Api(value = "美团通知")
public class MeiTuanController {

    private static Logger log = LoggerFactory.getLogger(MeiTuanService.class);

    @RequestMapping(value = "/placeOrder", method = RequestMethod.POST)
    @ApiOperation(value = "下单")
    @ResponseBody
    public void placeOrder(@RequestBody JSONObject reqBodyStr, HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("============回调任务Start=============");
            String accessKey = reqBodyStr.getString("accessKey");
            String content = reqBodyStr.getString("content");
            log.info("美团下单-回调参数: {}", reqBodyStr);
            if (accessKey == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "accessKey错误");
            }
            if (!Objects.equals(accessKey, CommonSysConst.getSysConfig().getMtAccessKey())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "accessKey错误");
            }

            if (content == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "content错误");
            }


            JSONObject jsonObject = JSONObject.parseObject(EncryptUtil.aesDecrypt(content, CommonSysConst.getSysConfig().getMtSecretKey()));;
            log.info("美团下单-解密参数: {}", jsonObject);

            log.info("============回调任务End=============");


            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer= response.getWriter();
            writer.write("SUCCESS");


        } catch (Exception e) {
            log.error("WechatPayController --> wechatNotify() error!", e);
        }
    }
}
