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.AESEncodeUtil;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighCompanyAccount;
import com.hai.entity.HighCompanyTwoPwd;
import com.hai.entity.HighMerchantStoreAccount;
import com.hai.enum_type.CompanyAmountSourceTypeEnum;
import com.hai.enum_type.MerStoreAmountSourceTypeEnum;
import com.hai.enum_type.MerStoreAmountTypeEnum;
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.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
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 = "/merStoreAccount")
@Api(value = "商户门店接口")
public class HighMerStoreAmountController {

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

    @Resource
    private HighMerchantStoreAccountService merchantStoreAccountService;

    @Resource
    private HighMerchantStoreAccountRecordService merchantStoreAccountRecordService;

    @Resource
    private HighCompanyTwoPwdService companyTwoPwdService;

    @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("storeId") == null
                    || body.getBigDecimal("amount") == 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");
            }
            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());
            merchantStoreAccountService.recharge(body.getLong("storeId"), body.getBigDecimal("amount"), 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 = "/setAmountsEarlyWarning", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设置加油站预警值")
    public ResponseData setAmountsEarlyWarning(@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("storeId") == null || body.getBigDecimal("earlyWarning") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            if (body.getBigDecimal("earlyWarning").compareTo(new BigDecimal("0")) == -1) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "充值金额不能小于0");
            }
            // 门店
            HighMerchantStoreAccount accountDetail = merchantStoreAccountService.getStoreAccountDetail(body.getLong("storeId"));
            if (accountDetail == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "此加油站无法设置预警");
            }
            accountDetail.setAmountsEarlyWarning(body.getBigDecimal("earlyWarning"));
            merchantStoreAccountService.editStoreAccount(accountDetail);

            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 = "/getAccountRecordList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询账户记录列表")
    public ResponseData getAccountRecordList(@RequestParam(name = "type", required = false) Integer type,
                                             @RequestParam(name = "sourceType", required = false) Integer sourceType,
                                             @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                             @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                             @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                             @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            if (userInfoModel.getMerchantStore() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("storeId", userInfoModel.getMerchantStore().getId());
            param.put("type", type);
            param.put("sourceType", sourceType);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(merchantStoreAccountRecordService.getRecordList(param)));

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

    @RequestMapping(value = "/getAccount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询账户")
    public ResponseData getAccount() {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            if (userInfoModel.getMerchantStore() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }

            Map<String, Object> map = new HashMap<>();
            // 查询公司账户
            HighMerchantStoreAccount account = merchantStoreAccountService.getStoreAccountDetail(userInfoModel.getMerchantStore().getId());
            if (account == null) {
                map.put("amounts", 0);
            } else {
                map.put("amounts", account.getAmounts());
            }
            return ResponseMsgUtil.success(map);

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

}
