package com.xxfc.platform.order.biz;

import cn.hutool.core.date.DateUtil;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.order.bo.CompanyPerformanceBo;
import com.xxfc.platform.order.contant.enumerate.ReceivedStatisticsEnum;
import com.xxfc.platform.order.entity.OrderReceivedStatistics;
import com.xxfc.platform.order.pojo.dto.CompanyPerformanceFindDTO;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/11/23 14:48
 */
@Transactional(rollbackFor = Exception.class)
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CompanyPerformanceBiz {

    private final OrderReceivedStatisticsBiz orderReceivedStatisticsBiz;
    private final VehicleFeign vehicleFeign;

    /**
     * 导出数据
     *
     * @param companyPerformanceFindDTO
     * @param outputStream
     */
    public void exportOrderReceivedStatisticsData(CompanyPerformanceFindDTO companyPerformanceFindDTO, ServletOutputStream outputStream) throws IOException {
        companyPerformanceFindDTO.setPage(null);
        companyPerformanceFindDTO.setLimit(null);
        //1.查询数据
        List<CompanyPerformanceBo> companyPerformanceBos = selectCompanyPerformances(companyPerformanceFindDTO);

        //excel相关
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook();
        XSSFSheet sheet = hssfWorkbook.createSheet("公司业绩统计报表");
        Row headerRow = sheet.createRow(0);
        CellStyle headerCellStyle = createHeaderCellStyle(hssfWorkbook);
        String[] headerValue = {"时间", "公司", "会员费", "租车费","押金","不计免赔费", "旅游费", "租借天数", "出车服务次数", "收车服务次数"};
        createHeader(headerRow, 0, headerValue, headerCellStyle);
        for (int i = 0; i < headerValue.length; i++) {
            sheet.setColumnWidth(i, 24 * 256);
        }
        //设置数据
        CellStyle generalCellStyle = createGeneralCellStyle(hssfWorkbook);
        List<String[]> companyStatisticsData = getCompanyStatisticsData(companyPerformanceBos, companyPerformanceFindDTO.getStatisticalWay());
        createCompnayStatisticsCellData(sheet, 1, generalCellStyle, companyStatisticsData);
        hssfWorkbook.write(outputStream);
        hssfWorkbook.close();

    }

    private void createCompnayStatisticsCellData(Sheet sheet, int startRowIndex, CellStyle cellStyle, List<String[]> staffStatisticsData) {
        for (String[] data : staffStatisticsData) {
            Row row = sheet.createRow(startRowIndex++);
            createCellCount(row, 0, data, cellStyle);
        }
    }

    private void createCellCount(Row row, int CellStartIndex, String[] data, CellStyle cellStyle) {
        for (int i = CellStartIndex, y = 0; y < data.length; i++, y++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(data[y]);

        }
    }

    private List<String[]> getCompanyStatisticsData(List<CompanyPerformanceBo> companyPerformanceBos, Integer statisticalWay) {
        List<String[]> data = new ArrayList<>(companyPerformanceBos.size());
        for (int i = 0; i < companyPerformanceBos.size(); i++) {
            String[] companyData = getData(companyPerformanceBos.get(i), statisticalWay);
            data.add(companyData);
        }
        return data;
    }

    private String[] getData(CompanyPerformanceBo companyPerformanceBo, Integer statisticalWay) {
        String dateStr = "";
        if (statisticalWay == ReceivedStatisticsEnum.DAY.getWayCode()) {
          dateStr = companyPerformanceBo.getDateStr();
        }
        if (statisticalWay == ReceivedStatisticsEnum.WEEK.getWayCode()) {
            dateStr=String.format("%s~%s",companyPerformanceBo.getStartDate(),companyPerformanceBo.getEndDate());
        }
        if (statisticalWay == ReceivedStatisticsEnum.MONTH.getWayCode()) {
          dateStr = companyPerformanceBo.getMonth();
        }
        return new String[]{
                dateStr,
                companyPerformanceBo.getCompanyName(),
                companyPerformanceBo.getMemberAmount().toString(),
                companyPerformanceBo.getRentVehilceAmount().toString(),
                companyPerformanceBo.getDepositAmount().toString(),
                companyPerformanceBo.getNoDeductibleAmount().toString(),
                companyPerformanceBo.getTravelAmount().toString(),
                String.valueOf(companyPerformanceBo.getRentDays()),
                String.valueOf(companyPerformanceBo.getDepartureNum()),
                String.valueOf(companyPerformanceBo.getArrivalNum())};
    }

    private void createHeader(Row row, int cellStartIndex, String[] header, CellStyle cellStyle) {
        for (int i = 0; i < header.length; i++) {
            Cell cell = row.createCell(cellStartIndex);
            cell.setCellValue(header[i]);
            cell.setCellStyle(cellStyle);
            cellStartIndex += 1;
        }
    }

    private CellStyle createGeneralCellStyle(XSSFWorkbook hssfWorkbook) {
        CellStyle cellStyleGeneral = createHeaderCellStyle(hssfWorkbook);
        cellStyleGeneral.setWrapText(true);
        XSSFFont generalFont = createFont(hssfWorkbook);
        generalFont.setBold(false);
        cellStyleGeneral.setFont(generalFont);
        return cellStyleGeneral;
    }

    private CellStyle createHeaderCellStyle(XSSFWorkbook hssfWorkbook) {
        XSSFCellStyle cellStyleHeader = hssfWorkbook.createCellStyle();
        cellStyleHeader.setAlignment(HorizontalAlignment.CENTER);
        cellStyleHeader.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyleHeader.setLocked(false);
        XSSFFont headerFont = createFont(hssfWorkbook);
        cellStyleHeader.setFont(headerFont);
        return cellStyleHeader;
    }

    private XSSFFont createFont(XSSFWorkbook hssfWorkbook) {
        XSSFFont font = hssfWorkbook.createFont();
        font.setFontName("黑体");
        font.setBold(true);
        return font;
    }

    public List<CompanyPerformanceBo> selectCompanyPerformances(CompanyPerformanceFindDTO companyPerformanceFindDTO){
        Map<Integer, String> companyMap = vehicleFeign.findCompanyMap();
        List<CompanyPerformanceBo> companyPerformanceBos = new ArrayList<>();
        //日统计
        if (companyPerformanceFindDTO.getStatisticalWay() == ReceivedStatisticsEnum.DAY.getWayCode()) {
            companyPerformanceBos = orderReceivedStatisticsBiz.selectCompanyPerformanceWithDay(companyPerformanceFindDTO);
        }

        //按周
        if (companyPerformanceFindDTO.getStatisticalWay() == ReceivedStatisticsEnum.WEEK.getWayCode()) {
            companyPerformanceBos = orderReceivedStatisticsBiz.selectCompanyPerformanceWithWeek(companyPerformanceFindDTO);
        }
        //按月
        if (companyPerformanceFindDTO.getStatisticalWay() == ReceivedStatisticsEnum.MONTH.getWayCode()) {
            companyPerformanceBos = orderReceivedStatisticsBiz.selectCompanyPerformanceWithMonth(companyPerformanceFindDTO);

        }
        if (CollectionUtils.isEmpty(companyPerformanceBos)) {
            return companyPerformanceBos;
        }
        companyPerformanceBos = wrapCompanyPermanceBo(companyPerformanceBos, companyMap, companyPerformanceFindDTO.getStatisticalWay());

        return companyPerformanceBos;
    }


    /**
     * 分页查询公司业绩
     *
     * @param companyPerformanceFindDTO
     * @return
     */
    public PageDataVO<CompanyPerformanceBo> selectCompanyPerformancePage(CompanyPerformanceFindDTO companyPerformanceFindDTO) {

        Map<Integer, String> companyMap = vehicleFeign.findCompanyMap();
        PageDataVO<CompanyPerformanceBo> pageDataVO = new PageDataVO<>();
        //日统计
        if (companyPerformanceFindDTO.getStatisticalWay() == ReceivedStatisticsEnum.DAY.getWayCode()) {
            pageDataVO = orderReceivedStatisticsBiz.selectCompanyPerformanceWithDayPage(companyPerformanceFindDTO);
        }

        //按周
        if (companyPerformanceFindDTO.getStatisticalWay() == ReceivedStatisticsEnum.WEEK.getWayCode()) {
            pageDataVO = orderReceivedStatisticsBiz.selectCompanyPerformanceWithWeekPage(companyPerformanceFindDTO);
        }
        //按月
        if (companyPerformanceFindDTO.getStatisticalWay() == ReceivedStatisticsEnum.MONTH.getWayCode()) {
            pageDataVO = orderReceivedStatisticsBiz.selectCompanyPerformanceWithMonthPage(companyPerformanceFindDTO);

        }
        List<CompanyPerformanceBo> data = pageDataVO.getData();
        if (CollectionUtils.isEmpty(data)) {
            return pageDataVO;
        }
        List<CompanyPerformanceBo> companyPerformanceBos = wrapCompanyPermanceBo(data, companyMap, companyPerformanceFindDTO.getStatisticalWay());
        pageDataVO.setData(companyPerformanceBos);

        if (companyPerformanceFindDTO.getPage() == 1) {
            int totalCount = orderReceivedStatisticsBiz.selectCountByCondition(companyPerformanceFindDTO);
            long isZero = totalCount % companyPerformanceFindDTO.getLimit();
            long totalPage = isZero == 0 ? totalCount / companyPerformanceFindDTO.getLimit() : totalCount / companyPerformanceFindDTO.getLimit() + 1;
            pageDataVO.setTotalCount(Long.valueOf(totalCount));
            pageDataVO.setTotalPage(Integer.valueOf(String.valueOf(totalPage)));
        }
        return pageDataVO;
    }

    public List<CompanyPerformanceBo> wrapCompanyPermanceBo(List<CompanyPerformanceBo> companyPerformanceBos,Map<Integer,String> companyMap,Integer statisticsWay){
        for (CompanyPerformanceBo companyPerformanceBo : companyPerformanceBos) {
            String companyName = companyMap == null ? "" : companyMap.get(companyPerformanceBo.getCompanyId());
            companyPerformanceBo.setCompanyName(companyName);
            if (statisticsWay == ReceivedStatisticsEnum.WEEK.getWayCode()) {
                Calendar cal = Calendar.getInstance();
                cal.setFirstDayOfWeek(Calendar.MONDAY);
                cal.set(Calendar.YEAR, companyPerformanceBo.getYear());
                cal.set(Calendar.WEEK_OF_YEAR, Integer.valueOf(companyPerformanceBo.getWeekOfYear().replace("" + companyPerformanceBo.getYear(), "")));
                cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
                Date startDate = cal.getTime();
                cal.add(Calendar.DAY_OF_WEEK, 6);
                Date endDate = cal.getTime();
                companyPerformanceBo.setStartDate(DateUtil.format(startDate,"yyyy.MM.dd"));
                companyPerformanceBo.setEndDate(DateUtil.format(endDate,"yyyy.MM.dd"));
                companyPerformanceBo.setWeekOfYear(String.format("%s.%s",companyPerformanceBo.getYear()+"",companyPerformanceBo.getWeekOfYear().replace(companyPerformanceBo.getYear()+"","")));
            }
            if(statisticsWay == ReceivedStatisticsEnum.DAY.getWayCode()) {
                companyPerformanceBo.setDateStr(DateUtil.format(companyPerformanceBo.getDate(),"yyyy.MM.dd"));
            }

            if (statisticsWay == ReceivedStatisticsEnum.MONTH.getWayCode()){
                companyPerformanceBo.setMonth(String.format("%s.%s",companyPerformanceBo.getYear()+"",companyPerformanceBo.getMonth().replace(companyPerformanceBo.getYear()+"","")));
            }

        }
        return companyPerformanceBos;
    }
}
