package com.yizhi.application.assignment.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.assignment.application.vo.AssignmentQXVO;
import com.yizhi.assignment.application.vo.entity.AssignmentStudent;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.context.TaskContext;
import com.yizhi.core.application.file.constant.FileConstant;
import com.yizhi.core.application.file.task.AbstractDefaultTask;
import com.yizhi.core.application.file.util.OssUpload;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.vo.AccountVO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AssignmentUnsubmittedExport extends AbstractDefaultTask<String, Map<String,Object>> {


	private static final Logger logger = LoggerFactory.getLogger(AssignmentUnsubmittedExport.class);

	@Autowired
	private AssignmentClient assignmentClient;
	@Autowired
	private AccountClient accountClient;
	@Autowired
    private OrganizationClient organizationClient;



	@Override
	protected String execute(Map<String, Object> map) {
		// TODO Auto-generated method stub
		  String upLoadUrl=null;
		  Long companyId=(Long) map.get("companyId");
		  Long accountId=(Long) map.get("accountId");
		  Long siteId=(Long) map.get("siteId");
		  Long assignmentId=(Long) map.get("assignmentId");
		  Long taskId=(Long) map.get("taskId");
		  Date submitTime=(Date) map.get("submitTime");
		  String serialNo=(String) map.get("serialNo");
		  String taskName=(String) map.get("taskName");
		  RequestContext context = (RequestContext) map.get("context");
        Map<Long, String> accountOrgFullNameMap = organizationClient.getAccountOrgFullNameMap(companyId);

         logger.info("返回当前的组织列表：{}", JSON.toJSON(accountOrgFullNameMap));

		  /**
		   * 走异步任务
		   */
		  TaskContext taskContext = new TaskContext(taskId, serialNo, taskName, accountId, submitTime, siteId, companyId);
	      working(taskContext);


		 //指定的学员范围
		  AssignmentQXVO assignmentQXVO=assignmentClient.exportExcel(assignmentId);
		  List<AccountVO> list=new ArrayList<AccountVO>();  //查询到未提交作业的名单在这个集合
		  if(assignmentQXVO!=null) {
			  if(assignmentQXVO.getVisibleRange()==1) {  //全平台可见
				  //根据站点id  找到站点下的所有人
				  List<AccountVO> listSiteIdAllStudent=accountClient.findBySiteId(assignmentQXVO.getSiteId());
				  //站点下的所有的id集合
				  List<Long> listIdAllStudentIds=new ArrayList<Long>();
				  if(listSiteIdAllStudent!=null) {
					  for (int i = 0; i < listSiteIdAllStudent.size(); i++) {
						  listIdAllStudentIds.add(listSiteIdAllStudent.get(i).getId());
					}
				  }
				 //已经提交的人员
				  List<Long> listIdCommitStudentIds=new ArrayList<Long>();
				  if(assignmentQXVO.getListSubmitAccountId()!=null) {
					  listIdCommitStudentIds=assignmentQXVO.getListSubmitAccountId();
				  }
				  //两者取差集
				  listIdAllStudentIds.removeAll(listIdCommitStudentIds);
				  list=accountClient.idsGet(listIdAllStudentIds);
			  }

			  if(assignmentQXVO.getVisibleRange()==2&&assignmentQXVO.getListStudent()!=null) {   //指定用户可见
				  List<AssignmentStudent> listQXIdAllStudent=assignmentQXVO.getListStudent();  //指定的人
				  List<Long> listIdAllStudentIds=new ArrayList<Long>();//指定的ids
				  for (int i = 0; i < listQXIdAllStudent.size(); i++) {
					  AssignmentStudent assignmentStudent=listQXIdAllStudent.get(i);
					  if(assignmentStudent.getType()==2) {   //用户
						  listIdAllStudentIds.add(assignmentStudent.getAccountId());
					  }
					  if(assignmentStudent.getType()==1) {   //部门
						  List<AccountVO> listAccountVO = accountClient.findByOrgId(assignmentStudent.getAccountId(), companyId);
						  if(listAccountVO!=null) {
							  for (int j = 0; j < listAccountVO.size(); j++) {
								  listIdAllStudentIds.add(listAccountVO.get(j).getId());
							}
						  }
					  }
					  if(assignmentStudent.getType()==3) {   //用户组
						  List<AccountVO> listAccountVO = accountClient.findByGroupId(assignmentStudent.getAccountId(), companyId);
						  if(listAccountVO!=null) {
							  for (int j = 0; j < listAccountVO.size(); j++) {
								  listIdAllStudentIds.add(listAccountVO.get(j).getId());
							}
						  }
					  }
				  }

				  //已经提交的人员
				  List<Long> listIdCommitStudentIds=new ArrayList<Long>();
				  if(assignmentQXVO.getListSubmitAccountId()!=null) {
					  listIdCommitStudentIds=assignmentQXVO.getListSubmitAccountId();
				  }
				  //两者取差集
				  listIdAllStudentIds.removeAll(listIdCommitStudentIds);
				  list=accountClient.idsGet(listIdAllStudentIds);

				  //指定的人去重
				  List<Long> newList = new  ArrayList<Long>();
			         for (Long cd:listIdAllStudentIds) {
			            if(!newList.contains(cd)){
			                newList.add(cd);
			            }
			        }

			      list=accountClient.idsGet(newList);

			  }
			  if(assignmentQXVO.getVisibleRange()==2&&assignmentQXVO.getListStudent()==null) {
				  logger.error("设置范围为指定人员可见，但是没有指定人");//根本就没数据
			  }
		  }



        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");


		    try {
				//excel生成过程: excel-->sheet-->row-->cell
				// 第一步，创建一个Excel文件
				HSSFWorkbook wb = new HSSFWorkbook();

				//最大限度是50000


				// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
				HSSFSheet sheet = wb.createSheet(assignmentQXVO.getName()+"未完成名单");

				// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
				HSSFRow row = sheet.createRow((int) 0);
				// 第四步，创建单元格，并设置值表头 设置表头居中
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

				// 合并单元格
				CellRangeAddress cra=new CellRangeAddress(0,0,0,3); // 起始行, 终止行, 起始列, 终止列
				sheet.addMergedRegion(cra);
				HSSFCell cell = row.createCell((short) 0);
				cell.setCellValue(assignmentQXVO.getName()+"未完成名单");
				cell.setCellStyle(style);

				// 第三步，在sheet中添加表头第1行,注意老版本poi对Excel的行数列数有限制short
				HSSFRow row2 = sheet.createRow((int) 1);
				// 第四步，创建单元格
				CellRangeAddress cra2=new CellRangeAddress(1,1,0,3);
				sheet.addMergedRegion(cra2);
				HSSFCell cell2 = row2.createCell((short) 0);
				cell2.setCellValue("统计周期：截止"+df.format(submitTime));

				//创建第三行
				HSSFRow row3 = sheet.createRow((int) 2);
				row3.createCell((short) 0).setCellValue("用户名");
				row3.createCell((short) 1).setCellValue("姓名");
				row3.createCell((short) 2).setCellValue("所在部门");
				row3.createCell((short) 3).setCellValue("所在组织架构");
				row3.createCell((short) 4).setCellValue("用户状态");

				// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
				for (int i = 0; i < list.size(); i++){
				    row = sheet.createRow(i + 3);
				    AccountVO acc = new AccountVO();
				    acc=list.get(i);

					// 第四步，创建单元格，并设置值
					row.createCell((short) 0).setCellValue(acc.getName());
					row.createCell((short) 1).setCellValue(acc.getFullName());
					row.createCell((short) 2).setCellValue(acc.getOrgName());
					logger.info("组织id：{}",acc.getOrgId());
					row.createCell((short) 3).setCellValue(accountOrgFullNameMap.get(acc.getOrgId()));
					row.createCell((short) 4).setCellValue(acc.getEnabled()?"开通":"未开通");
					//taskDetail(taskContext.getTaskId(), assignmentQXVO.getName()+"导出数据第+"+(i+1)+"+行成功");
				}
				
				String fileName = assignmentQXVO.getName()+df2.format(submitTime)+".xls";
				String requestPath= FileConstant.SAVE_PATH;
				File fileDir=new File(requestPath);
				if(!fileDir.exists()) {
					fileDir.mkdir();
				}
				String path = requestPath+fileName;
				FileOutputStream os=null;
				File file=null;
				try {
					os= new FileOutputStream(path);
					wb.write(os);
					//阿里云返回url
					upLoadUrl = OssUpload.upload(path, fileName);
					file=new File(path);
					success(taskContext,"成功",upLoadUrl);
				} catch (Exception e1) {
					e1.printStackTrace();
					fail(taskContext, "写入过程中发生错误");
					logger.error("作业导出过程中发生错误，请查看日志");
				} 
				finally {
					if(os!=null) {
					   os.close();
					}
					if(wb!=null) {
					   wb.close();
					}
					if(file!=null) {
					   file.delete();
					}
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				fail(taskContext, assignmentQXVO.getName()+"作业导出过程中发生错误，请查看日志");	
				logger.error("作业导出过程中发生错误，请查看日志");
			}
		return upLoadUrl;
	}

}
