package com.bweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongConfig;
import com.hai.dao.HighGasOrderPushMapper;
import com.hai.entity.HighCoupon;
import com.hai.entity.HighGasOrderPush;
import com.hai.entity.HighMerchant;
import com.hai.entity.HighUser;
import com.hai.enum_type.OrderPushType;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighOpenApiService;
import com.hai.service.HighUserService;
import com.hai.service.SecConfigService;
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.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sum1Dream
 * @ClassName HighOpenApiController
 * @Description // 开放接口
 * @Date 2021/11/24 4:49 下午
 **/
@Controller
@RequestMapping(value = "/openApi")
@Api(value = "开放接口")
public class HighOpenApiController {

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

    @Resource
    private HighOpenApiService highOpenApiService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighGasOrderPushMapper highGasOrderPushMapper;

    @Resource
    private SecConfigService secConfigService;

    @Resource
    private HuiLianTongConfig huiLianTongConfig;


    @RequestMapping(value = "/getGuizhouSinopecList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取专属优惠券")
    public ResponseData getUserExclusiveDiscount(@RequestParam(name = "useScope", required = false) Integer useScope,
                                            @RequestParam(name = "phone", required = true) String phone,
                                            @RequestParam(name = "year", required = false) String year) {
        try {

            HighUser highUser = highUserService.findByPhone(phone);

            if (highUser == null || highUser.getStatus() == 0) {
                log.error("getUserOrderPreList error!", "未找到用户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前手机号暂无用户");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("userId", highUser.getId());
            map.put("useScope", useScope);
            if (year != null) {
                map.put("createTimeS", year + "-01-01 00:00:00");
                map.put("createTimeE", year + "-12-31 23:59:59");
            }

            return ResponseMsgUtil.success(highOpenApiService.getUserCouponsList(map));

        } catch (Exception e) {
            log.error("HighOpenApiController --> getGuizhouSinopecList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getGuizhouSinopecList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取贵州中石化电子卡券")
    public ResponseData getGuizhouSinopecList(HttpServletRequest request) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if  (request.getHeader("x-forwarded-for") == null)  {
                ip = request.getRemoteAddr();
            }  else  {
                ip = request.getHeader("x-forwarded-for");
            }

            if (!secConfigService.isConfig("IP_WHITE" , ip)) {
                log.error("getGuizhouSinopec error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "非法ip地址，请联系管理人员！");
            }

            // 获取token
            String token = huiLianTongConfig.getToken();

            // 查询电子卡券类型
            JSONObject corpCouTypes = HuiLianTongConfig.getCorpCouTypes(token);
            System.out.println(corpCouTypes.toJSONString());
            if (!corpCouTypes.getString("result").equals("success")) {
                log.error("HighOpenApiController -> getGuizhouSinopecList() error!","获取电子卡券列表失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取电子卡券列表失败");
            }

            return ResponseMsgUtil.success(corpCouTypes.getJSONArray("data"));
        } catch (Exception e) {
            log.error("HighCouponController -> getGuizhouSinopec() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/checkCouponStatus",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询电子券状态")
    public ResponseData checkCouponStatus(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if  (request.getHeader("x-forwarded-for") == null)  {
                ip = request.getRemoteAddr();
            }  else  {
                ip = request.getHeader("x-forwarded-for");
            }

            if (!secConfigService.isConfig("IP_WHITE" , ip)) {
                log.error("getGuizhouSinopec error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "非法ip地址，请联系管理人员！");
            }

            // 获取token
            String token = huiLianTongConfig.getToken();

            // 查询电子卡券类型
            JSONObject data = HuiLianTongConfig.getCouState(token, object.getString("couNo"));
            if (!data.getString("result").equals("success")) {
                log.error("HighOpenApiController -> insertCoupon() error!","查询电子券状态失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "查询电子券状态失败");
            }

            return ResponseMsgUtil.success(data.getJSONObject("data"));
        } catch (Exception e) {
            log.error("HighCouponController -> getGuizhouSinopec() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/couJointDist",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商户派发电子券")
    public ResponseData couJointDist(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

            String ip = "";
            // 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
            if  (request.getHeader("x-forwarded-for") == null)  {
                ip = request.getRemoteAddr();
            }  else  {
                ip = request.getHeader("x-forwarded-for");
            }

            if (!secConfigService.isConfig("IP_WHITE" , ip)) {
                log.error("couJointDist error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "非法ip地址，请联系管理人员！");
            }

            // 获取token
            String token = huiLianTongConfig.getToken();

            // 商户派发电子券
            JSONObject returnParam = HuiLianTongConfig.couJointDist(token, object.getString("orderNo"), object.getString("couTypeCode"), object.getInteger("distCouCount"), object.getString("phone"), object.getString("thirdUserId"));
            System.out.println("派发电子券" + returnParam);
            // 推送记录
            HighGasOrderPush highGasOrderPush = new HighGasOrderPush();
            highGasOrderPush.setType(OrderPushType.type6.getType());
            highGasOrderPush.setOrderNo(object.getString("orderNo"));
            highGasOrderPush.setCreateTime(new Date());
            highGasOrderPush.setCode(returnParam.getString("result"));
            highGasOrderPush.setRequestContent(JSONObject.toJSONString(object));
            highGasOrderPush.setReturnContent(returnParam.toJSONString());
            highGasOrderPushMapper.insert(highGasOrderPush);
            if (!returnParam.getString("result").equals("success")) {
                log.error("HighOpenApiController -> couJointDist() error!","商户派发电子券失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "商户派发电子券失败");
            }

            return ResponseMsgUtil.success(returnParam.getJSONArray("data"));
        } catch (Exception e) {
            log.error("HighOpenApiController -> couJointDist() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/test",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "测试")
    public ResponseData test(HttpServletRequest request) {
        try {

            String ip = "";

            if (request.getHeader("x-forwarded-for") == null) {
                ip =  request.getRemoteAddr();
            }
            ip =  request.getHeader("x-forwarded-for");

            return ResponseMsgUtil.success(ip);
        } catch (Exception e) {
            log.error("HighCouponController -> getGuizhouSinopec() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
