package com.goafanti.order.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.Result;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.model.TOrderMonthReport;
import com.goafanti.common.model.TOrderNew;
import com.goafanti.common.utils.ExcelUtils;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.OrderReportBo;
import com.goafanti.order.bo.TOrderBonusBo;
import com.goafanti.order.service.FundManageOrderService;
import com.goafanti.order.service.OrderBonusService;
import com.goafanti.order.service.OrderReportService;
import com.goafanti.permission.service.NewRoleService;

@RestController
@RequestMapping(value = "/api/admin/bonus")
public class OrderBonusStatisticsApiController extends CertifyApiController {
	@Resource
	private FundManageOrderService fundManageOrderServiceImpl;
	@Resource
	private OrderBonusService orderBonusServiceImpl;
	@Resource
	private OrderReportService orderReportServiceImpl;
	@Resource
	private NewRoleService newRoleService;
	@Value(value = "${upload.private.path}")
	private String	uploadPrivatePath	= null;
	 /**
	  * 财务专员校对单量
	  * @param orderNew
	  * @return
	  */
	 @RequestMapping(value="/proofreading", method = RequestMethod.POST)
	 public Result proofreading(TOrderNew orderNew){
		 Result res = new Result();
		 res.setData(fundManageOrderServiceImpl.updateProofreading(orderNew));
		 return res;
	 }
	 
	 /**
	  * 营销员奖金统计
	  * @param orderNewBo
	  * @return
	  */
	 @RequestMapping(value="/saleBonusStatistics", method = RequestMethod.GET)
	 public Result saleBonusStatistics(TOrderBonusBo bonusBo, Integer pageNo, Integer pageSize){
		 Result res = new Result();
		 res.setData(orderBonusServiceImpl.saleBonusStatistics(bonusBo, pageNo, pageSize));
		 return res;
	 }
	 
	 /**
	  * 财务专员发放营销员奖金
	  * @param id
	  * @return
	  */
	 @RequestMapping(value="/bonusPayment", method = RequestMethod.POST)
	 public Result bonusPayment(String id,String orderNo){
		 Result res = new Result();
		 Integer i = orderBonusServiceImpl.updateBounsPaymnetStatus(id, orderNo);
		 if(i>0){
				res.setData("发放成功!");
			}else{
				res.getError().add(buildError("", "没有校对单量,不能发放"));
			}
		 return res;
	 }
	 
	 /**
	  * 财务专员查看技术员奖金数据
	  * @param bonusBo
	  * @param pageNo
	  * @param pageSize
	  * @return
	  */
	 @RequestMapping(value="/technicianBonusStatistics", method = RequestMethod.GET)
	 public Result technicianBonusStatistics(TOrderBonusBo bonusBo,Integer pageNo, Integer pageSize){
		 Result res = new Result();
		 res.setData(orderBonusServiceImpl.technicianBonusStatistics(bonusBo, pageNo, pageSize));
		 return res;
	 }
	 
	 /**
	  * 财务专员发放技术员的奖金操作
	  * @param id
	  * @return
	  */
	 @RequestMapping(value="/changeBonus", method = RequestMethod.POST)
	 public Result changeBonus(String id){
		 Result res = new Result();
		 res.setData(orderBonusServiceImpl.updateChangeBonus(id));
		 return res;
	 }
	 
	 
	 /**
	  * 财务专员导出营销员奖金数据
	  * @param bonusBo
	  * @param response
	  * @return
	  * @throws IOException
	  */
	 @RequestMapping(value="/exportSaleBonusData", method = RequestMethod.GET)
	 public Result exportSaleBonusData(TOrderBonusBo bonusBo,HttpServletResponse response) throws IOException{
		 OutputStream out = response.getOutputStream();
		 Result res = new Result();
		 bonusBo.setGrantBy(TokenManager.getAdminId());
		 XSSFWorkbook wb = orderBonusServiceImpl.exportSaleBonusData(bonusBo);
		 if(null == wb){
			 wb = new XSSFWorkbook();
			 XSSFSheet sheet = wb.createSheet("没有营销员奖金记录");
			 XSSFRow row = sheet.createRow(0);
			 XSSFCell cell = row.createCell(0);
			 cell.setCellValue("没有营销员奖金记录");
		 }
		 String fileName = "营销员奖金统计" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
		 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
		 response.setContentType("application/octet-stream;charset=utf-8");  
		 try {
			 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		 } finally {
			 out.flush(); 
			 out.close(); 
		 }
		 return res;
	 }
	 
	/**
	 * 导出技术员(咨询师)的奖金数据
	 * @param bonusBo
	 * @param response
	 * @return
	 * @throws IOException
	 */
	 @RequestMapping(value="/exportTechnicianBonusData", method = RequestMethod.GET)
	 public Result exportTechnicianBonusData(TOrderBonusBo bonusBo,HttpServletResponse response) throws IOException{
		 OutputStream out = response.getOutputStream();
		 Result res = new Result();
		 bonusBo.setGrantBy(TokenManager.getAdminId());
		 XSSFWorkbook wb = orderBonusServiceImpl.exportTechnicianBonusData(bonusBo);
		 if(null == wb){
			 wb = new XSSFWorkbook();
			 XSSFSheet sheet = wb.createSheet("没有技术员奖金记录");
			 XSSFRow row = sheet.createRow(0);
			 XSSFCell cell = row.createCell(0);
			 cell.setCellValue("没有技术员奖金记录");
		 }
		 String fileName = "技术员奖金统计" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
		 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
		 response.setContentType("application/octet-stream;charset=utf-8");  
		 try {
			 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		 } finally {
			 out.flush(); 
			 out.close(); 
		 }
		 return res;
	 }
	 
	 /**
	  * 订单报表统计数据
	  * @param reportBo
	  * @param pageNo
	  * @param pageSize
	  * @return
	  * @throws IOException
	  */
	 @RequestMapping(value="/orderReportList", method = RequestMethod.GET)
	 public Result orderReportList(OrderReportBo reportBo, Integer pageNo, Integer pageSize) throws IOException{
		Result res = new Result();
		if(null == reportBo.getMonth() || null == reportBo.getMonth1()){
			res.getError().add(buildError("", "没有指定订单日期"));
			return res;
		}
		res.setData(orderReportServiceImpl.getOrderReportData(reportBo, pageNo, pageSize));
		return res;
	 }
	 
	 /**
	  * 导出订单数据
	  * @param orderReportBo
	  * @param response
	  * @return
	  * @throws IOException
	  */
	 @RequestMapping(value="/exportOrderData", method = RequestMethod.GET)
	 public Result exportOrderData(OrderReportBo orderReportBo,HttpServletResponse response) throws IOException{
		 //判断当前登录的角色
		 Result res = new Result();
		 if(null == orderReportBo.getMonth() || null == orderReportBo.getMonth1()){
			res.getError().add(buildError("", "没有指定订单日期"));
			return res;
		 }
		 String date = orderReportBo.getMonth() == orderReportBo.getMonth1() ? orderReportBo.getMonth().toString() : orderReportBo.getMonth() + "-" + orderReportBo.getMonth1(); 
		 OutputStream out = response.getOutputStream();
		 XSSFWorkbook wb = orderReportServiceImpl.exportMonthData(orderReportBo, date);
		 if(null == wb){
			 wb = new XSSFWorkbook();
			 XSSFSheet sheet = wb.createSheet("没有订单统计记录");
			 XSSFRow row = sheet.createRow(0);
			 XSSFCell cell = row.createCell(0);
			 cell.setCellValue("没有订单统计记录");
		 }
		 String fileName = "订单统计" + date + ".xls";
		 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
		 response.setContentType("application/octet-stream;charset=utf-8");  
		 try {
			 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		 } finally {
			 out.flush(); 
			 out.close(); 
		 }
		 return res;
	 }
	 /**
	  * 导入订单模板
	  * @param req
	  * @return
	  */
	@RequestMapping(value = "/uploadOrderExcel",method = RequestMethod.POST)
	public Result uploadExcel(HttpServletRequest req){
		Result res = new Result();
		String excelPath = handleFile(res, "/order_report_file/", true, req, "");
		ExcelUtils utils = new ExcelUtils();
			Set<OrderReportBo> boSet;
			try {
				boSet = utils.parseOrderExcel(uploadPrivatePath + excelPath);
				String errorMessage = "";
				//if(boSet.size()>100)	errorMessage += "导入数据不能超过一百条;";
				errorMessage += utils.getVacantRows();
				if(StringUtils.isNotBlank(errorMessage)) {
					res.getError().add(new Error(errorMessage));
					return res;
				}
				Set<Integer> existRows = new TreeSet<Integer>(); //数据库已存在
				Set<Integer> filterRows = new TreeSet<Integer>(); //过滤提示
				orderReportServiceImpl.checkOrderReport(boSet,existRows,filterRows);
				if(existRows.size()>0){
					errorMessage = StringUtils.join(existRows.toArray(),",")+ " 订单统计数据已存在;";
					res.getError().add(new Error(errorMessage));
					return res;
				}
				if(filterRows.size()>0){
					errorMessage = StringUtils.join(filterRows.toArray(),",")+ " 行没有找到相关员工电话,已经被系统过滤;";
					res.getError().add(new Error(errorMessage));
					return res;
				}
				res.setData(orderReportServiceImpl.saveUploadData(boSet));
			} catch (IOException e) {
				e.printStackTrace();
			}	
		return res;
	}
	
	/**
	 * 下载年度订单数据模板
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/downOrderModelExcel",method = RequestMethod.GET)
	public Result downOrderModelExcel(HttpServletResponse response) throws IOException{
		Result res = new Result();
		 OutputStream out = response.getOutputStream();
		 XSSFWorkbook wb = ExportExcelUtil.downOrderModelExcel();
		 String fileName = "导入年度销售数据模板.xls";
		 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
		 response.setContentType("application/octet-stream;charset=utf-8");  
		 try {
			 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		 } finally {
			 out.flush(); 
			 out.close(); 
		 }
		return res;
	}
	 
	/**
	 * 手动更新校对单量
	 * @param report
	 * @return
	 */
	@RequestMapping(value="/updateProof", method = RequestMethod.POST)
	public Result updateProof(TOrderMonthReport report){
		Result res = new Result();
		res.setData(orderReportServiceImpl.updateMonthDataById(report));
		return res;
	}
	
	/**
	 * 营销管理员查看所有营销员奖金
	 * @param bonusBo
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value="/getAllSaleBonus", method = RequestMethod.GET)
	public Result getAllSaleBonus(TOrderBonusBo bonusBo, Integer pageNo, Integer pageSize){
		 Result res = new Result();
		 res.setData(orderBonusServiceImpl.saleBonusStatistics(bonusBo, pageNo, pageSize));
		 return res;
	}
	
	/**
	 * 营销管理员导出所有营销员奖金
	 * @param bonusBo
	 * @param response
	 * @return
	 * @throws IOException
	 */
	 @RequestMapping(value="/exportAllSaleBonusData", method = RequestMethod.GET)
	 public Result exportAllSaleBonusData(TOrderBonusBo bonusBo,HttpServletResponse response) throws IOException{
		 OutputStream out = response.getOutputStream();
		 Result res = new Result();
		 XSSFWorkbook wb = orderBonusServiceImpl.exportSaleBonusData(bonusBo);
		 if(null == wb){
			 wb = new XSSFWorkbook();
			 XSSFSheet sheet = wb.createSheet("没有营销员奖金记录");
			 XSSFRow row = sheet.createRow(0);
			 XSSFCell cell = row.createCell(0);
			 cell.setCellValue("没有营销员奖金记录");
		 }
		 String fileName = "营销员奖金统计" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
		 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
		 response.setContentType("application/octet-stream;charset=utf-8");  
		 try {
			 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		 } finally {
			 out.flush(); 
			 out.close(); 
		 }
		 return res;
	 }
}
