package cn.com.countrygarden.bi.main.service.performance;

import cn.com.countrygarden.bi.main.dao.performance.PerformanceAreaMapper;
import cn.com.countrygarden.bi.main.event.ExcelDownloadEvent;
import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.List;


@Service
public class DownloadService implements ApplicationContextAware {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TbSysOrganService tbSysOrganService;

    @Autowired
    private PerformanceAreaMapper performanceAreaMapper;

    private ApplicationContext ac;

    /**
     * 获得文件方法
     * @param fileName
     * @param typeNo
     * @return
     * @throws FileNotFoundException
     */
    public FileInputStream getFile(String fileName, String typeNo) throws FileNotFoundException {

        File file;
        String resourceLocation =  "classpath:excel" + File.separator + "performance" + File.separator;

        if("1".equals(typeNo)){
            resourceLocation += fileName + ".xlsx";
        }else if("2".equals(typeNo)){
            resourceLocation += "cityCompany" + File.separator + fileName + ".xlsx";
        }

        try {
            file = ResourceUtils.getFile(resourceLocation);
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("excel文件不存在!");
        }

        return new FileInputStream(file);

    }

    /**
     * 获得Excel工作簿方法(用流的方式)
     */
    public Workbook getWorkbook(String fileName,String typeNo) throws FileNotFoundException{

        FileInputStream fis =  this.getFile(fileName,typeNo);
        Workbook wxb = null;
        try {
            wxb = new XSSFWorkbook(fis);
        } catch (IOException e) {
            logger.info(e.getMessage(),e);
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.info(e.getMessage(),e);
                }
            }
        }

        return wxb;
    }

    /**
     * 生成excel工作薄（不通用待完善 业务）
     * @param fileName
     * @param typeNo
     * @return
     * @throws FileNotFoundException
     */
    public Workbook createWorkbook(String fileName,String typeNo) throws FileNotFoundException{
        //获得工作簿
        Workbook wxb = this.getWorkbook(fileName,typeNo);
        //工作表
        Sheet sheet = wxb.getSheetAt(0);
        //所有数据从第7行开始
        int indexRow = 6;

        if ("1".equals(typeNo)) {
            //查询所有绩效区域
            List<TbSysOrgan> tbSysOrganList = tbSysOrganService.selectPerformanceArea();

            for (TbSysOrgan tbSysOrgan : tbSysOrganList) {
                Row row = sheet.createRow(indexRow);
                row.createCell(0).setCellValue(tbSysOrgan.getOrganCode());//写入区域id
                row.createCell(1).setCellValue(tbSysOrgan.getOrganName());//写入二级区域名称
                row.createCell(2).setCellValue(tbSysOrgan.getOrganName());//写入三级区域名称
                indexRow++;
            }
        } else if ("2".equals(typeNo)) {

            List<PerformanceArea> areaList = performanceAreaMapper.selectAllByTypeNo(typeNo);
            for (PerformanceArea area : areaList) {
                Row row = sheet.createRow(indexRow);
                row.createCell(0).setCellValue(area.getHierachyId());//写入区域id
                row.createCell(1).setCellValue(area.getHierachyName());//写入二级区域名称
                row.createCell(2).setCellValue(area.getHierachyName());//写入三级区域名称
                indexRow++;
            }
        }

        ExcelDownloadEvent excelDownloadEvent = new ExcelDownloadEvent(this,typeNo);

        //触发事件
        ac.publishEvent(excelDownloadEvent);

        return wxb;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.ac = applicationContext;
    }
}
