package com.v1.controller.business;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.ApiMerchants;
import com.hai.entity.HighGoldRec;
import com.hai.entity.HighUser;
import com.hai.model.ResponseData;
import com.hai.service.*;
import com.hai.service.impl.OutRechargeOrderServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/orderRebate")
@Api(value = "订单返利")
public class OrderRebateController {

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

    @Resource
    private BsOrderRebateService bsOrderRebateService;

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private SecConfigService secConfigService;

    @Resource
    private HighGoldRecService highGoldRecService;

    @Resource
    private ApiIpAddressService apiIpAddressService;

    @RequestMapping(value = "/rebate", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "积分返利")
    public ResponseData rebate(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("phone")) ||
                    StringUtils.isBlank(object.getString("productType")) ||
                    StringUtils.isBlank(object.getString("orderNo")) ||
                    StringUtils.isBlank(object.getString("orderId")) ||
                    StringUtils.isBlank(object.getString("price")) ||
                    StringUtils.isBlank(object.getString("title")) ||
                    StringUtils.isBlank(object.getString("createTime")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "商户号错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("merchId" , object.getString("merchId"));
            map.put("phone" , object.getString("phone"));
            map.put("productType" , object.getInteger("productType"));
            map.put("orderNo" , object.getString("orderNo"));
            map.put("orderId" , object.getLong("orderId"));
            map.put("price" , object.getBigDecimal("price"));
            map.put("title" , object.getString("title"));
            map.put("createTime" , object.getDate("createTime"));
            map.put("apiKey" , apiMerchants.getApiKey());

            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }

            bsOrderRebateService.insertOrderRebate(object);

            return ResponseMsgUtil.success("赠送成功");
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/recycleIntegral", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退款回收积分")
    public ResponseData recycleIntegral(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("orderNo")) ||
                    StringUtils.isBlank(object.getString("orderId")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "商户号错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("apiKey" , apiMerchants.getApiKey());
            map.put("merchId" , object.getString("merchId"));
            map.put("orderId" , object.getString("orderId"));
            map.put("orderNo" , object.getString("orderNo"));


            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }


            Map<String, Object> mapGold = new HashMap<>();
            mapGold.put("goldType", 1);
            mapGold.put("resId", object.getLong("orderId"));
            mapGold.put("resOrderNo", object.getString("orderNo"));

            List<HighGoldRec> goldRecs = highGoldRecService.getGoldRec(mapGold);

            if (goldRecs.size() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , "未知订单号");
            }

            Integer integralNum = 0;

            Long userId = null;

            for (HighGoldRec goldRec : goldRecs) {
                userId = goldRec.getUserId();
                integralNum += goldRec.getGold();
            }

            HighUser user = highUserService.findByUserId(userId);

            if (integralNum > user.getGold()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "积分数量不足");
            }

            String remark = "订单" + object.getString("orderNo") + "退款积分冻结：" + integralNum;
            // 积分退款
            highUserService.goldHandle(user.getId(), integralNum,2, 103, object.getLong("orderId") , remark , object.getString("orderNo"));

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/refundReturn", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "退款回调")
    public ResponseData refundReturn(@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 (!apiIpAddressService.validationIpAddressLegal(object.getString("merchId") , ip)) {
                log.error("getRechargeProduct error!", "非法ip地址，请联系管理人员！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.IP_ERROR, "非法ip地址，请联系管理人员！");
            }

            if (
                    StringUtils.isBlank(object.getString("merchId")) ||
                    StringUtils.isBlank(object.getString("orderId")) ||
                    StringUtils.isBlank(object.getString("refundStatus")) ||
                    StringUtils.isBlank(object.getString("orderNo")) ||
                    StringUtils.isBlank(object.getString("sign"))
            ) {
                log.error("getRechargeProduct error!", "请求参数校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR);
            }

            ApiMerchants apiMerchants = apiMerchantsService.findByMchId(object.getString("merchId"));

            if (apiMerchants == null) {
                log.error("getRechargeProduct error!", "商户号错误！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_NOT_EXIST);
            }

            Map<String , Object> map = new HashMap<>();
            map.put("apiKey" , apiMerchants.getApiKey());
            map.put("merchId" , object.getString("merchId"));
            map.put("orderId" , object.getLong("orderId"));
            map.put("refundStatus" , object.getString("refundStatus"));
            map.put("orderNo" , object.getString("orderNo"));


            if (!secConfigService.isSignVerify(map , object.getString("sign"))) {
                log.error("getRechargeProduct error!", "签名校验失败！");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SIGN_VERIFY);
            }

            Map<String, Object> mapGold = new HashMap<>();
            mapGold.put("goldType", 2);
            mapGold.put("resType", 103);
            mapGold.put("resId", object.getLong("orderId"));

            HighGoldRec goldRecs = highGoldRecService.findGoldRec(mapGold);

            if (goldRecs == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , "未知订单号");
            }

            if (object.getString("refundStatus").equals("succeed")) {
                // 查询是否存在多次退款
                Map<String, Object> mapGoldRepeat = new HashMap<>();
                mapGoldRepeat.put("goldType", 1);
                mapGoldRepeat.put("resType", 3);
                mapGoldRepeat.put("resId", object.getLong("orderId"));

                List<HighGoldRec> goldRecsRepeat = highGoldRecService.getGoldRec(mapGoldRepeat);

                if (goldRecsRepeat.size() > 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR , "重复退款");
                }

                String remark = "订单" + object.getString("orderNo") + "退款成功扣除积分：" + goldRecs.getGold();
                goldRecs.setResType(3);
                goldRecs.setUpdateTime(new Date());
                goldRecs.setRemark(remark);
                highGoldRecService.updateGoldRec(goldRecs);
            } else {

                String remark = "订单" + object.getString("orderNo") + "退款失败，退还积分：" + goldRecs.getGold();
                goldRecs.setStatus(0);
                goldRecs.setUpdateTime(new Date());
                highGoldRecService.updateGoldRec(goldRecs);
                // 积分退款
                highUserService.goldHandle(goldRecs.getUserId(), goldRecs.getGold(),1, 104, object.getLong("orderId") , remark , object.getString("orderNo"));

            }

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
