package com.qs.mp.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qs.mp.admin.domain.Ticket;
import com.qs.mp.admin.domain.excel.TicketExcel;
import com.qs.mp.admin.domain.vo.TicketCntVO;
import com.qs.mp.admin.mapper.TicketMapper;
import com.qs.mp.admin.service.ITicketService;
import com.qs.mp.channel.domain.ChannelOrderDetail;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.utils.RSAUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 盲票 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-03-08
 */
@Service
public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket> implements ITicketService {

	@Autowired
	private ITicketService ticketService;

	@Value("${export.page-size}")
	private int pageSize;

	@Override
	public Ticket getRandOne(String boxId) {
		return getBaseMapper().getRandOne(boxId, 1);
	}

	@Override
	@Transactional
	public int importTicket(List<TicketExcel> ticketExcelList) {
		if (null != ticketExcelList && ticketExcelList.size() > 0) {
			List<Ticket> ticketList = new ArrayList<Ticket>();
			for (TicketExcel ticketExcel : ticketExcelList) {
				if(null != ticketExcel && StringUtils.isNotBlank(ticketExcel.getSerialNo())) {
					LambdaQueryWrapper<Ticket> ticketQueryWrapper = new LambdaQueryWrapper<Ticket>();
					ticketQueryWrapper.eq(Ticket::getSerialNo, ticketExcel.getSerialNo());
					Ticket ticket = ticketService.getOne(ticketQueryWrapper);
					if(null != ticket && StringUtils.isNotBlank(ticket.getTicketId())) {
						Ticket updateTicket = new Ticket();
						updateTicket.setTicketId(ticket.getTicketId());
						updateTicket.setCipherLuckyNum(RSAUtil.encrypt(ticketExcel.getCipherLuckyNum()));
						updateTicket.setDrawNum(ticketExcel.getDrawNum());
						ticketList.add(updateTicket);
					}
				}
			}
			if(null != ticketList && ticketList.size() > 0) {
				boolean res = ticketService.updateBatchById(ticketList,pageSize);
				if(!res) {
					throw new ServiceException("盲票导入失败，请联系管理员");
				}
				return ticketList.size();
			}
		}

		return 0;
	}

	@Override
	public List<Ticket> listTicket(Wrapper<Ticket> queryWrapper) {
		return getBaseMapper().listTicket(queryWrapper);
	}

	@Override
	public int getTicketQtyCnt(Long channelId) {
		return getBaseMapper().getTicketQtyCnt(channelId);
	}

	@Override
	public List<TicketCntVO> listTicketQtyCnt(Wrapper<ChannelOrderDetail> queryWrapper) {
		return getBaseMapper().listTicketQtyCnt(queryWrapper);
	}
	
}
