package com.iformall.controller.mem;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.*;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.vo.WxCouponChannelVo;
import com.iformall.enums.EnumCouponChannelStatus;
import com.iformall.enums.EnumCouponChannelType;
import com.iformall.service.*;
import io.swagger.annotations.Api;
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 java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("memCoupon")
@Api(description = "会员券相关接口")
public class MemCouponController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponChannelService couponChannelService;

    @Autowired
    private MemCouponFromDspService memCouponFromDspService;

    @Autowired
    private WxCouponService couponService;

    @ApiOperation("已投放券列表接口")
    @GetMapping("couponChannelList")
    @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 couponChannelList(Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] MemCouponController::list");
        WxCouponChannel wxCouponChannel = new WxCouponChannel();
        if (null == wxCouponChannel) {
            wxCouponChannel = new WxCouponChannel();
        }
        wxCouponChannel.updateTenantInfo(getTenantInfo());
        wxCouponChannel.setTargetAd(EnumCouponChannelType.COUPON_CHANNEL_ID_H5.getCode());
        wxCouponChannel.setStatus(EnumCouponChannelStatus.STATUS_THROW_IN.getCode());
        wxCouponChannel.setSortColumns(BaseEntity.SortField.UpdateDate_DESC);
        final PageInfo<WxCouponChannelVo> page = couponChannelService.listPageCVo(wxCouponChannel, pageNum, pageSize);
        return new ResultData(page);
    }

    @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 MemCouponFromDsp memCouponFromDsp, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] MemCouponController::list");
        if (null == memCouponFromDsp) {
            memCouponFromDsp = new MemCouponFromDsp();
        } else {
            if (StringUtils.isBlank(memCouponFromDsp.getPhone())) {
                memCouponFromDsp.setPhone(null);
            }
        }
        memCouponFromDsp.updateTenantInfo(getTenantInfo());
        memCouponFromDsp.setSortColumns(BaseEntity.SortField.CreateDate_DESC);
        PageInfo<MemCouponFromDsp> page = memCouponFromDspService.listAsPage(memCouponFromDsp, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("检查用户购买券是否可用")
    @PostMapping("checkMemCoupon")
    @SystemControllerLog(description = "会员券管理-检查")
    public ResultData checkMemCoupon(@RequestBody MemCouponFromDsp memCouponFromDsp) {
        logger.debug("[" + getIpAddr() + "] MemCouponController::add");
        if (StringUtils.isBlank(memCouponFromDsp.getPhone())) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "phone必填");
        }
        if (memCouponFromDsp.getCouponChannelId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId必填");
        }
        memCouponFromDsp.updateTenantInfo(getTenantInfo());
        WxCouponChannel couponChannel = couponChannelService.getById(memCouponFromDsp.getCouponChannelId());
        if (memCouponFromDsp.getCouponId() == null) {
            memCouponFromDsp.setCouponId(couponChannel.getCouponId());
        }
        // 1. 检查券是否已超限, 无剩余库存
        WxCoupon coupon = couponService.getById(memCouponFromDsp.getCouponId());
        if (coupon == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "券不存在:" + memCouponFromDsp.getCouponId());
        }
        MemCouponFromDsp couponQ = new MemCouponFromDsp() {{
            updateTenantInfo(memCouponFromDsp);
            setCouponId(memCouponFromDsp.getCouponId());
            setStatus(0);
        }};
        Integer couponCount = memCouponFromDspService.countByInfo(couponQ);
        if (coupon.getRemainInventory() <= couponCount) {
            return new ResultData(ErrorCode.REMAIN_IS_EMPTY);
        }
        // 2. 检查此会员是否已超限, 达到券购买限制
        couponQ = new MemCouponFromDsp() {{
            updateTenantInfo(memCouponFromDsp);
            setPhone(memCouponFromDsp.getPhone());
            setCouponId(memCouponFromDsp.getCouponId());
        }};
        couponCount = memCouponFromDspService.countByInfo(couponQ);
        if (coupon.getUseLimitQuantity() <= couponCount) {
            return new ResultData(ErrorCode.ORDER_IS_LIMITED);
        }
        return new ResultData();
    }

    @ApiOperation("根据id更新接口")
    @PostMapping("add")
    @SystemControllerLog(description = "会员券管理-添加")
    public ResultData add(@RequestBody MemCouponFromDsp memCouponFromDsp) {
        logger.debug("[" + getIpAddr() + "] MemCouponController::add");
        if (StringUtils.isBlank(memCouponFromDsp.getPhone())) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "phone必填");
        }
        if (memCouponFromDsp.getCouponChannelId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId必填");
        }
        memCouponFromDsp.updateTenantInfo(getTenantInfo());
        WxCouponChannel couponChannel = couponChannelService.getById(memCouponFromDsp.getCouponChannelId());
        if (memCouponFromDsp.getCouponId() == null) {
            memCouponFromDsp.setCouponId(couponChannel.getCouponId());
        }
        // 1. 检查券是否已超限, 无剩余库存
        WxCoupon coupon = couponService.getById(memCouponFromDsp.getCouponId());
        if (coupon == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "券不存在:" + memCouponFromDsp.getCouponId());
        }
        MemCouponFromDsp couponQ = new MemCouponFromDsp() {{
            updateTenantInfo(memCouponFromDsp);
            setCouponId(memCouponFromDsp.getCouponId());
            setStatus(0);
        }};
        Integer couponCount = memCouponFromDspService.countByInfo(couponQ);
        if (coupon.getRemainInventory() <= couponCount) {
            return new ResultData(ErrorCode.REMAIN_IS_EMPTY);
        }
        // 2. 检查此会员是否已超限, 达到券购买限制
        couponQ = new MemCouponFromDsp() {{
            updateTenantInfo(memCouponFromDsp);
            setPhone(memCouponFromDsp.getPhone());
            setCouponId(memCouponFromDsp.getCouponId());
        }};
        couponCount = memCouponFromDspService.countByInfo(couponQ);
        if (coupon.getUseLimitQuantity() <= couponCount) {
            return new ResultData(ErrorCode.ORDER_IS_LIMITED);
        }
        // 3. 保存
        memCouponFromDsp.setStatus(0);
        memCouponFromDspService.saveOrUpdate(memCouponFromDsp);
        return new ResultData();
    }

    @ApiOperation("根据手机号查询接口")
    @GetMapping("/findByPhone")
    @ApiImplicitParam(name = "phone", value = "phone", dataType = "String", paramType = "query", required = true)
    @SystemControllerLog(description = "会员券管理-根据手机号查询接口")
    public ResultData findByPhone(String phone) {
        logger.debug("[" + getIpAddr() + "] MemCouponController::findByPhone");
        if (StringUtils.isEmpty(phone)) {
            return new ResultData(new ArrayList<MemCouponFromDsp>());
        }
        MemCouponFromDsp memQ = new MemCouponFromDsp() {{
            updateTenantInfo(getTenantInfo());
            setPhone(phone);
        }};
        List<MemCouponFromDsp> memCouponFromDsps = memCouponFromDspService.getList(memQ);
        return new ResultData(memCouponFromDsps);
    }
}