package com.iformall.controller.market;

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.enums.EnumCouponPasswordStatus;
import com.iformall.enums.EnumCouponStatus;
import com.iformall.enums.EnumCouponValidType;
import com.iformall.exception.MallinkException;
import com.iformall.service.PushLimitService;
import com.iformall.service.WxCouponPasswordService;
import com.iformall.service.WxCouponPresentService;
import com.iformall.service.WxCouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author gongbiao
 */
@RestController
@RequestMapping("couponPresent")
@Api(description = "卡投放接口")
public class WxCouponPresentController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponPresentService wxCouponPresentService;

    @Autowired
    PushLimitService pushLimitService;

    @Autowired
    WxCouponService wxCouponService;

    @Autowired
    WxCouponPasswordService wxCouponPasswordService;

    @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 WxCouponPresent wxCouponPresent, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxCouponPresentController::list");
        wxCouponPresent.setTenantId(getTenantId());
        wxCouponPresent.setSortColumns(BaseEntity.SortField.CreateTime_DESC, BaseEntity.SortField.Id_DESC);
        final PageInfo<WxCouponPresent> page = wxCouponPresentService.listAsPage(wxCouponPresent, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("根据id查询接口")
    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "查询")
    public ResultData findById(@RequestParam Long id) {
        logger.debug("[" + getIpAddr() + "] WxCouponPresentController::findById");
        return new ResultData(wxCouponPresentService.findById(id));
    }


    @ApiOperation("新增接口")
    @PostMapping("add")
    @SystemControllerLog(description = "新增")
    public ResultData add(@RequestBody WxCouponPresent wxCouponPresent) {
        logger.debug("[" + getIpAddr() + "] WxCouponInjectController::add");

        if (wxCouponPresent.getCouponId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "请选择卡");
        }

        if (wxCouponPresent.getPhones().isEmpty()) {
            return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "请填写手机号");
        }
        MallUserInfo user = getUser();
        wxCouponPresent.setUserId(user.getId());
        wxCouponPresent.setTenantId(user.getTenantId());
        try {
            pushLimitService.checkSendTime(user.getTenantId());
        } catch (MallinkException e) {
            logger.error(e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        }
        WxCoupon wxCoupon = wxCouponService.getById(wxCouponPresent.getCouponId());
        if (wxCoupon.getValidType().equals(EnumCouponValidType.BETWEEN_TWO_TIME.getCode())) { //时间范围
            if (new Date().after(wxCoupon.getValidEndDate())) {
                return new ResultData(ErrorCode.COUPON_IS_EXPIRED);
            }
        }
        if (!wxCoupon.getStatus().equals(EnumCouponStatus.COUPON_STATUS_THROW_IN.getCode())) {
            return new ResultData(ErrorCode.COUPON_IS_TAKE_OFF);
        }

        //获取手机号
        String phones = wxCouponPresent.getPhones();
        String[] phoneSplit = phones.split(",");
        Set<String> phoneSet = new HashSet<>(phoneSplit.length);
        for (String phone : phoneSplit) {
            if (!phone.isEmpty()) {
                phoneSet.add(phone);
            }
        }
        //查询有效券数量
        WxCouponPassword wxCouponPassword = new WxCouponPassword();
        wxCouponPassword.setTenantId(user.getTenantId());
        wxCouponPassword.setCouponId(wxCouponPresent.getCouponId());
        wxCouponPassword.setStatus(EnumCouponPasswordStatus.INIT.getCode());
        List<WxCouponPassword> list = wxCouponPasswordService.findList(wxCouponPassword);
        if (phoneSet.size() > list.size()) {
            logger.info(ErrorCode.REMAIN_IS_EMPTY.getMessage());
            return new ResultData(ErrorCode.REMAIN_IS_EMPTY);
        }

        wxCouponPresent.setCouponName(wxCoupon.getTitle());
        wxCouponPresentService.add(wxCouponPresent, list, phoneSet);
        return new ResultData();
    }

}
