package com.goafanti.order.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.goafanti.admin.service.DepartmentService;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.Result;
import com.goafanti.common.dao.TOrderTaskMapper;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.order.bo.InputProjectStatistics;
import com.goafanti.order.bo.InputProvincialStatistics;
import com.goafanti.order.bo.OutProjectStatistics;
import com.goafanti.order.bo.OutProvincialStatistics;
import com.goafanti.order.bo.outStatistics.*;
import com.goafanti.order.enums.ApprovalTypeEnums;
import com.goafanti.order.service.ProjectStatisticsService;
import groovy.util.logging.Log4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.CellRangeAddress;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Service
@Log4j
public class ProjectStatisticsServiceImpl extends BaseMybatisDao<TOrderTaskMapper> implements ProjectStatisticsService {

	@Value("${upload.path}")
	private String downloadPath;
	@Autowired
	private DepartmentService departmentService;


	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutProjectStatistics> selectTaskList(InputProjectStatistics ps) {
		Map<String, Object> params= new HashedMap<>();
		Integer pageNo=1,pageSize=10;
		if(ps.getStartDate()!=null)params.put("startDate", ps.getStartDate());
		if(ps.getEndDate()!=null)params.put("endDate", ps.getEndDate()+" 23:59:59");
		if(ps.getDeps()!=null)params.put("deps", departmentService.parseArray(ps.getDeps()));
		if(ps.getThchDeps()!=null)params.put("thchDeps", departmentService.parseArray(ps.getThchDeps()));
		if(ps.getProjectStatus()!=null)params.put("projectStatus", ps.getProjectStatus());
		if(ps.getTaskProjectStatus()!=null)params.put("taskProjectStatus", ps.getTaskProjectStatus());
		if(ps.getProjectType()!=null)params.put("projectType", ps.getProjectType());
		if(ps.getOrderNo()!=null)params.put("orderNo", ps.getOrderNo());
		if(ps.getContractNo()!=null)params.put("contractNo", ps.getContractNo());
		if(ps.getUserName()!=null)params.put("userName", ps.getUserName());
		if (ps.getThchId()!=null)params.put("thchId", ps.getThchId());
		if (ps.getType()!=null){
			String[] split = ps.getType().split(",");
			params.put("type", split);
		}
		if(ps.getDeclarationBatch()!=null)params.put("declarationBatch", ps.getDeclarationBatch());
		if(ps.getProjectSituation()!=null)params.put("projectSituation", ps.getProjectSituation());
		if(ps.getProjectAmount()!=null) {
			// 0~0.5万、0.5~1万、1~2万、2~5万、5~10万、10~30万、30~50万、50到80万、80万上
			double s = 0,e=0;
			if (ps.getProjectAmount()==0) { s=0;e=0.5;
			}else if (ps.getProjectAmount()==1) {s=0;e=0.5;
			}else if (ps.getProjectAmount()==2) {s=0.5;e=1;
			}else if (ps.getProjectAmount()==3) {s=1;e=2;
			}else if (ps.getProjectAmount()==4) {s=2;e=5;
			}else if (ps.getProjectAmount()==5) {s=5;e=10;
			}else if (ps.getProjectAmount()==6) {s=10;e=30;
			}else if (ps.getProjectAmount()==7) {s=30;e=50;
			}else if (ps.getProjectAmount()==8) {s=50;e=80;
			}else if (ps.getProjectAmount()==9) {s=80;
			}
			params.put("projectAmount", ps.getProjectAmount());
			params.put("amountStart", s);
			params.put("amountEnd", e);
		}
		params.put("status",ps.getStatus()==null?0:ps.getStatus());
		if(ps.getProvince()!=null)	params.put("province", ps.getProvince());
		if(ps.getProjectId()!=null) params.put("projectId", ps.getProjectId());
		if(ps.getScreen()!=null) params.put("screen", ps.getScreen());
		if (ps.getSdStatus()!=null)params.put("sdStatus",ps.getSdStatus());
		if(ps.getPageNo()!=null)pageNo=ps.getPageNo();
		if(ps.getPageSize()!=null)pageSize=ps.getPageSize();
		Pagination<OutProjectStatistics> p = (Pagination<OutProjectStatistics>)findPage("selectProjectStatisticsListByPage",
				"selectProjectStatisticsCount", params, pageNo, pageSize);
		return p;
	}




	@Override
	public Result exporTaskList( InputProjectStatistics ib,HttpServletResponse response)  {
			if(ib.getPageSize()==null)ib.setPageSize(9999999);
			if(ib.getStatus()==null)ib.setStatus(0);
			List<OutProjectStatistics> list=  (List<OutProjectStatistics>) selectTaskList(ib).getList();
		for (OutProjectStatistics e : list) {
			if (com.goafanti.common.utils.StringUtils.isNotEmpty(e.getType())){
				String[] split = e.getType().split(",");
				StringBuilder sb=new StringBuilder();
				for (String s : split) {
					if (ApprovalTypeEnums.QT.getCode().equals(Integer.valueOf(s))){
						sb.append(ApprovalTypeEnums.getDesc(s))
								.append("(").append(e.getTypeExplain()).append(")")
								.append(",");
					}else {
						sb.append(ApprovalTypeEnums.getDesc(s)).append(",");
					}
				}
				e.setType(sb.substring(0,sb.length()-1));
			}
		}
			Result res =new Result();
			if (ib.getStatus()==null||ib.getStatus()==0){
				List<OutProjectStatisticsCommon> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsCommon common = new OutProjectStatisticsCommon();
					BeanUtils.copyProperties(o,common);
					tl.add(common);
				}
				NewExcelUtil<OutProjectStatisticsCommon> excelUtil=new NewExcelUtil<>(OutProjectStatisticsCommon.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（通用）",downloadPath);
			}else if (ib.getStatus()==1){//高新、科技
				List<OutProjectStatisticsHighTech> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsHighTech highTech = new OutProjectStatisticsHighTech();
					BeanUtils.copyProperties(o,highTech);
					tl.add(highTech);
				}
				NewExcelUtil<OutProjectStatisticsHighTech> excelUtil=new NewExcelUtil<>(OutProjectStatisticsHighTech.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（高新）",downloadPath);

			}else if (ib.getStatus()==2){//双软
				List<OutProjectStatisticsDoubleSoft> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsDoubleSoft doubleSoft = new OutProjectStatisticsDoubleSoft();
					BeanUtils.copyProperties(o,doubleSoft);

					tl.add(doubleSoft);
				}
				NewExcelUtil<OutProjectStatisticsDoubleSoft> excelUtil=new NewExcelUtil<>(OutProjectStatisticsDoubleSoft.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（双软）",downloadPath);

			}else if (ib.getStatus()==3){//软著
				List<OutProjectStatisticsSoftwareWorks> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsSoftwareWorks softwareWorks = new OutProjectStatisticsSoftwareWorks();
					BeanUtils.copyProperties(o,softwareWorks);
					softwareWorks.setQuantityAndcount(softwareWorks.getCommodityQuantity()+"/"+softwareWorks.getCertificatesCount());
					tl.add(softwareWorks);
				}
				NewExcelUtil<OutProjectStatisticsSoftwareWorks> excelUtil=new NewExcelUtil<>(OutProjectStatisticsSoftwareWorks.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（软著）",downloadPath);

			}else if (ib.getStatus()==4){//软著
				List<OutProjectStatisticsPatent> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsPatent patent = new OutProjectStatisticsPatent();
					BeanUtils.copyProperties(o,patent);
					patent.setQuantityAndcount(patent.getCommodityQuantity()+"/"+patent.getCertificatesCount());
					tl.add(patent);
				}
				NewExcelUtil<OutProjectStatisticsPatent> excelUtil=new NewExcelUtil<>(OutProjectStatisticsPatent.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（专利）",downloadPath);
			}else if (ib.getStatus()==5){//会员
				List<OutProjectStatisticsMember> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsMember member = new OutProjectStatisticsMember();
					BeanUtils.copyProperties(o,member);
					if (member.getServiceLife()!=null){
						JSONArray jsonArray = JSONArray.parseArray(member.getServiceLife());
						Object[] object=jsonArray.stream().toArray();
						member.setServiceLife(StringUtils.join(object,","));
					}
					if (member.getContractTerm()!=null){
						JSONArray jsonArray = JSONArray.parseArray(member.getContractTerm());
						Object[] object=jsonArray.stream().toArray();
						member.setContractTerm(StringUtils.join(object,"～"));
					}
					tl.add(member);
				}
				NewExcelUtil<OutProjectStatisticsMember> excelUtil=new NewExcelUtil<>(OutProjectStatisticsMember.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（会员）",downloadPath);
			}else if (ib.getStatus()==6){//会员
				List<OutProjectStatisticsAudit> tl=new ArrayList<>();
				for (OutProjectStatistics o : list) {
					OutProjectStatisticsAudit audit = new OutProjectStatisticsAudit();
					BeanUtils.copyProperties(o,audit);
					if (audit.getServiceLife()!=null){
						JSONArray jsonArray = JSONArray.parseArray(audit.getServiceLife());
						Object[] object=jsonArray.stream().toArray();
						audit.setServiceLife(StringUtils.join(object,","));
					}
					if (audit.getContractTerm()!=null){
						JSONArray jsonArray = JSONArray.parseArray(audit.getContractTerm());
						Object[] object=jsonArray.stream().toArray();
						audit.setContractTerm(StringUtils.join(object,"～"));
					}
					tl.add(audit);
				}
				NewExcelUtil<OutProjectStatisticsAudit> excelUtil=new NewExcelUtil<>(OutProjectStatisticsAudit.class);
				res=excelUtil.exportExcel(tl,"项目汇总表（审计）",downloadPath);
			}
			return  res;
	}



	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutProvincialStatistics> selectProvincialStatistics(InputProvincialStatistics is) {
		Map<String, Object> params= new HashedMap<>();
		Integer pageNo=1,pageSize=10;
		if(is.getStartDate()!=null)params.put("startDate", is.getStartDate());
		if(is.getEndDate()!=null)params.put("endDate", is.getEndDate()+" 23:59:59");
		if(is.getThchDeps()!=null)params.put("thchDeps", departmentService.parseArray(is.getThchDeps()));
		if(is.getProjectStatus()!=null)params.put("projectStatus", is.getProjectStatus());
		if(is.getProjectType()!=null)params.put("projectType", is.getProjectType());
		if(is.getProvince()!=null)params.put("province", is.getProvince());
		if(is.getProjectId()!=null)params.put("projectId", is.getProjectId());
		params.put("status",is.getStatus()==null?0:is.getStatus());
		if(is.getPageNo()!=null)pageNo=is.getPageNo();
		if(is.getPageSize()!=null)pageSize=is.getPageSize();
		Pagination<OutProvincialStatistics> p = (Pagination<OutProvincialStatistics>)findPage("selectProvincialStatisticsListByPage",
				"selectProvincialStatisticsCount", params, pageNo, pageSize);
		return p;
	}

	@Override
	public Result exporProvincialList(InputProvincialStatistics ib) {
		OutputStream out = null;
		XSSFWorkbook wb=null;
		try {
			if(ib.getPageSize()==null)ib.setPageSize(9999999);
			if(ib.getStatus()==null)ib.setStatus(0);
			@SuppressWarnings("unchecked")
			List<OutProvincialStatistics> list=  (List<OutProvincialStatistics>) selectProvincialStatistics(ib).getList();
			//派单賞份负责部门项目类別陸存数(个)派单数(个)下证数(个)签单额(万元)成本(万元)利润(万元)
			String[] comment = {"派单省份","负责部门","项目别类","库存数","派单数"};
			List<String> ls = new ArrayList<String>();
			Collections.addAll(ls, comment);
    		if (ib.getStatus()==1) {
				//高新
    			//是否立项 立项时间 是否抽查 联系人电话 法人电话 证书编号 申报批次
    			String[] ss= {"完成数","立项数","抽查数","未通过"};
    			Collections.addAll(ls, ss);
			}else if (ib.getStatus()==2||ib.getStatus()==3) {
				//发明专利、实用新型
				ls.add("受理数");
				ls.add("完结数");
				ls.add("授权数");
				ls.add("驳回数");

			}else if (ib.getStatus()==4) {
				//软著
				ls.add("下证数");
			}else if (ib.getStatus()==5) {
				//商标
				String[] ss= {"申请数","驳回数","下证数"};
				Collections.addAll(ls, ss);
			}else if (ib.getStatus()==0) {
				String[] ss= {"完成数","公示数"};
				Collections.addAll(ls, ss);
			}
    		String[] ss= {"签单额(万元)","成本(万元)","利润(万元)"};
			Collections.addAll(ls, ss);
    		comment= ls.toArray(new String[ls.size()]);
//    		String fileName ="项目数据统计" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
			String filename = UUID.randomUUID().toString() + "_ProvincialList.xlsx";
    		wb =ExportExcelUtil.exportTemplateInfoS(comment,"项目数据统计");
    		//根据列表编写文档
    		XSSFSheet sheet =wb.getSheetAt(0);
    		XSSFRow xr = sheet.createRow(sheet.getLastRowNum()+1);
    		//4.创建一个cell
    		XSSFCell cell = xr.createCell(0);
    		cell.setCellValue(getProvincialInputString(ib));
    		sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, comment.length-1));//合并单元格
    		for (OutProvincialStatistics ob : list) {
    			//新增一行
    			XSSFRow r = sheet.createRow(sheet.getLastRowNum()+1);
    			for (int i = 0; i < comment.length; i++) {
    				//当前列的只
    				String o = "";
    				switch (comment[i]) {
//    				"派单省份","负责部门","项目别类","库存数(个)","派单数(个)","下证数(个)","签单数(个)","成本(万元)","利润(万元)"
    				case "派单省份": o = ob.getProvinceName(); break;
    				case "负责部门": o = ob.getThchDepName(); break;
    				case "项目别类": o = ob.getProjectStatus(); break;
    				case "库存数": o = ob.getStockCount().toString(); break;
    				case "派单数": o = ob.getDistributeCount().toString(); break;
    				//"完成数","立项数","抽查数","未通过"
    				case "完成数": o = ob.getCompleteCount().toString(); break;
    				case "立项数": o = ob.getSetUpCount().toString(); break;
    				case "抽查数": o = ob.getSpotCheckCount().toString(); break;
    				case "未通过": o = ob.getFailedCount().toString(); break;
    				//受理数 完结数 授权数 驳回数
    				case "受理数": o = ob.getAcceptCount().toString(); break;
    				case "完结数": o = ob.getCompleteCount().toString(); break;
    				case "授权数": o = ob.getAuthorizeCount().toString(); break;
    				case "驳回数": o = ob.getRejectCount().toString(); break;
    				//下证数
    				case "下证数": o = ob.getCertificatesCount().toString(); break;
    				//"申请数","驳回数","下证数"
    				case "申请数": o = ob.getApplyCount().toString(); break;
    				//"完成数","公示/立项数"
    				case "公示数": o = ob.getPublicityCount().toString(); break;

    				case "签单额(万元)": o = ob.getAmountCount().stripTrailingZeros().toPlainString(); break;
    				case "成本(万元)": o = ob.getCostAmount().stripTrailingZeros().toPlainString(); break;
    				case "利润(万元)": o = ob.getProfit().stripTrailingZeros().toPlainString(); break;
    				default: o = ""; break;
    				}
    				XSSFCell c = r.createCell(i);
    				c.setCellValue(o);

    			}
    		}
			String downloadPath = this.downloadPath+"/" + filename;
			File desc = new File(downloadPath);
			if (!desc.getParentFile().exists()) {
				desc.getParentFile().mkdirs();
			}
			out=new FileOutputStream(downloadPath);
    		// 返回数据流
			 wb.write(out);
			return new Result().data(filename);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(new Error("表格生成错误。"));
		}finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (wb !=null){
				try {
					wb.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	private String getProvincialInputString(InputProvincialStatistics ib) {
		String str="搜索条件:";
		int i=1;
		if(ib.getStartDate()!=null) str=StringUtils.join(str,i++,"-开始时间：",ib.getStartDate(),"   ");
		if(ib.getEndDate()!=null)str=StringUtils.join(str,i++,"-结束时间：",ib.getEndDate(),"   ");
		if(ib.getProvince()!=null)str=StringUtils.join(str,i++,"-省份：",ib.getProvinceName(),"   ");
		if(ib.getThchDeps()!=null)str=StringUtils.join(str,i++,"-责任部门：",ib.getThchDepName(),"   ");
		if(ib.getProjectStatus()!=null)str=StringUtils.join(str,i++,"-项目别类：",ib.getProjectStatusName(),"   ");
		if(ib.getProjectType()!=null)str=StringUtils.join(str,i++,"-项目分类：",ib.getProjectTypeName(),"   ");
		if(ib.getProjectId()!=null)str=StringUtils.join(str,i++,"-项目名称：",ib.getProjectName(),"   ");
		if(i==1)StringUtils.join(str,"无");
		return str;
	}

}
