package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.po.*;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.vo.WxCouponActionLogVo;
import com.iformall.domain.vo.WxCouponSendVo;
import com.iformall.enums.EnumCouponSendSendType;
import com.iformall.enums.EnumCouponSendStatus;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxCUserMapper;
import com.iformall.service.WxCouponActionLogService;
import com.iformall.service.WxCouponSendService;
import com.iformall.utils.DateUtils;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/couponSend")
@Api(description = "商户注券相关接口")
public class WxCouponSendController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private WxCouponSendService wxCouponSendService;
	@Autowired
	private WxCouponActionLogService wxCouponActionLogService;

	@Resource
	private WxCUserMapper wxCUserMapper;

	@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(WxCouponSend wxCouponSend, Integer pageNum, Integer pageSize) {
		logger.debug("[" + getIpAddr() + "] WxCouponSendController::list");
		if (Objects.isNull(wxCouponSend.getSendType())) {
			return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
		}
		wxCouponSend.setTenantId(getTenantId());
		wxCouponSend.setMerchantId(getUser().getMerchantId());
		if (Objects.nonNull(wxCouponSend.getExpired()) && Objects.equals(wxCouponSend.getExpired(), 0)) {
			wxCouponSend.setMerchantRemain(0);
		}
		wxCouponSend.setStatus(wxCouponSend.getStatus());
		//库存大于0
		if (Objects.isNull(wxCouponSend.getSortColumn())) {
			wxCouponSend.setSortColumns(BaseEntity.SortField.CreateDate_DESC);
		}
		final PageInfo<WxCouponSendVo> page = wxCouponSendService.listAsPage(wxCouponSend, pageNum, pageSize);

		for (WxCouponSendVo cs : page.getList()) {
			cs.setSendCount(wxCouponActionLogService.getCountByChannelId(getTenantId(), cs.getSendType(), cs.getId()));
		}
		return new ResultData(page);
	}

	@ApiOperation("商户注券")
	@PostMapping("/handSel")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "wxCouponSendIds", value = "CouponSend ID数组", dataType = "string", allowMultiple = true, paramType = "query", required = true),
			@ApiImplicitParam(name = "cUserId", value = "用户ID", dataType = "long", paramType = "query", required = true),
	})
	public ResultData handSel(@RequestBody Map<String, Object> params) {
		logger.debug("[" + getIpAddr() + "] WxCouponSendController::handSel");
		if (CollectionUtils.isEmpty(params)) {
			return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
		}

		String cUserId = (String) params.get("cUserId");

		if (!params.containsKey("wxCouponSendIds")) {
			return new ResultData(ErrorCode.COUPON_IS_EMPTY);
		}

		List<String> wxCouponSendIds = (List<String>) params.get("wxCouponSendIds");
		if (CollectionUtils.isEmpty(wxCouponSendIds)) {
			return new ResultData(ErrorCode.COUPON_IS_EMPTY);
		}

		WxCouponSend wxCouponSend = new WxCouponSend();
		wxCouponSend.setIds(wxCouponSendIds.stream().map(Long::parseLong).collect(Collectors.toList()));
		wxCouponSend.setTenantId(getTenantId());
		wxCouponSend.setSendType(EnumCouponSendSendType.MERCHANT.getCode());
		wxCouponSend.setStatus(EnumCouponSendStatus.VALID.getCode());
		try {
			wxCouponSendService.handSel(wxCouponSend, Long.parseLong(cUserId));
		} catch (MallinkException e) {
			logger.error("注券异常: ", e);
			return new ResultData(e.getErrorCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("注券异常: ", e);
			return new ResultData(ErrorCode.COUPON_HANDSEL_VERIFY, e.getMessage());
		}
		return new ResultData();
	}

	@ApiOperation("注券记录")
	@GetMapping("/actionLog")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "channelType", value = "注券类型，商户注券=7", dataType = "int", paramType = "query", required = true),
			@ApiImplicitParam(name = "beginDate", value = "开始日期 yyyy-MM-dd", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "endDate", value = "结束日期 yyyy-MM-dd", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
	})
	public ResultData sendLog(Integer channelType, String beginDate, String endDate, Integer pageNum, Integer pageSize) {
		logger.debug("[" + getIpAddr() + "] WxCouponSendController::actionLog");
		Map<String, Object> params = new HashMap<>();
		if (Objects.nonNull(beginDate)) {
			Date begin = DateUtils.stringToDate(beginDate);
			params.put("beginDate", begin);
		}

		if (Objects.nonNull(endDate)) {
			Date end = DateUtils.stringToDate(endDate);
			Calendar cal = Calendar.getInstance();
			cal.setTime(end);
			cal.add(Calendar.DATE, 1);
			params.put("endDate", cal.getTime());
		}
		params.put("tenantId", getTenantId());
		params.put("channelType", channelType);
		params.put("merchantId", getUser().getMerchantId());
		PageInfo<WxCouponActionLogVo> data = wxCouponActionLogService.getActionLog(params, pageNum, pageSize);
		return new ResultData(data);
	}


}
