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.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighCompanyAccount;
import com.hai.enum_type.CompanyAmountSourceTypeEnum;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighCompanyAccountRecordService;
import com.hai.service.HighCompanyAccountService;
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.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 = "/companyAccount")
@Api(value = "代理商接口")
public class HighCompanyAmountController {

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

    @Resource
    private HighCompanyAccountService companyAccountService;

    @Resource
    private HighCompanyAccountRecordService companyAccountRecordService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/recharge", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "余额充值")
    public synchronized ResponseData recharge(@RequestBody JSONObject body) {
        try {

                if (body.getLong("orgId") == null
                || body.getBigDecimal("amount") == null
                || StringUtils.isBlank(body.getString("smsCode"))) {
                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 (redisUtil.get("COMPANY_AMOUNT_RECHARGE_SMS_CODE") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");
            }
            if (!redisUtil.get("COMPANY_AMOUNT_RECHARGE_SMS_CODE").toString().equals(body.getString("smsCode"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("sourceType", CompanyAmountSourceTypeEnum.type1.getType());
            map.put("sourceContent",  "充值金额：" + body.getBigDecimal("amount") + " 元");
            companyAccountService.recharge(body.getLong("orgId"), 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 = "/getAccountRecordList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询账户记录列表")
    public ResponseData getAccountRecordList(@RequestParam(name = "companyId", required = false) Long companyId,
                                             @RequestParam(name = "orgId", required = false) Long orgId,
                                             @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, "");
            }

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

            if (userInfoModel.getBsCompany() != null && userInfoModel.getSecUser().getAdminFlag() == 1) {
                param.put("companyId", userInfoModel.getBsCompany().getId());
                param.put("orgId", orgId);
            } else if (userInfoModel.getBsCompany() != null && userInfoModel.getSecUser().getAdminFlag() == 0) {
                param.put("orgId", userInfoModel.getBsOrganization().getId());
            }

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

        } catch (Exception e) {
            log.error("HighCompanyAmountController --> 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, "");
            }

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

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

}
