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

import cn.com.countrygarden.bi.main.model.performance.PerformanceCompany;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.service.performance.PerformanceCompanyService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.util.SyncErpToPerformanceUtil;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 模板下载
 *
 * @author Max
 * @version 1.0
 * @since 1.8
 */
@Controller("templateDownload")
@RequestMapping("/templateDownload")
public class TemplateDownloadController {

    private Logger logger = LoggerFactory.getLogger(PerformanceAuthorityController.class);

    @Autowired
    private TbSysOrganService tbSysOrganService;

    @Autowired
    private SyncErpToPerformanceUtil syncErpToPerformanceUtil;

    @Autowired
    private PerformanceCompanyService performanceCompanyService;


    /**
     * 月度-区域—模板下载
     *
     * @param response Response
     */
    @RequestMapping(value = "/choiceRegionMonthlyDownload", method = {RequestMethod.POST, RequestMethod.GET})
    public void choiceRegionMonthlyDownload(HttpServletResponse response) {
        try {
            //获得模板文件
            File templateFile = ResourceUtils.getFile("classpath:excel" + File.separator + "performance" + File.separator +
                    "monthly" + File.separator + "区域月度完成情况.xlsx");
            FileInputStream fileInputStream = new FileInputStream(templateFile);
            Workbook xwb = new XSSFWorkbook(fileInputStream);//得到模板信息
            Sheet sheet = xwb.getSheetAt(0);//得到第一个工作薄
            int indexRow = 6;//所有数据从第7行开始

            //查询所有绩效区域
            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++;
            }

            //同步数据库，erp同步到performance_env
            syncErpToPerformanceUtil.syncByType("1");

            //输出
            response.setHeader("Content-Disposition", "attachment; filename=" + new String("区域月度完成情况".getBytes("gbk"), "ISO-8859-1") + ".xlsx");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            response.setContentType("application/vnd.ms-excel");
            OutputStream outputStream = response.getOutputStream();
            xwb.write(outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            logger.error("file not found");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("IOException");
            e.printStackTrace();
        }
    }

    /**
     * 月度-区域—模板下载
     *
     * @param response Response
     */
    @RequestMapping(value = "/choiceCompanyMonthlyDownload", method = {RequestMethod.POST, RequestMethod.GET})
    public void choiceCompanyMonthlyDownload(HttpServletResponse response) {
        try {
            //获得模板文件
            File templateFile = ResourceUtils.getFile("classpath:excel" + File.separator + "performance" + File.separator +
                    "monthly" + File.separator + "城市公司月度完成情况.xlsx");
            FileInputStream fileInputStream = new FileInputStream(templateFile);
            Workbook xwb = new XSSFWorkbook(fileInputStream);//得到模板信息
            Sheet sheet = xwb.getSheetAt(0);//得到第一个工作薄
            //所有数据从第7行开始
            int indexRow = 6;

            List<PerformanceCompany> performanceCompanyList = performanceCompanyService.selectValidCompany();//获得所有城市公司

            for (PerformanceCompany performanceCompany : performanceCompanyList) {
                Row row = sheet.createRow(indexRow);
                row.createCell(0).setCellValue(performanceCompany.getHierarchyId());//写入城市公司id
                row.createCell(1).setCellValue(performanceCompany.getHierarchyName());//写入二级区域名称
                row.createCell(2).setCellValue(performanceCompany.getHierarchyName());//写入三级区域名称
                indexRow++;
            }

            //输出
            response.setHeader("Content-Disposition", "attachment; filename=" + new String("城市公司月度完成情况".getBytes("gbk"), "ISO-8859-1") + ".xlsx");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            response.setContentType("application/vnd.ms-excel");
            OutputStream outputStream = response.getOutputStream();
            xwb.write(outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            logger.error("file not found");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("IOException");
            e.printStackTrace();
        }
    }
}
