package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxCUserBasicInfo;
import com.iformall.domain.po.WxCreditHistory;
import com.iformall.domain.po.WxMerchant;
import com.iformall.domain.po.WxMerchantBUser;
import com.iformall.domain.vo.WxCreditHistoryVo;
import com.iformall.enums.EnumMerchantStatus;
import com.iformall.enums.EnumScoreType;
import com.iformall.enums.EnumUserType;
import com.iformall.enums.EnumYesOrNo;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxCUserBasicInfoService;
import com.iformall.service.WxCUserTagsService;
import com.iformall.service.WxCreditHistoryService;
import com.iformall.service.WxMerchantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/credit")
@Api(description = "积分相关接口")
@Slf4j
public class WxCreditHistoryController extends BaseController  {

    @Autowired
    private WxCreditHistoryService wxCreditHistoryService;

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @Autowired
    private WxMerchantService wxMerchantService;

    @Autowired
    private WxCUserTagsService wxCUserTagsService;

    @ApiOperation("根据商户ID和消费金额获取所增加积分 取data里credit的值, 服务台会查询一般商户的信息，普通商户只会调用自己的id")
    @GetMapping("/findByMerchantIdAndSpend")
    @ApiImplicitParams({
            @ApiImplicitParam(name="merchantId",value="商户ID",dataType="long", paramType = "query",required=true),
            @ApiImplicitParam(name="spendStr",value="消费金额",dataType="int", paramType = "query",required=true),
            @ApiImplicitParam(name = "userId", value = "会员Id", dataType = "long", paramType = "query", required = true)})
    public ResultData findByMerchantIdAndSpend(Long merchantId, String spendStr,Long userId) {
        log.debug("[" + getIpAddr() + "] WxCreditHistoryController::findByMerchantIdAndSpend");
        WxMerchant wxMerchant = new WxMerchant();
        wxMerchant.setStatus(EnumYesOrNo.YES.getCode());
        wxMerchant.setId(getUser().getMerchantId());
        wxMerchant = wxMerchantService.findOne(wxMerchant);
        //普通商户只允许查询自己的消费金额所增加的积分
        if (wxMerchant.getIsAdmin() != EnumYesOrNo.YES.getCode() && merchantId.longValue() != getUser().getMerchantId().longValue()) {
            return new ResultData(ErrorCode.USER_NO_PERMISSION);
        }
        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("根据手机号查询接口")
    @GetMapping("/findByPhone")
    @ApiImplicitParam(name = "phone", value = "phone", dataType = "String", paramType = "query", required = true)
    public ResultData findByPhone(String phone) {
        log.debug("[" + getIpAddr() + "] WxCUserBasicInfoController::findByPhone");
        List<WxCUserBasicInfo> wxCUserBasicInfoList = wxCUserBasicInfoService.findByPhone(getTenantId(),phone);
        WxCUserBasicInfo wxCUserBasicInfo = new WxCUserBasicInfo();
        if (wxCUserBasicInfoList != null && wxCUserBasicInfoList.size() > 0) {
            wxCUserBasicInfo = wxCUserBasicInfoList.get(0);
        } else {
            return new ResultData(ErrorCode.USER_NOT_AUTH_PHONE);
        }
        return new ResultData(wxCUserBasicInfo);
    }

    @ApiOperation("新增接口")
    @PostMapping("/add")
    public ResultData add(@RequestBody WxCreditHistory wxCreditHistory) {
        log.debug("[" + getIpAddr() + "] WxCreditHistoryController::add");
        wxCreditHistory.setTenantId(getTenantId());
        wxCreditHistory.setOperatorId(getUser().getId());
        WxMerchant wxMerchant = new WxMerchant();
        wxMerchant.setId(getUser().getMerchantId());
        wxMerchant.setStatus(EnumMerchantStatus.VALID.getCode());
        WxMerchant merchant = wxMerchantService.findOne(wxMerchant);
        //消费积分:取当前人的商户ID
        if (wxCreditHistory.getCreditType() == EnumScoreType.REDUCE_CREDIT.getCode()) {
            wxCreditHistory.setMerchantId(getUser().getMerchantId());
        } else {
            //新增积分:
            //如果为商管商户 则消费商户按前端传入的进行记录
            if (merchant != null && merchant.getIsAdmin() != null && merchant.getIsAdmin() == 1) {
                wxCreditHistory.setMerchantId(wxCreditHistory.getMerchantId());
            } else {
                wxCreditHistory.setMerchantId(getUser().getMerchantId());
            }
        }
        //B端操作用户
        wxCreditHistory.setOperatorType(EnumUserType.BUSER.getCode());
        try {
            wxCreditHistoryService.creditUsercheck(wxCreditHistory.getCUserId());
            wxCreditHistory.setBuserId(getBuser().getId());
            WxCreditHistory credit = wxCreditHistoryService.saveOrUpdate(wxCreditHistory);
            //更新标签
            if (wxCreditHistory.getTags() != null && !wxCreditHistory.getTags().isEmpty()) {
                wxCUserTagsService.updateTagByUserId(wxCreditHistory.getCUserId(), wxCreditHistory.getTags());
            }
            return new ResultData(Result.SUCCESS, "操作成功", credit);
        } catch (MallinkException e) {
            log.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        }
    }

    @ApiOperation("分页列表接口")
    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageNum",value="页数",dataType="int", paramType = "query",required=true),
            @ApiImplicitParam(name="pageSize",value="每页条数",dataType="int", paramType = "query",required=true)})
    public ResultData list(@ModelAttribute WxCreditHistory wxCreditHistory, Integer pageNum, Integer pageSize) {
        log.debug("[" + getIpAddr() + "] WxCreditHistoryController::list");
        if (null == wxCreditHistory) wxCreditHistory = new WxCreditHistory();
        WxMerchantBUser bUser = getUser();
        WxMerchant merchant = wxMerchantService.getById(wxCreditHistory.getMerchantId());
        if (merchant != null && merchant.getIsAdmin() != null && merchant.getIsAdmin() == 1) {
            wxCreditHistory.setOperatorId(bUser.getId());
            wxCreditHistory.setOperatorType(EnumUserType.BUSER.getCode());
            wxCreditHistory.setMerchantId(null);
        }
        final PageInfo<WxCreditHistoryVo> page = wxCreditHistoryService.listAsPageMore(wxCreditHistory, pageNum, pageSize);
        return new ResultData(page);
    }

}
