package com.bweb.controller;

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.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighMerchantAccount;
import com.hai.entity.HighMerchantStoreAccount;
import com.hai.enum_type.MerStoreAmountSourceTypeEnum;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/merAccount")
@Api(value = "商户门店接口")
public class HighMerAmountController {

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

    @Resource
    private HighMerchantAccountService merchantAccountService;

    @Resource
    private HighMerchantAccountMarketingService accountMarketingService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/recharge", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "余额充值")
    public synchronized ResponseData recharge(@RequestBody JSONObject body) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            if (userInfoModel.getBsCompany() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            if (body.getLong("merId") == null || body.getBigDecimal("amount") == null || body.getBoolean("marketingStatus") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            if (body.getBigDecimal("amount").compareTo(new BigDecimal("0")) == -1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "充值金额不能小于0");
            }
            if (body.getBoolean("marketingStatus").equals(true)
                        && body.getInteger("marketingType") == null
                        && body.getBigDecimal("marketingPrice") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("sourceType", MerStoreAmountSourceTypeEnum.type1.getType());
            map.put("sourceContent",  "充值额度：" + body.getBigDecimal("amount") + " 元");
            map.put("opUserId", userInfoModel.getSecUser().getId());
            map.put("opUserName", userInfoModel.getSecUser().getUserName());

            Map<String, Object> marketingParam = new HashMap<>();
            marketingParam.put("marketingStatus", body.getBoolean("marketingStatus"));
            marketingParam.put("marketingType", body.getInteger("marketingType"));
            marketingParam.put("marketingPrice", body.getBigDecimal("marketingPrice"));
            marketingParam.put("marketingOilNoData", body.getJSONArray("marketingOilNoData"));
            merchantAccountService.recharge(body.getLong("merId"), body.getBigDecimal("amount"), marketingParam, map);

            return ResponseMsgUtil.success("操作成功");

        } catch (DeadlockLoserDataAccessException deadlockLoserDataAccessException) {
            log.error("HighActivityController -> userLottery() error!", "服务器繁忙");
            return ResponseMsgUtil.builderResponse(ErrorCode.SERVER_BUSY_ERROR.getCode(),ErrorCode.SERVER_BUSY_ERROR.getMsg(),null);

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

    @RequestMapping(value = "/getMerAccount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户账户")
    public ResponseData getMerAccount(@RequestParam(name = "merId", required = true) Long merId) {
        try {

            BigDecimal account = new BigDecimal("0");
            // 查询商户余额
            HighMerchantAccount merchantAccount = merchantAccountService.getMerAccountDetail(merId);
            if (merchantAccount != null) {
                account = merchantAccount.getAmounts();
            }
            Map<String, Object> param = new HashMap<>();
            param.put("amount", account.subtract(merchantAccountService.countMerGasOilAmount(merId)));
            param.put("oilNoReliefPrice", accountMarketingService.getDetailByMerAndType(merId, 3));

            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value = "/getMerAccountMarketing", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户账户营销信息")
    public ResponseData getMerAccountMarketing(@RequestParam(name = "merId", required = true) Long merId,
                                               @RequestParam(name = "type", required = true) Integer type) {
        try {

            return ResponseMsgUtil.success(accountMarketingService.getDetailByMerAndType(merId, type));

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

}
