package com.qs.mp.web.controller.api.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.admin.domain.Coupon;
import com.qs.mp.admin.domain.CouponChannel;
import com.qs.mp.admin.domain.CouponTicket;
import com.qs.mp.admin.domain.Goods;
import com.qs.mp.admin.domain.GoodsSku;
import com.qs.mp.admin.domain.TicketBox;
import com.qs.mp.admin.domain.param.CouponParam;
import com.qs.mp.admin.domain.param.GoodsParam;
import com.qs.mp.admin.domain.vo.CouponVO;
import com.qs.mp.admin.domain.vo.GoodsVO;
import com.qs.mp.admin.service.ICouponChannelService;
import com.qs.mp.admin.service.ICouponService;
import com.qs.mp.admin.service.ICouponTicketService;
import com.qs.mp.admin.service.ITicketBoxService;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.annotation.Log;
import com.qs.mp.common.constant.Constants;
import com.qs.mp.common.constant.UserConstants;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.BusinessType;
import com.qs.mp.common.enums.CouponStatusEnum;
import com.qs.mp.common.enums.CouponUseAreaEnum;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import ma.glasnost.orika.MapperFacade;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther liugl
 * @create 2022-03-09 23:45:48
 * @describe 代金券管理前端控制器
 */
@Api(tags = "代金券管理API")
@RestController
@RequestMapping("/api/v1/mp/admin/coupon/*")
public class CouponMgrController extends BaseApiController {

	@Autowired
	private ICouponService couponService;

	@Autowired
	private ICouponTicketService couponTicketService;

	@Autowired
	private ITicketBoxService ticketBoxService;

	@Autowired
	private ICouponChannelService couponChannelService;

	@Autowired
	private IChannelService channelService;

	@Autowired
	private ISysUserService userService;

	@Autowired
	private MapperFacade mapperFacade;

	/**
	 * 获取代金券列表信息，支持翻页
	 *
	 * @return
	 */
	@PostMapping("/list")
	@PreAuthorize("@ss.hasPermi('business:coupon:list')")
	@ApiOperation("获取代金券列表信息，支持翻页")
	@ApiResponses(
			@ApiResponse(code = 200, message = "成功", response = Coupon.class)
	)
	public TableDataInfo listCoupon(@RequestBody CouponParam coupon) {
		List<Coupon> list = new ArrayList<Coupon>();
		startPage();
		QueryWrapper<Coupon> queryWrapper = new QueryWrapper<Coupon>();
		queryWrapper.lambda().like(null != coupon && StringUtils.isNotBlank(coupon.getTitle()), Coupon::getTitle, coupon.getTitle());
		queryWrapper.lambda().eq(null != coupon && null != coupon.getStatus(), Coupon::getStatus, coupon.getStatus());
		queryWrapper.lambda().eq(null != coupon && null != coupon.getType(), Coupon::getType, coupon.getType());
		queryWrapper.lambda().notIn(null != coupon && !CollectionUtils.isEmpty(coupon.getExcludeCouponIds()), Coupon::getCouponId, coupon.getExcludeCouponIds());
		queryWrapper.lambda().eq(Coupon::getIsDeleted, 0);
		queryWrapper.orderByAsc("FIELD(`status`, 'init', 'on', 'off')");
		queryWrapper.lambda().orderByDesc(Coupon::getCouponId);
		list = couponService.list(queryWrapper);
		return getDataTable(list);
	}


	/**
	 * 获取代金券详情信息
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "/detail")
	@PreAuthorize("@ss.hasPermi('business:coupon:query')")
	@ApiOperation("获取代金券详情信息")
	@ApiResponses(
			@ApiResponse(code = 200, message = "操作成功", response = CouponVO.class)
	)
	public AjaxResult getCouponDetail(@RequestBody JSONObject jsonObject) {
		String couponId = jsonObject.getString("couponId");
		if (StringUtils.isBlank(couponId)){
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Coupon coupon = couponService.getById(Long.valueOf(couponId));
		if(null == coupon) {
			 return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		CouponVO couponVO = new CouponVO();
		BeanUtils.copyProperties(coupon, couponVO);
		List<TicketBox> ticketBoxList = new ArrayList<>();
		// 查询盲票限制列表
		List<CouponTicket> ticketList = new ArrayList<>();
		LambdaQueryWrapper<CouponTicket> ticketQueryWrapper = new LambdaQueryWrapper<>();
		ticketQueryWrapper.eq(CouponTicket::getCouponId, coupon.getCouponId());
		ticketQueryWrapper.orderByDesc(CouponTicket::getCreatedTime);
		ticketList = couponTicketService.list(ticketQueryWrapper);
		if(null != ticketList && ticketList.size() > 0) {
			List<String> boxIdList = ticketList.stream().map(CouponTicket::getBoxId).collect(Collectors.toList());
			if(null != boxIdList && boxIdList.size() > 0) {
				LambdaQueryWrapper<TicketBox> ticketBoxQueryWrapper = new LambdaQueryWrapper<>();
				ticketBoxQueryWrapper.in(TicketBox::getBoxId, boxIdList);
				ticketBoxQueryWrapper.orderByDesc(TicketBox::getCreatedTime);
				ticketBoxList = ticketBoxService.list(ticketBoxQueryWrapper);
				couponVO.setTicketBoxList(ticketBoxList);
			}
		}
		// 查询门店限制列表
		List<Channel> channelList = new ArrayList<>();
		List<CouponChannel> couponChannelList = new ArrayList<>();
		LambdaQueryWrapper<CouponChannel> couponChanneQueryWrapper = new LambdaQueryWrapper<>();
		couponChanneQueryWrapper.eq(CouponChannel::getCouponId, coupon.getCouponId());
		couponChanneQueryWrapper.orderByDesc(CouponChannel::getCreatedTime);
		couponChannelList = couponChannelService.list(couponChanneQueryWrapper);
		if(null != couponChannelList && couponChannelList.size() > 0) {
			List<Long> channelIdList = couponChannelList.stream().map(CouponChannel::getChannelId).collect(Collectors.toList());
			if(null != channelIdList && channelIdList.size() > 0) {
				LambdaQueryWrapper<Channel> channelQueryWrapper = new LambdaQueryWrapper<>();
				channelQueryWrapper.in(Channel::getChannelId, channelIdList);
				channelQueryWrapper.orderByDesc(Channel::getCreatedTime);
				channelList = channelService.list(channelQueryWrapper);
				couponVO.setChannelList(channelList);
			}
		}
		return AjaxResult.success(couponVO);
	}


	public static void main(String[] args) {
		String boxIds = "964952657896800257,979749771218649117,986362095543124033,986361444503257092,984109134842560513";
		String[] boxIdArray = boxIds.split(",");
		for (int i = 0; i < boxIdArray.length; i++) {
			String boxId = boxIdArray[i];
			System.out.println("boxId = " + boxId);
		}

	}

	/**
	 * 新增优惠券信息
	 * @param
	 * @return
	 */
	@Log(title = "新增优惠券", businessType = BusinessType.INSERT)
	@ApiOperation(value = "新增优惠券信息", notes = "新增优惠券")
	@PostMapping("/create")
	@PreAuthorize("@ss.hasPermi('business:coupon:add')")
	public AjaxResult couponCreate(@Validated @RequestBody CouponParam couponParam) {
		if (StringUtils.isNotBlank(couponParam.getCouponId())) {
			return AjaxResult.error("该代金券已存在");
		}
		Coupon coupon = mapperFacade.map(couponParam, Coupon.class);
		// 1、校验名称是否重复（代金券表）
		LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Coupon::getTitle, coupon.getTitle());
		queryWrapper.eq(Coupon::getIsDeleted, 0);
		int nameCount = couponService.count(queryWrapper);
		if(nameCount > 0) {
			return AjaxResult.error("代金券名称" + coupon.getTitle() + "已存在！");
		}
		// 使用范围
		List<CouponTicket> ticketList = new ArrayList<>();
		if(StringUtils.isNotBlank(couponParam.getBoxIds())) {
			String[] boxIdArray = couponParam.getBoxIds().split(",");
	        for (int i = 0; i < boxIdArray.length; i++) {
	        	String boxId = boxIdArray[i];
	        	CouponTicket couponTicket = new CouponTicket();
	        	couponTicket.setBoxId(boxId);
	        	ticketList.add(couponTicket);
	        }
		}
//		if(coupon.getUseArea() != CouponUseAreaEnum.COMMON
//				&& ticketList.size() == 0) {
//			return AjaxResult.error("使用范围为指定盲票时需要至少选择一种盲票");
//		}
		if(StringUtils.isBlank(coupon.getPicUrl())) {
			coupon.setPicUrl(Constants.COUPON_PIC);
		}
		// 3.插入数据
		try {
			couponService.saveCoupon(coupon,ticketList);
		} catch (Exception e) {
			return AjaxResult.error("代金券'" + coupon.getTitle() + "'新增失败" + e.getMessage());
		}

		return AjaxResult.success("代金券'" + coupon.getTitle() + "'新增成功");
	}

	/**
	 * 编辑代金券信息
	 * @param
	 * @return
	 */
	@Log(title = "修改优惠券", businessType = BusinessType.UPDATE)
	@ApiOperation(value = "编辑代金券信息", notes = "代金券端编辑代金券")
	@PostMapping("/update")
	@PreAuthorize("@ss.hasPermi('business:coupon:edit')")
	public AjaxResult couponUpdate(@Validated @RequestBody CouponParam couponParam) {
		if (null == couponParam || StringUtils.isBlank(couponParam.getCouponId())) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		Coupon coupon = mapperFacade.map(couponParam, Coupon.class);
		// 1、校验修改代金券是否为当前用户的代金券
		Coupon oldCoupon = couponService.getById(coupon.getCouponId());
		if(null == oldCoupon || null == oldCoupon.getCouponId()) {
			return AjaxResult.error("代金券'" + oldCoupon.getTitle() + "'编辑失败，代金券ID异常");
		}
		// 2.校验名称是否重复（代金券表）；
		if(!coupon.getTitle().equals(oldCoupon.getTitle())) {
			LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(Coupon::getTitle, coupon.getTitle());
			queryWrapper.eq(Coupon::getIsDeleted, 0);
			int nameCount = couponService.count(queryWrapper);
			if(nameCount > 0) {
				return AjaxResult.error("代金券名称" + coupon.getTitle() + "已存在！");
			}
		}
		// 使用范围
		List<CouponTicket> ticketList = new ArrayList<>();
		if(StringUtils.isNotBlank(couponParam.getBoxIds())) {
			String[] boxIdArray = couponParam.getBoxIds().split(",");
	        for (int i = 0; i < boxIdArray.length; i++) {
	        	String boxId = boxIdArray[i];
	        	CouponTicket couponTicket = new CouponTicket();
	        	couponTicket.setBoxId(boxId);
	        	couponTicket.setCouponId(coupon.getCouponId());
				ticketList.add(couponTicket);
	        }
		}
		try {
			couponService.updateCoupon(coupon, ticketList);
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success("代金券'" + coupon.getTitle() + "'编辑成功");
	}


	/**
	 * 上下架优惠券
	 * @param
	 * @return
	 */
	@Log(title = "上下架优惠券", businessType = BusinessType.UPDATE)
	@PreAuthorize("@ss.hasPermi('business:coupon:on')")
	@ApiOperation(value = "上下架优惠券信息", notes = "优惠券管理编辑代金券")
	@PostMapping("/status")
	public AjaxResult couponStatus(@RequestBody JSONObject jsonObject) {
		String couponId = jsonObject.getString("couponId");
		String status = jsonObject.getString("status");
		if (StringUtils.isBlank(couponId) || StringUtils.isBlank(status)) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		try {
			couponService.lambdaUpdate().set(Coupon::getStatus, CouponStatusEnum.PUT_ON.getValue().equals(status)?CouponStatusEnum.PUT_ON:CouponStatusEnum.PUT_OFF).eq(Coupon::getCouponId, Long.valueOf(couponId)).update();
			// 查询代金券信息
		} catch (Exception e) {
			return AjaxResult.error("操作失败");
		}
		return AjaxResult.success("操作成功");
	}


	/**
	 * 删除代金券商品(假删)
	 *
	 * @param
	 * @return
	 */
	@Log(title = "删除优惠券", businessType = BusinessType.DELETE)
	@PostMapping(value = "/remove")
	@PreAuthorize("@ss.hasPermi('business:coupon:remove')")
	public AjaxResult removeCoupon(@RequestBody JSONObject jsonObject) {
		String couponId = jsonObject.getString("couponId");
	    if (StringUtils.isBlank(couponId)){
	      return error(ErrorCodeEnum.ERROR_CODE_1001);
	    }
	    Coupon coupon = couponService.getById(Long.valueOf(couponId));
		if(null == coupon) {
			 return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		// 商品未下架， 不允许删除
		if(coupon.getStatus().equals("on")) {
			return AjaxResult.error("代金券未下架，不允许删除");
		}
		LambdaUpdateWrapper<Coupon> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.set(Coupon::getIsDeleted, 1);
		updateWrapper.eq(Coupon::getCouponId, coupon.getCouponId());
		boolean res = couponService.update(updateWrapper);
		if(!res) {
			return AjaxResult.error("代金券删除失败");
		}
		return AjaxResult.success("代金券删除成功");
	}

}
