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.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.*;
import com.hai.entity.ApiMerchants;
import com.hai.entity.ApiProduct;
import com.hai.entity.ApiProductConfig;
import com.hai.enum_type.ApiAmountRecordTypeEnum;
import com.hai.enum_type.CompanyAmountSourceTypeEnum;
import com.hai.model.HighMerchantModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.ApiMerchantsService;
import com.hai.service.ApiProductService;
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.beans.factory.annotation.Autowired;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/apiMerchants")
@Api(value = "api商户")
public class ApiMerchantsController {

    Logger log = LoggerFactory.getLogger(ApiProductController.class);

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/getListApiMerchant", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询产品列表")
    public ResponseData getListApiMerchant(
            @RequestParam(value = "merchantName", required = false) String merchantName,
            @RequestParam(value = "mchId", required = false) String mchId,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize, HttpServletRequest request
    ) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            map.put("merchantName", merchantName);
            map.put("phone", phone);
            map.put("mchId", mchId);
            map.put("status", status);

            PageHelper.startPage(pageNum,pageSize);

            List<ApiMerchants> list = apiMerchantsService.getListApiMerchants(map);
            return ResponseMsgUtil.success(new PageInfo<>(list));

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

    @RequestMapping(value = "/getListApiMerchantByAll", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询所以可用商户列表")
    public ResponseData getListApiMerchantByAll(HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            map.put("status", 100);

            List<ApiMerchants> list = apiMerchantsService.getListApiMerchants(map);
            return ResponseMsgUtil.success(list);

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

    @RequestMapping(value="/insertMerchant",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加商户")
    public ResponseData insertMerchant(@RequestBody ApiMerchants apiMerchants, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighMerchantController -> updateMerchant() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            if (StringUtils.isBlank(apiMerchants.getMerchantName())
                    || StringUtils.isBlank(apiMerchants.getPhone())
                    || StringUtils.isBlank(apiMerchants.getUserName())
            ) {
                log.error("ApiMerchantsController -> insertMerchant() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            apiMerchants.setCreateTime(new Date());
            apiMerchants.setOperatorId(userInfoModel.getSecUser().getId());
            apiMerchants.setOperatorName(userInfoModel.getSecUser().getUserName());
            apiMerchants.setStatus(100);
            apiMerchants.setAmounts(new BigDecimal(0));
            apiMerchants.setUpdateTime(new Date());
            apiMerchants.setMchId(DateUtil.date2String(new Date(), "yyyyMM") + IDGenerator.nextId(5));
            apiMerchants.setApiKey(WxUtils.MD5(apiMerchants.getMchId() , true));
            apiMerchantsService.insertApiMerchants(apiMerchants);

            return ResponseMsgUtil.success("新增成功");
        } catch (Exception e) {
            log.error("ApiMerchantsController -> insertMerchant() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/updateMerchant",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改商户")
    public ResponseData updateMerchant(@RequestBody ApiMerchants apiMerchants, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (userInfoModel.getBsCompany() == null) {
                log.error("ApiMerchantsController -> updateMerchant() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            ApiMerchants merchants = apiMerchantsService.findById(apiMerchants.getId());

            if (StringUtils.isBlank(apiMerchants.getMerchantName())
                    || StringUtils.isBlank(apiMerchants.getPhone())
                    || StringUtils.isBlank(apiMerchants.getUserName())
                    || apiMerchants.getId() == null
            ) {
                log.error("ApiMerchantsController -> insertMerchant() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            merchants.setOperatorId(userInfoModel.getSecUser().getId());
            merchants.setOperatorName(userInfoModel.getSecUser().getUserName());
            merchants.setUpdateTime(new Date());
            merchants.setMerchantName(apiMerchants.getMerchantName());
            merchants.setPhone(apiMerchants.getPhone());
            merchants.setUserName(apiMerchants.getUserName());
            apiMerchantsService.updateApiMerchants(merchants);

            return ResponseMsgUtil.success("修改成功");
        } catch (Exception e) {
            log.error("HighMerchantController -> insertMerchant() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询详情")
    public ResponseData findById(@RequestParam(value = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(apiMerchantsService.findById(id));

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

    @RequestMapping(value = "/editMerchantsStatus", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改商户状态")
    public ResponseData editMerchantsStatus(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            ApiMerchants merchants = apiMerchantsService.findById(object.getLong("id"));

            merchants.setStatus(object.getInteger("status"));
            merchants.setOperatorName(userInfoModel.getSecUser().getUserName());
            merchants.setOperatorId(userInfoModel.getSecUser().getId());
            apiMerchantsService.updateApiMerchants(merchants);

            return ResponseMsgUtil.success("修改成功");

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


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

            if (body.getLong("merchantId") == 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")) < 0) {
                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", ApiAmountRecordTypeEnum.type1.getType());
            map.put("sourceContent",  "充值金额：" + body.getBigDecimal("amount") + " 元");
            apiMerchantsService.recharge(body.getLong("merchantId"), body.getBigDecimal("amount"), map);

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

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

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

    @RequestMapping(value = "/getMerchRechargeData", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户充值记录")
    public ResponseData getMerchRechargeData(@RequestParam(value = "merchantId", required = true) Long merchantId) {
        try {

            return ResponseMsgUtil.success(apiMerchantsService.getMerchRechargeData(merchantId));

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

    @RequestMapping(value = "/getListMerchProduct", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户产品")
    public ResponseData getListMerchProduct(@RequestParam(value = "merchantId", required = true) Long merchantId) {
        try {

            return ResponseMsgUtil.success(apiMerchantsService.getListMerchProduct(merchantId));

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


}
