package com.kiisoo.ic.analysis.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.analysis.bean.TableAnalysisDTO;
import com.kiisoo.ic.common.BaseController;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.mapper.PoiCustomerContactDataStatMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.store.bean.CpUserExcelDTO;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yechenhao
 * @date 2020/5/9 14:24
 * @company kiisoo
 * @details 报表分析service
 */
@Service
public class TableAnalysisService extends BaseController {


    @Autowired
    private RetailCompanyMapper retailCompanyMapper;


    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;


    @Autowired
    private PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper;


    /**
     * 查询
     * @param selectStartTime 开始时间
     * @param selectEndTime 结束时间
     * @return
     */
    public List<TableAnalysisDTO> listCompanyAddCustomer(Date selectStartTime, Date selectEndTime){
        List<TableAnalysisDTO> results = new ArrayList<>();
        QueryWrapper<PrivilageOrganizational> companyQw = new QueryWrapper<>();
        companyQw.eq("level",2).eq("type",2).eq("status",1);
        List<PrivilageOrganizational> companys = retailCompanyMapper.selectList(companyQw);
        for (PrivilageOrganizational company:companys){
            List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCompany(company.getId());
            if (CollectionUtils.isEmpty(poiStores)){
                continue;
            }
            List<Long> storeIds = poiStores.stream().map(a->a.getId()).collect(Collectors.toList());
            BigDecimal sumAdd = poiCustomerContactDataStatMapper.selectSumAddCustomer(storeIds,selectStartTime,selectEndTime);
            if (sumAdd == null){
                sumAdd = new BigDecimal(0);
            }
            BigDecimal avgAdd = sumAdd.divide(new BigDecimal(storeIds.size()),0, BigDecimal.ROUND_HALF_UP);
            TableAnalysisDTO tableAnalysisDTO = new TableAnalysisDTO();
            tableAnalysisDTO.setCompanyName(company.getName());
            tableAnalysisDTO.setAddCustomer(sumAdd);
            tableAnalysisDTO.setAvgAddCustomer(avgAdd);
            tableAnalysisDTO.setStoreNum(storeIds.size());
            results.add(tableAnalysisDTO);
        }
        return results;
    }

    public List<TableAnalysisDTO> listCompanyApplyCustomer(Date selectStartTime, Date selectEndTime, Integer count) {
        List<TableAnalysisDTO> results = new ArrayList<>();
        QueryWrapper<PrivilageOrganizational> companyQw = new QueryWrapper<>();
        companyQw.eq("level",2).eq("type",2).eq("status",1);
        List<PrivilageOrganizational> companys = retailCompanyMapper.selectList(companyQw);
        for (PrivilageOrganizational company:companys){
            List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCompany(company.getId());
            if (CollectionUtils.isEmpty(poiStores)){
                continue;
            }
            List<Long> storeIds = poiStores.stream().map(a->a.getId()).collect(Collectors.toList());
            TableAnalysisDTO result = new TableAnalysisDTO();
            List<TableAnalysisDTO> tableAnalysisDTOS = poiCustomerContactDataStatMapper.selectSumApplyCustomer(storeIds,count,selectStartTime,selectEndTime);
            if (CollectionUtils.isEmpty(tableAnalysisDTOS)){
                result.setStoreNum(0);
                result.setApplyCustomer(new BigDecimal(0));
            }else{
                BigDecimal sumApply = new BigDecimal(0);
                Integer storeNum = tableAnalysisDTOS.size();
                for (TableAnalysisDTO tableAnalysisDTO:tableAnalysisDTOS){
                    sumApply = sumApply.add(tableAnalysisDTO.getApplyCustomer());
                }
                BigDecimal avgAdd = sumApply.divide(new BigDecimal(storeNum),0, BigDecimal.ROUND_HALF_UP);
                result.setStoreNum(storeNum);
                result.setApplyCustomer(avgAdd);
            }
            result.setCompanyName(company.getName());
            results.add(result);
        }
        return results;
    }

    public void downloadExcel(String title, String jsonData, String company, HttpServletResponse response) throws IOException {
        String[] headNames = company.replace("[", "").replace("]", "").split(",");
        HSSFWorkbook ws = new HSSFWorkbook();
        String[] titles = title.split(",");
        Sheet hssfSheet = ws.createSheet("零售公司");

        HSSFCellStyle cellStyle = ws.createCellStyle();
        cellStyle.setWrapText(true);//设置自动换行


        int isAdd = 0;

        //设置列名
        if (null != headNames && headNames.length > 0) {

            Row row = hssfSheet.createRow(isAdd++);
            for (int i = 0; i <= headNames.length; i++) {
                if (i == 0){
                    Cell cell = row.createCell(i);
                    cell.setCellValue("零售公司");
                }else{
                    String name = headNames[i-1];
                    name = name.replace("\"","");
                    Cell cell = row.createCell(i);
                    cell.setCellValue(name);
                }
            }
        }

        String[] split = jsonData.split("##");

        for (int i = 0; i < titles.length; i++) {

            //创造行
            Row row = hssfSheet.createRow(isAdd++);

            String dataStr = split[i];
            String[] datas = dataStr.replace("[", "").replace("]", "").split(",");
            for (int j = 0;j<=datas.length;j++){
                if (j == 0){
                    String name = titles[i];
                    name = name.replace("\"","");
                    Cell cell = row.createCell(j);
                    cell.setCellValue(name);
                }else{
                    String value = datas[j-1];
                    Cell cell = row.createCell(j);
                    cell.setCellValue(value);
                }
            }
        }
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=company.xls");
        response.setContentType("application/msexcel");
        ws.write(output);
    }
}
