package com.xxfc.platform.activity.biz;

import cn.hutool.core.date.DateUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.util.excel.ExcelUtils;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.google.common.collect.Lists;
import com.xxfc.platform.activity.bo.ActivityWinningRecordBo;
import com.xxfc.platform.activity.bo.ActivityWinningRecordTotalVo;
import com.xxfc.platform.activity.constant.PrizeTypeEnum;
import com.xxfc.platform.activity.dto.ActivityWinningRecordFindDTO;
import com.xxfc.platform.activity.dto.ActivityWinningRecordPageDTO;
import com.xxfc.platform.activity.entity.ActivityWinningRecord;
import com.xxfc.platform.activity.mapper.ActivityWinningRecordMapper;
import com.xxfc.platform.activity.vo.ActivityWinningRecordVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 中奖记录
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-12-03 16:46:02
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class ActivityWinningRecordBiz extends BaseBiz<ActivityWinningRecordMapper, ActivityWinningRecord> {

    /**
     * 保存
     *
     * @param activityWinningRecord
     */
    public void saveRecord(ActivityWinningRecord activityWinningRecord) {
        activityWinningRecord.setCrtTime(new Date());
        mapper.insertSelective(activityWinningRecord);
    }


    public ActivityWinningRecordBo listActivityWinningRecordWithPage(ActivityWinningRecordFindDTO activityWinningRecordFindDTO) {
        ActivityWinningRecordBo activityWinningRecordBo = new ActivityWinningRecordBo();
        PageDataVO<ActivityWinningRecordPageDTO> dataVO = PageDataVO.pageInfo(activityWinningRecordFindDTO.getPage(), activityWinningRecordFindDTO.getLimit(),
                () -> mapper.selectActivityWinningRecord(activityWinningRecordFindDTO));
        ActivityWinningRecordTotalVo activityWinningRecordTotalVo = getActivityWinningRecordTotal(activityWinningRecordFindDTO);
        List<ActivityWinningRecordPageDTO> data = dataVO.getData();
        if (CollectionUtils.isEmpty(data)){
            activityWinningRecordBo.setActivityWinningRecordTotalVo(activityWinningRecordTotalVo);
            return activityWinningRecordBo;
        }
        List<ActivityWinningRecordVo> activityWinningRecordVos = new ArrayList<>();
        ActivityWinningRecordVo activityWinningRecordVo = null;

        for (ActivityWinningRecordPageDTO activityWinningRecord : data) {

            activityWinningRecordVo = new ActivityWinningRecordVo();
            BeanUtils.copyProperties(activityWinningRecord,activityWinningRecordVo);
            activityWinningRecordVos.add(activityWinningRecordVo);
        }
        activityWinningRecordBo.setPageNum(dataVO.getPageNum());
        activityWinningRecordBo.setPageSize(dataVO.getPageSize());
        activityWinningRecordBo.setTotalPage(dataVO.getTotalPage());
        activityWinningRecordBo.setTotalCount(dataVO.getTotalCount());
        activityWinningRecordBo.setActivityWinningRecordTotalVo(activityWinningRecordTotalVo);
        activityWinningRecordBo.setActivityWinningRecords(activityWinningRecordVos);
        return activityWinningRecordBo;
    }

    private ActivityWinningRecordTotalVo getActivityWinningRecordTotal(ActivityWinningRecordFindDTO activityWinningRecordFindDTO){
        activityWinningRecordFindDTO.setHasWinning(null);
        ActivityWinningRecordTotalVo activityWinningRecordTotalVo = new ActivityWinningRecordTotalVo();
        List<ActivityWinningRecordPageDTO> activityWinningRecords = mapper.selectActivityWinningRecord(activityWinningRecordFindDTO);
        if (CollectionUtils.isEmpty(activityWinningRecords)){
            return  activityWinningRecordTotalVo;
        }
        AtomicInteger onlineCounter = new AtomicInteger(0);
        AtomicInteger onlineWinCounter= new AtomicInteger(0);
        AtomicInteger localeCounter = new AtomicInteger(0);
        AtomicInteger localeWineCounter = new AtomicInteger(0);
        for (ActivityWinningRecordPageDTO activityWinningRecord : activityWinningRecords) {
            if (activityWinningRecord.getPrizeType()==1){
                onlineCounter.incrementAndGet();
                if (activityWinningRecord.getHasWinning()==1){
                    onlineWinCounter.incrementAndGet();
                }
            }
            if (activityWinningRecord.getPrizeType()==2){
                localeCounter.incrementAndGet();
                if (activityWinningRecord.getHasWinning()==1){
                    localeWineCounter.incrementAndGet();
                }
            }
        }
        activityWinningRecordTotalVo.setOnLineNum(onlineCounter.get());
        activityWinningRecordTotalVo.setOnLineWineNum(onlineWinCounter.get());
        activityWinningRecordTotalVo.setLocaleNum(localeCounter.get());
        activityWinningRecordTotalVo.setLocaleWineNum(localeWineCounter.get());
        return activityWinningRecordTotalVo;
    }

    public void exportActivityWinngingData(ActivityWinningRecordFindDTO activityWinningRecordFindDTO, ServletOutputStream outputStream) throws IOException {
        ExcelUtils excelUtils = new ExcelUtils("中奖列表");
        XSSFWorkbook hssfWorkbook = excelUtils.getHssfWorkbook();
        XSSFSheet sheet = excelUtils.getSheet();
        List<ActivityWinningRecordPageDTO> activityWinningRecordPageDTOS = mapper.selectActivityWinningRecord(activityWinningRecordFindDTO);
        ActivityWinningRecordTotalVo activityWinningRecordTotal = getActivityWinningRecordTotal(activityWinningRecordFindDTO);

        String[] header1 = {"线上抽奖触发数","线上中奖个数","现场上抽奖触发数","现场中奖个数"};
        Row headerRow1 = sheet.createRow(0);
        CellStyle headerCellStyle = excelUtils.createHeaderCellStyle();
        excelUtils.createHeader(headerRow1,0,header1,headerCellStyle);

        String[] headerValue = {activityWinningRecordTotal.getOnLineNum()+"",activityWinningRecordTotal.getOnLineWineNum()+"",activityWinningRecordTotal.getLocaleNum()+"",activityWinningRecordTotal.getLocaleWineNum()+""};
        CellStyle generalCellStyle = excelUtils.createGeneralCellStyle();
        ArrayList<String[]> headerData = Lists.newArrayList();
        headerData.add(headerValue);
        excelUtils.createCellData(sheet,1,generalCellStyle,headerData);

        CellRangeAddress cellRangeAddress = new CellRangeAddress(2, 2, 0, 6);
        sheet.addMergedRegion(cellRangeAddress);

        String[] header2 = {"用户名","电话","身份","发放类型","抽奖礼品","兑奖码","中奖时间"};
        Row header2Row = sheet.createRow(3);
        excelUtils.createHeader(header2Row,0,header2,headerCellStyle);

        List<String[]> activityWinngingDataList = getActivityWinngingDataList(activityWinningRecordPageDTOS);
        excelUtils.createCellData(sheet,4,generalCellStyle,activityWinngingDataList);

        hssfWorkbook.write(outputStream);
        hssfWorkbook.close();
    }

    private List<String[]> getActivityWinngingDataList(List<ActivityWinningRecordPageDTO> activityWinningRecordDTOS){
         List<String[]> activityWinngingDataList = new ArrayList<>();
        for (ActivityWinningRecordPageDTO activityWinningRecordDTO : activityWinningRecordDTOS) {
            String[] activityWinngingData = getActivityWinngingData(activityWinningRecordDTO);
            activityWinngingDataList.add(activityWinngingData);
        }
        return activityWinngingDataList;
    }

    private String[] getActivityWinngingData(ActivityWinningRecordPageDTO activityWinningRecordPageDTO){
        String prizeType= activityWinningRecordPageDTO.getPrizeType()== PrizeTypeEnum.ONLINE.getCode()?"线上":"现场";
        String expiryDateCode = StringUtils.hasText(activityWinningRecordPageDTO.getExpiryDateCode())?activityWinningRecordPageDTO.getExpiryDateCode():"无";
        String timeStr = DateUtil.format(activityWinningRecordPageDTO.getLotteryTime(),"yyyy-MM-dd HH:mm:ss");
        return new String[]{activityWinningRecordPageDTO.getUserName(),activityWinningRecordPageDTO.getPhone(),
                activityWinningRecordPageDTO.getPositionName(),prizeType,activityWinningRecordPageDTO.getPrizeName(),
                expiryDateCode,timeStr};
    }

    public ActivityWinningRecordVo findActivityAttendanceRecordById(Long id) {
        ActivityWinningRecordVo activityWinningRecordVo = new ActivityWinningRecordVo();
        ActivityWinningRecord activityAttendanceRecord = mapper.selectByPrimaryKey(id);
        Optional.ofNullable(activityAttendanceRecord).ifPresent(x->BeanUtils.copyProperties(x,activityWinningRecordVo));
        return activityWinningRecordVo;
    }
}