package com.iformall.controller.mem;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.WxCreditHistory;
import com.iformall.domain.vo.WxCreditHistoryVo;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxCreditHistoryService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("wxCreditHistory")
public class WxCreditHistoryController extends BaseController {
    @Autowired
    private WxCreditHistoryService wxCreditHistoryService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation("分页列表接口")
    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "积分历史-列表")
    public ResultData list(@ModelAttribute WxCreditHistory wxCreditHistory, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxCreditHistoryController::list");
        if (null == wxCreditHistory) wxCreditHistory = new WxCreditHistory();
        final PageInfo<WxCreditHistoryVo> page = wxCreditHistoryService.listAsPageMore(wxCreditHistory, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("根据商户ID和消费金额获取所增加积分 取data里credit的值")
    @GetMapping("findByMerchantIdAndSpend")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantId", value = "商户ID", dataType = "long", paramType = "query", required = true),
            @ApiImplicitParam(name = "spend", value = "消费金额", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "会员Id", dataType = "long", paramType = "query", required = true)})
    @SystemControllerLog(description = "积分历史-根据商户ID和消费金额获取所增加积分")
    public ResultData findByMerchantIdAndSpend(Long merchantId, String spendStr,Long userId) {
        logger.debug("[" + getIpAddr() + "] WxCreditHistoryController::findByMerchantIdAndSpend");
        if(Objects.isNull(merchantId)|| StringUtils.isEmpty(spendStr)||Objects.isNull(userId)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL) ;
        }

        try {
            Map<String, Integer> result = wxCreditHistoryService.findByMerchantIdAndSpend(merchantId, spendStr, userId,getTenantId()) ;
            return new ResultData(result);
        } catch (MallinkException e) {
            return new ResultData(e.getErrorCode(),e.getMessage());
        } catch (Exception e) {
            return new ResultData(ErrorCode.SYS_PARAMETER_ERROR,e.getMessage());
        }
    }

    @ApiOperation("新增接口")
    @PostMapping("add")
    @SystemControllerLog(description = "积分历史-新增接口")
    public ResultData add(@RequestBody WxCreditHistory wxCreditHistory) {
        logger.debug("[" + getIpAddr() + "] WxCreditHistoryController::add");
        MallUserInfo user = getUser();
        wxCreditHistory.setTenantId(user.getTenantId());
        wxCreditHistory.setOperatorId(user.getId());
        try {
            wxCreditHistoryService.creditUsercheck(wxCreditHistory.getCUserId()) ;
            WxCreditHistory credit = wxCreditHistoryService.saveOrUpdate(wxCreditHistory);
            return new ResultData(Result.SUCCESS, "操作成功", credit);
        } catch (MallinkException e) {
            logger.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        }
    }

    @ApiOperation("根据id查询接口")
    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "积分历史-查询")
    public ResultData findById(Long id) {
        logger.debug("[" + getIpAddr() + "] WxCreditHistoryController::findById");
        return new ResultData(Result.SUCCESS, "查询成功", wxCreditHistoryService.getById(id));
    }

    /**
     * 根据A端设置的【每自然年末扣除前N年用户积分】规则,扣减用户积分
     *
     * @return
     */
    public ResultData clearCreditByYear() {
        logger.debug("[" + getIpAddr() + "] WxCreditHistoryController::clearCreditByYear");
        wxCreditHistoryService.clearCreditByYear();
        return new ResultData(Result.SUCCESS);
    }

    @GetMapping("exportData")
    @SystemControllerLog(description = "积分历史-导出数据")
    public void exportData(@ModelAttribute WxCreditHistory wxCreditHistory, HttpServletRequest request, HttpServletResponse response) {
        wxCreditHistory.setTenantId(getTenantId());
        wxCreditHistoryService.exportData(request, response, wxCreditHistory);
    }

    @ApiOperation("积分统计概览")
    @GetMapping("getCreditSummary")
    @SystemControllerLog(description = "积分历史-积分统计概览")
    public ResultData getCreditSummary(@ModelAttribute WxCreditHistory wxCreditHistory) {
        logger.debug("[" + getIpAddr() + "] WxCreditHistoryController::getCreditSummary");
        wxCreditHistory.setTenantId(getTenantId());
        return wxCreditHistoryService.getCreditSummary(wxCreditHistory);
    }

}
