package com.goafanti.order.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goafanti.common.bo.EmailBo;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.paymentNodeEmailBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.BusinessProjectMapper;
import com.goafanti.common.dao.NewOrderDunMapper;
import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.dao.OrganizationContactBookMapper;
import com.goafanti.common.dao.OrganizationIdentityMapper;
import com.goafanti.common.dao.PaymentNodeMapper;
import com.goafanti.common.dao.TArrearsDunMapper;
import com.goafanti.common.dao.TOrderBonusMapper;
import com.goafanti.common.dao.TOrderLogMapper;
import com.goafanti.common.dao.TOrderMidMapper;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.dao.TOrderTaskMapper;
import com.goafanti.common.dao.TTaskHoursMapper;
import com.goafanti.common.dao.TTaskLogMapper;
import com.goafanti.common.dao.TTaskMidMapper;
import com.goafanti.common.dao.TaskHoursCountMapper;
import com.goafanti.common.dao.TaskLogMapper;
import com.goafanti.common.dao.TaskProgressMapper;
import com.goafanti.common.dao.UserBusinessMapper;
import com.goafanti.common.dao.UserLockReleaseMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.OrderLogProcess;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.BusinessProject;
import com.goafanti.common.model.Notice;
import com.goafanti.common.model.OrganizationContactBook;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.TArrearsDun;
import com.goafanti.common.model.TOrderBonus;
import com.goafanti.common.model.TOrderLog;
import com.goafanti.common.model.TOrderMid;
import com.goafanti.common.model.TOrderNew;
import com.goafanti.common.model.TOrderTask;
import com.goafanti.common.model.TTaskHours;
import com.goafanti.common.model.TTaskLog;
import com.goafanti.common.model.TTaskMid;
import com.goafanti.common.model.TaskHoursCount;
import com.goafanti.common.model.TaskLog;
import com.goafanti.common.model.TaskProgress;
import com.goafanti.common.model.UserBusiness;
import com.goafanti.common.model.UserLockRelease;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.common.utils.SendEmailUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.OutNewOrderDunBo;
import com.goafanti.order.bo.TOrderTaskBo;
import com.goafanti.order.bo.TOrderTaskDetailBo;
import com.goafanti.order.bo.TOrderTaskListBo;
import com.goafanti.order.bo.TaskLogBo;
import com.goafanti.order.bo.TaskProgressBo;
import com.goafanti.order.bo.inuptTaskHoursListBo;
import com.goafanti.order.bo.inuptTaskListBo;
import com.goafanti.order.enums.BonusSubject;
import com.goafanti.order.enums.NewOrderDunType;
import com.goafanti.order.enums.OrderDunProjectType;
import com.goafanti.order.enums.OrderProjectStatus;
import com.goafanti.order.enums.ProcessStatus;
import com.goafanti.order.enums.ProjectNewStage;
import com.goafanti.order.service.OrderNewService;
import com.goafanti.order.service.OrderProjectService;
import com.goafanti.organization.bo.OutPaymentNode;
import com.goafanti.techproject.enums.TaskState;
@Service
public class OrderProjectServiceImpl extends BaseMybatisDao<TOrderTaskMapper> implements OrderProjectService {
	@Autowired
	private TOrderTaskMapper tOrderTaskMapper;
	@Autowired
	private TOrderNewMapper	tOrderNewMapper;
	@Autowired
	private TTaskHoursMapper	tTaskHoursMapper;
	@Autowired
	private TOrderBonusMapper 	tOrderBonusMapper;
	@Autowired
	private TTaskLogMapper	tTaskLogMapper;
	@Autowired
	private TOrderLogMapper	tOrderLogMapper;
	@Autowired
	private TaskProgressMapper	taskProgressMapper;
	@Autowired
	private OrganizationContactBookMapper	organizationContactBookMapper;
	@Autowired
	private OrganizationIdentityMapper	 organizationIdentityMapper;
	@Autowired
	private TaskLogMapper	taskLogMapper;
	@Autowired
	private OrderNewService	orderNewService;
	@Autowired
	private TaskHoursCountMapper	taskHoursCountMapper;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private BusinessProjectMapper	businessProjectMapper;
	@Autowired
	private NewOrderDunMapper	newOrderDunMapper;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Autowired
	private TArrearsDunMapper	tArrearsDunMapper;
	@Autowired
	private PaymentNodeMapper	paymentNodeMapper;
	@Autowired
	private NoticeMapper	noticeMapper;
	@Autowired
	private TTaskMidMapper	tTaskMidMapper;
	@Autowired
	private UserMapper	userMapper;
	@Autowired
	private UserLockReleaseMapper	userLockReleaseMapper;
	@Autowired
	private UserBusinessMapper	userBusinessMapper;
	@Value(value = "${upload.path}")
	private String 					uploadPath 			= null;
	
	Logger							logger	= LoggerFactory.getLogger(OrderProjectServiceImpl.class);
	
	@Override
	public int updateProjectDistribution(Integer taskId, String taskReceiverId,Integer specially,String remarks) {
		TOrderTask t=tOrderTaskMapper.selectByPrimaryKey(taskId);
		TOrderNew tn=checkDeleteSign(t.getOrderNo());
		Date date=new Date();
		t.setTaskStatus(TaskState.DISTRIBUTION.getCode());
		t.setTaskAllocator(TokenManager.getAdminId());
		t.setTaskReceiver(taskReceiverId);
		t.setTaskDistributionTime(date);
		Admin a=adminMapper.selectByPrimaryKey(taskReceiverId);
		if (a==null||a.getId()==null) {
			throw  new BusinessException(new Error("分配人员不存在！","分配人员不存在！"));
		}
		insetLog(taskId, taskReceiverId);
		//0-经理 （经理分派会创建子项目）1 管理员或经理转交
		if (specially==1) {
			addOrderLog(t.getOrderNo(), OrderLogProcess.XMDDPD.getCode(),remarks);
			t.setManagerId(taskReceiverId);
			t.setConsultantId(null);
			//设置催款触发
			TOrderNew b=tOrderNewMapper.selectByPrimaryKey(t.getOrderNo());
			if(b.getApproval()==0)orderNewService.pushOrderDun(t.getOrderNo());
			if (userMapper.checkLock(tn.getBuyerId())<1) {
				userMapper.updateShareType(tn.getBuyerId(),tn.getSalesmanId());
			}
			if (userLockReleaseMapper.checkLock(tn.getSalesmanId(),tn.getBuyerId(),t.getCommodityId())<1) {
				UserLockRelease ulr=new UserLockRelease();
				ulr.setId(UUID.randomUUID().toString());
				ulr.setBusinessProjectId(t.getCommodityId());
				ulr.setType(1);
				ulr.setUid(tn.getBuyerId());
				ulr.setAid(tn.getSalesmanId());
				ulr.setStatus(0);
				ulr.setLockTime(date);
				userLockReleaseMapper.insertSelective(ulr);
			}
				UserBusiness ub=new UserBusiness();
				ub.setId(UUID.randomUUID().toString());
				ub.setUid(tn.getBuyerId());
				ub.setAid(tn.getSalesmanId());
				ub.setFollowSituation(5);
				ub.setCustomerStatus(4);
				ub.setCreateTime(date);
				ub.setUpdateTime(date);
				ub.setRemarks("派单自动锁定客户");
				ub.setBusinessProjectId(t.getCommodityId());
				userBusinessMapper.insertSelective(ub);
		}else if (specially==0) {
			addOrderLog(t.getOrderNo(), OrderLogProcess.XMPD.getCode(),remarks);
			t.setConsultantId(taskReceiverId);
		//咨询师推给咨询师经理
		}else if(specially==2) { 
			t.setConsultantId(null);
		}
		t.setReceiverName(a.getName());
		tOrderTaskMapper.updateByPrimaryKey(t);
		List<String> aids = new ArrayList<>();
		aids.add(taskReceiverId);
		orderNewService.pushGeneralSendNoticeAndEmail(aids, NoticeStatus.ORDER_TASK_TO.getCode(),t.getOrderNo(), TokenManager.getAdminId(),0);
		
		checkProjiectAllocation(t.getOrderNo());
		return 1;
	}
	
	
	
	public TOrderNew checkDeleteSign(String orderNo) {
		TOrderNew t=tOrderNewMapper.selectByPrimaryKey(orderNo);
		if(t.getDeleteSign()==2||t.getDeleteSign()==3) throw new BusinessException(new Error(ErrorConstants.ORDER_ALREADY_REVOKE, t.getOrderNo(),""));
		return t;
	}
	public void addOrderLog(String orderNo, Integer code,String remarks) {
		TOrderLog tl=new TOrderLog();
		tl.setOrderNo(orderNo);
		tl.setProcess(code);
		tl.setAid(TokenManager.getAdminId());
		if(null!=remarks)tl.setRemarks(remarks);
		tOrderLogMapper.insertSelective(tl);
		
	}
	public void checkProjiectAllocation(String  orderNo) {
		List<TOrderTaskBo> taskBos=tOrderTaskMapper.selectOrderTask(orderNo);
		TOrderNew tNew=new TOrderNew();
		tNew.setOrderNo(orderNo);
		int i=0;
		for (TOrderTaskBo to : taskBos) {
			if (to.getTaskStatus()>TaskState.UN_DISTRIBUTION.getCode()&&to.getTaskStatus()<TaskState.INVALID.getCode()) {
				i++;
			}
			
		}
		if (i==taskBos.size()) {
			tNew.setProcessStatus(ProcessStatus.YQBFPZXSGLY.getCode());
		}else if(i>0&&i<taskBos.size()){
			tNew.setProcessStatus(ProcessStatus.YBFPZXSGLY.getCode());
		}else if(i==0){
			tNew.setProcessStatus(ProcessStatus.YPZXSGLY.getCode());
		}
		tOrderNewMapper.updateByPrimaryKeySelective(tNew);
	}

	private void insetLog(Integer taskId, String taskReceiverId) {
		TTaskLog tl=new TTaskLog();
		tl.setCreateTime(new Date());
		tl.setTaskId(taskId);
		tl.setTaskAllocator(TokenManager.getAdminId());
		tl.setTaskReceiver(taskReceiverId);
		tTaskLogMapper.insertSelective(tl);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderTaskListBo> orderTaskList(inuptTaskListBo ib) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(ib.getPageSize()==null||ib.getPageSize()<0)ib.setPageSize(10);
		if(ib.getPageNo()==null||ib.getPageNo()<0)ib.setPageNo(1);
		params.put("outsource", ib.getOutsource()==null?0:ib.getOutsource());
		if (null!=ib.getSpecially()) params.put("specially", ib.getSpecially());
		if (StringUtils.isNotBlank(ib.getName())) params.put("name", ib.getName());
		if (StringUtils.isNotBlank(ib.getDepId())) params.put("depId", ib.getDepId());
		if (StringUtils.isNotBlank(ib.getOrderNo())) params.put("orderNo", ib.getOrderNo());
		if (StringUtils.isNotBlank(ib.getContractNo())) params.put("contractNo", ib.getContractNo());
		if (ib.getProjectStatus() !=null ) params.put("projectStatus", ib.getProjectStatus());
		if (StringUtils.isNotBlank(ib.getTaskId())) params.put("taskId", ib.getTaskId());
		if (ib.getApproval() !=null) params.put("approval", ib.getApproval());
		if (StringUtils.isNotBlank(ib.getAdminName())) params.put("adminName", ib.getAdminName());
		if (StringUtils.isNotBlank(ib.getStartTime())) params.put("startTime", ib.getStartTime());
		if (StringUtils.isNotBlank(ib.getEndTime())) params.put("endTime", ib.getEndTime());
		if (null != ib.getTaskStatus()) params.put("taskStatus", ib.getTaskStatus());
		if (ib.getOutsourceStatus() !=null) params.put("outsourceStatus", ib.getOutsourceStatus());
		List<String> fids=new ArrayList<>();
		if (TokenManager.hasRole(AFTConstants.FINANCE_ADMIN) ||TokenManager.hasRole(AFTConstants.SUPERADMIN)||
				TokenManager.hasRole(AFTConstants.CED)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)||
				TokenManager.hasRole(AFTConstants.VICE_CEO)) {
			params.put("role", 2);
		}else if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)) {
			params.put("role", 1);
			fids =adminMapper.selectBySuperId(TokenManager.getAdminId());
			params.put("fids",fids);
		}else if (TokenManager.hasRole(AFTConstants.FINANCE)) {
			params.put("role", 1);
			 fids.add(TokenManager.getAdminId());
			 params.put("fids",fids);
		} else {
			params.put("role", 0);
			params.put("aid", TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		} 
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectOrderTaskListByPage", "selectOrderTaskListCount", params, ib.getPageNo(), ib.getPageSize());
		List<TOrderTaskListBo> list=(List<TOrderTaskListBo>) p.getList();
		for (TOrderTaskListBo t : list) {
			if(t.getSplitStatus()==1) {
				List<TOrderTaskListBo> l=splitProjectList(t.getId());
				t.setSplitList(l);
			}
		}
		return p;
	}

	@Override
	public TOrderTaskDetailBo orderTaskDetail(String id) {
		TOrderTaskDetailBo t=tOrderTaskMapper.getOrderTaskDetail(id);
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)
				||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION)||TokenManager.hasRole(AFTConstants.TECH_ADMIN)
					||TokenManager.getAdminId().equals(t.getTaskReceiver())) {
			return t;
		}else {
			t.setOutsourceName("****");
			t.setOutsourcePrice("****");
			t.setDeclareUser("****");
			t.setDeclarePwd("****");
			t.setCertificateNumber("****");
			return t;
		}
		
		
	}

	@Override
	@Transactional
	public int updateOrderTask(TOrderTaskDetailBo t) {
		TOrderTask task=new TOrderTask();
		TOrderNew tn=checkDeleteSign(t.getOrderNo());
		task.setAttachmentUrl(t.getAttachmentUrl());
		task.setId(Integer.valueOf(t.getId()));
		task.setTaskStatus(t.getTaskStatus());
		task.setProjectStatus(t.getProjectStatus());
		task.setTaskComment(t.getTaskComment());
		task.setCertificateNumber(t.getCertificateNumber());
		task.setStatus(t.getStatus());
		task.setFormRetrieve(t.getFormRetrieve());
		task.setTaskRefund(t.getTaskRefund());
		task.setRefundContent(t.getRefundContent());
		task.setRetrieveContent(t.getRetrieveContent());
		task.setDeclareUser(t.getDeclareUser());
		task.setDeclarePwd(t.getDeclarePwd());
		task.setArrivalMoney(t.getArrivalMoney());
		task.setSetUpAmount(t.getSetUpAmount());
		task.setOutsourceName(t.getOutsourceName());
		task.setDeclarationBatch(t.getDeclarationBatch());
		if(StringUtils.isNotBlank(t.getOutsourcePrice()))task.setOutsourcePrice(new BigDecimal(t.getOutsourcePrice()));
		//根据修改的修改订单法人与联系人
		if(StringUtils.isNotEmpty(t.getContacts()))tn.setContacts(t.getContacts());
		if(StringUtils.isNotEmpty(t.getContactMobile()))	tn.setContactMobile(t.getContactMobile());
		if(StringUtils.isNotEmpty(t.getLegalPerson()))tn.setLegalPerson(t.getLegalPerson());
		if(StringUtils.isNotEmpty(t.getLegalPersonTel()))tn.setLegalPersonTel(t.getLegalPersonTel());
		tOrderNewMapper.updateByPrimaryKeySelective(tn);
		//修改公司地址信息
		if (null!=t.getLocationProvince()||null!=t.getLocationArea()||null!=t.getLocationCity()||null!=t.getPostalAddress()) {
			OrganizationIdentity org=new OrganizationIdentity();
			org.setUid(tn.getBuyerId());
			org.setLocationProvince(t.getLocationProvince());
			org.setLocationArea(t.getLocationArea());
			org.setLocationCity(t.getLocationCity());
			org.setPostalAddress(t.getPostalAddress());
			organizationIdentityMapper.updateServiceByUid(org);
		}
		
		//修改公司联系人
		int adcount=organizationContactBookMapper.checkContacts(tn.getBuyerId(), t.getContactMobile(),tn.getSalesmanId());
		if (StringUtils.isNotBlank(t.getContacts())&&StringUtils.isNotBlank(t.getContactMobile())&&adcount<1) {
			OrganizationContactBook contactBook=new OrganizationContactBook();
			contactBook.setId(UUID.randomUUID().toString());
			contactBook.setAid(tn.getSalesmanId());
			contactBook.setUid(tn.getBuyerId());
			contactBook.setName(t.getContacts());
			contactBook.setMobile(t.getContactMobile());
			organizationContactBookMapper.insertSelective(contactBook);
		}
		//新增结算奖金信息
		checkSettlementAward(tn,task);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(StringUtils.isNotBlank(t.getStartDate()))task.setTaskStartTime(sdf.parse(t.getStartDate()));
			if(StringUtils.isNotBlank(t.getEndDate()))task.setTaskEndTime(sdf.parse(t.getEndDate()));
			if(StringUtils.isNotBlank(t.getAcceptDate()))task.setAcceptTime(sdf.parse(t.getAcceptDate()));
			if(StringUtils.isNotBlank(t.getReviewDate()))task.setReviewTime(sdf.parse(t.getReviewDate()));
			if(StringUtils.isNotBlank(t.getPublicityDate()))task.setPublicityTime(sdf.parse(t.getPublicityDate()));
			if(StringUtils.isNotBlank(t.getLicenceDate()))task.setLicenceTime(sdf.parse(t.getLicenceDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		TOrderTask task2=tOrderTaskMapper.selectByPrimaryKey(task.getId());//查询出项目信息
		tOrderTaskMapper.updateByPrimaryKeySelective(task);
		TaskLog tl=new TaskLog();
		tl.setCreateTime(new Date());
		tl.setTaskId(t.getId());
		tl.setAid(TokenManager.getAdminId());
		if (t.getStatus()!=null) {
			if (t.getStatus()!=task2.getStatus()) {
				String s="将当前项目状态修改为";
				if (t.getStatus()==0)s+="开启";
				if (t.getStatus()==1)s+="暂停";
				tl.setContent(s);
				taskLogMapper.insertSelective(tl);
			}
			if (t.getTaskRefund()!=task2.getTaskRefund()) {
				String s="将当前项目退单修改为";
				if (t.getTaskRefund()==0)s+="未完成";
				if (t.getTaskRefund()==1)s+="已完成";
				if (t.getTaskRefund()==2)s+="其他";
				tl.setContent(s);
				taskLogMapper.insertSelective(tl);
			}
			if (t.getFormRetrieve()!=task2.getFormRetrieve()) {
				String s="将当前满意度表格回收修改为";
				if (t.getFormRetrieve()==0)s+="未回收";
				if (t.getFormRetrieve()==1)s+="已回收";
				if (t.getFormRetrieve()==2)s+="其他";
				tl.setContent(s);
				taskLogMapper.insertSelective(tl);
			}
		}
		//项目触发发催款
		if (task2.getSplitStatus()==0) {
			pushOrderDunAndPaymentNode(t,task2);
		}else if (task2.getSplitStatus()==2){
			//查出父项目
			List<TOrderTaskListBo> list=tOrderTaskMapper.splitProjectList(task2.getSplitSuper());
			//设置一个比较大的流程数字，然后取最小的
			Integer i=OrderProjectStatus.XMJD10.getCode();
			for (TOrderTaskListBo tt : list) {
				if (tt.getProjectStatus()<i) i=tt.getProjectStatus();
			}
			TOrderTask fatherTask=new TOrderTask();
			fatherTask.setId(task2.getSplitSuper());
			fatherTask.setProjectStatus(i);
			tOrderTaskMapper.updateByPrimaryKeySelective(fatherTask);
			TOrderTask task3=tOrderTaskMapper.selectByPrimaryKey(task2.getSplitSuper());
			//设置父任务
			TOrderTaskDetailBo t2=new TOrderTaskDetailBo();
			t2.setOrderNo(t.getOrderNo());
			t2.setId(task2.getSplitSuper().toString());
			t2.setProjectStatus(task3.getProjectStatus());
			pushOrderDunAndPaymentNode(t2,task3);
		}
		
		if (task2.getSuperId()!=null) {//是否有父项目
			TOrderTask task3 =tOrderTaskMapper.selectBySuperId(task2.getSuperId());
			task3.setId(Integer.valueOf(task2.getSuperId()));
			task3.setSuperId(null);
			tOrderTaskMapper.updateByPrimaryKeySelective(task3);
			TOrderTask task4 = tOrderTaskMapper.selectByPrimaryKey(Integer.valueOf(task2.getSuperId()));
			meanwhileUpdateOrder(task4);
		}else {
			meanwhileUpdateOrder(task2);
		}
		return 1;
	}

	private void pushOrderDunAndPaymentNode(TOrderTaskDetailBo t,TOrderTask task2) {
		List<OutNewOrderDunBo> list=newOrderDunMapper.selectByTid(t.getId());
		for (OutNewOrderDunBo ob : list) {
			if (ob!=null) {
				boolean flag=false;
				if((ob.getProjectType()==OrderDunProjectType.CGZH.getCode()&&ob.getDunType()==2&&//成果转化 验收
						t.getProjectStatus()==OrderProjectStatus.XMYS.getCode()))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.COMMON.getCode()&&ob.getDunType()==2&&//通用 公示
						t.getProjectStatus()==OrderProjectStatus.XMGS.getCode()))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.COMMON.getCode()&&ob.getDunType()==3&&//通用 下证
						t.getProjectStatus()==OrderProjectStatus.XMXZ.getCode()))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.KJXM.getCode()&&ob.getDunType()==2&&//科技项目 立项或者公示
						(t.getProjectStatus()==OrderProjectStatus.XMLX.getCode()||(t.getProjectStatus()==OrderProjectStatus.XMGS.getCode()))))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.KJXM.getCode()&&ob.getDunType()==3&&//科技项目 拨款
						t.getProjectStatus()==OrderProjectStatus.XMBK.getCode()))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.KJJR.getCode()&&ob.getDunType()==2&&//科技金融 拨款
						t.getProjectStatus()==OrderProjectStatus.XMBK.getCode()))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.RJKF.getCode()&&ob.getDunType()==2&&//软件开发 立项
						t.getProjectStatus()==OrderProjectStatus.XMLX.getCode()))flag=true;
				if((ob.getProjectType()==OrderDunProjectType.RJKF.getCode()&&ob.getDunType()==3&&//软件开发 验收
						t.getProjectStatus()==OrderProjectStatus.XMYS.getCode()))flag=true;
				if(ob.getProjectType()==OrderDunProjectType.ZSCQ.getCode()){//知识产权 公示 专利受理、转让（项目已提交），软著下证
					if(ob.getDunType()==3&&t.getProjectStatus()==OrderProjectStatus.XMXZ.getCode()) {
						flag=true;
					}else if (ob.getDunType()==2) {
						BusinessProject bp=businessProjectMapper.selectByPrimaryKey(task2.getCommodityId());
						if (bp.getType()==0&&t.getProjectStatus()==OrderProjectStatus.XMGS.getCode()) {
							flag=true;
						}
						if (bp.getType()==1&&t.getProjectStatus()==OrderProjectStatus.XMYTJ.getCode()) {
							flag=true;
						}
						if (bp.getType()==2&&t.getProjectStatus()==OrderProjectStatus.XMXZ.getCode()) {
							flag=true;
						}
						
					}
				} 
					if(flag) {
					//如果启动催款，则新增欠款与应收款
					tOrderMidMapper.addOrderReceivables(t.getOrderNo(), ob.getMoney());
					TOrderMid tm=tOrderMidMapper.selectByOrderNo(t.getOrderNo());
						TArrearsDun td=new TArrearsDun();
						td.setOrderArrears(tm.getOrderArrears());
						td.setOrderReceivables(tm.getOrderReceivables());
						if (tArrearsDunMapper.checkOrderNo(t.getOrderNo(),null)<1) {
							td.setOrderNo(t.getOrderNo());
							tArrearsDunMapper.insertSelective(td);
						}else if(tArrearsDunMapper.checkOrderNo(t.getOrderNo(),0)>0){
							Integer i=tArrearsDunMapper.selectByStatus(t.getOrderNo(), 0);
							td.setId(i);
							tArrearsDunMapper.updateByPrimaryKeySelective(td);
						}
					orderNewService.addNewDunNoticAndSendEmail(t.getOrderNo(),ob);
					ob.setStatus(1);
					ob.setStartTime(new Date());
					newOrderDunMapper.updateByPrimaryKeySelective(ob);
					
				}
			}
		}
		List<OutPaymentNode> list2=paymentNodeMapper.selectByTid(Integer.parseInt(t.getId()),0);
		for (OutPaymentNode op : list2) {
			if (op!=null) {
				boolean flag=false;
				if((op.getProjectType()==OrderDunProjectType.CGZH.getCode()&&op.getDunType()==2&&//成果转化 验收
						t.getProjectStatus()==OrderProjectStatus.XMYS.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.COMMON.getCode()&&op.getDunType()==2&&//通用 公示
						t.getProjectStatus()==OrderProjectStatus.XMGS.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.COMMON.getCode()&&op.getDunType()==3&&//通用 下证
						t.getProjectStatus()==OrderProjectStatus.XMXZ.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.KJXM.getCode()&&op.getDunType()==2&&//科技项目 立项或者公示
						(t.getProjectStatus()==OrderProjectStatus.XMLX.getCode()||(t.getProjectStatus()==OrderProjectStatus.XMGS.getCode()))))flag=true;
				if((op.getProjectType()==OrderDunProjectType.KJXM.getCode()&&op.getDunType()==3&&//科技项目 拨款
						t.getProjectStatus()==OrderProjectStatus.XMBK.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.KJJR.getCode()&&op.getDunType()==2&&//科技金融 拨款
						t.getProjectStatus()==OrderProjectStatus.XMBK.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.RJKF.getCode()&&op.getDunType()==2&&//软件开发 立项
						t.getProjectStatus()==OrderProjectStatus.XMLX.getCode()))flag=true;
				if((op.getProjectType()==OrderDunProjectType.RJKF.getCode()&&op.getDunType()==3&&//软件开发 验收
						t.getProjectStatus()==OrderProjectStatus.XMYS.getCode()))flag=true;
				if(op.getProjectType()==OrderDunProjectType.ZSCQ.getCode()){//知识产权 公示 专利受理、转让（项目已提交），软著下证
					if(op.getDunType()==3&&t.getProjectStatus()==OrderProjectStatus.XMXZ.getCode()) {
						flag=true;
					}else if (op.getDunType()==2) {
						BusinessProject bp=businessProjectMapper.selectByPrimaryKey(task2.getCommodityId());
						if (bp.getType()==0&&t.getProjectStatus()==OrderProjectStatus.XMGS.getCode()) {
							flag=true;
						}
						if (bp.getType()==1&&t.getProjectStatus()==OrderProjectStatus.XMYTJ.getCode()) {
							flag=true;
						}
						if (bp.getType()==2&&t.getProjectStatus()==OrderProjectStatus.XMXZ.getCode()) {
							flag=true;
						}
						
					}
				} 
					if(flag)addNoticAndEmail( op,NoticeStatus.PAYMENT_DUN.getCode());
			}
		}
	}
	
	
	public void addNoticAndEmail(OutPaymentNode pn,Integer type) {
		paymentNodeEmailBo pnb=paymentNodeMapper.selectBytidGetEmail(pn.getTid());
		String str=NoticeStatus.getValueByCode(type)+": 订单编号 -"+pnb.getOrderNo()+"， 操作人:平台超管中心-管理员。";
		Notice n =new Notice();
		n.setId(UUID.randomUUID().toString());
		n.setAid(pnb.getSalesmanId());
		n.setNoticeType(type);
		n.setContent(str);
		n.setReaded(0);//未读
		noticeMapper.insertSelective(n);
		pn.setDunStatus(1);
		paymentNodeMapper.updateByPrimaryKeySelective(pn);
		//营销员名称、邮箱、订单编号、客户名称
		String dunTypeName=NewOrderDunType.getValueByCode(Integer.valueOf(""+pn.getProjectType()+pn.getDunType()));
			//发送驳回邮件
		if(SendEmailUtil.isEmail(pnb.getEmail())) {
	    	 EmailBo bo = new EmailBo("付款通知", pnb.getEmail(), "平台超管中心", "管理员",
						"", pnb.getOrderNo(),pn.getPartyTimes(),
						dunTypeName,pnb.getSalesmanName(),pnb.getUserName(),2,0);
				if(StringUtils.isNotBlank(pnb.getEmail())) {
					try {
						SendEmailUtil.getInstance().patentSend(bo);
					} catch (UnsupportedEncodingException | MessagingException e) {
						LoggerUtils.debug(logger, "=========================================发送邮件异常"); 
						e.printStackTrace();
					}
				}
	     }
	}
	
	private void checkSettlementAward(TOrderNew tn,TOrderTask task) {
		if(task.getTaskStatus()==TaskState.COMPLETE.getCode()&&tn.getTotalAmount().compareTo(tn.getSettlementAmount())==0) {
			List<TOrderTask> l = tOrderTaskMapper.getReceiverByOid(tn.getOrderNo());
			for (TOrderTask tOrderTask : l) {
				if(null != tOrderTask &&null != tOrderTask.getTaskReceiver()){
					TOrderBonus bonus = new TOrderBonus();
					bonus.setId(UUID.randomUUID().toString());
					bonus.setOrderNo(tn.getOrderNo());
					bonus.setGrantBy(tn.getFinanceId());
					bonus.setBonusSubject(BonusSubject.WK.getCode());//12
					bonus.setTaskId(tOrderTask.getId());//任务id
					bonus.setGrantTarget(tOrderTask.getTaskReceiver());
					bonus.setGrantType(1);
					int c = tOrderBonusMapper.checkByOnoAndSub(bonus);
					//不存在就设置
					if(c==0){
						bonus.setId(UUID.randomUUID().toString());
						tOrderBonusMapper.insertSelective(bonus);
					}
					
				}
				
			}
		}
	}

	private void meanwhileUpdateOrder(TOrderTask task) {
//		if (task.getMain()==1) {//是否是主要项目 更改为不管是不是主项目都会有奖金信息
			//更改订单项目状态
			TOrderNew tNew=new TOrderNew();
			tNew.setProjectStatus(task.getProjectStatus());
			tNew.setOrderNo(task.getOrderNo());
			tOrderNewMapper.updateByPrimaryKeySelective(tNew);
			if (task.getProjectStatus()==ProjectNewStage.YTJ.getCode()||task.getProjectStatus()==ProjectNewStage.LS.getCode()||
					task.getProjectStatus()==ProjectNewStage.GS.getCode()) {
				TOrderBonus tb=new TOrderBonus();
				TOrderNew t=tOrderNewMapper.selectByPrimaryKey(task.getOrderNo());
				tb.setId(UUID.randomUUID().toString());
				tb.setOrderNo(task.getOrderNo());
				if (task.getProjectStatus()==ProjectNewStage.YTJ.getCode()) {
					tb.setBonusSubject(21);//项目已提交
					addOrderLog(task.getOrderNo(),OrderLogProcess.XMWC.getCode(),null);
				}
				if (task.getProjectStatus()==ProjectNewStage.LS.getCode())tb.setBonusSubject(23);//项目立项
				if (task.getProjectStatus()==ProjectNewStage.GS.getCode())tb.setBonusSubject(24);//项目公示
				tb.setGrantType(1);//技术员
				//新增奖金之前检查这个奖金数据是否存在
				tb.setGrantTarget(task.getTaskReceiver());
				int c = tOrderBonusMapper.checkByOnoAndSub(tb);
				if(c==0){
					tb.setGrantBy(t.getFinanceId());
					tb.setTaskId(task.getId());
					tOrderBonusMapper.insertSelective(tb);
				}
				
			}
		
	}

	@Override
	public int addTaskHours(TTaskHours t) {
		TOrderTask tt=tOrderTaskMapper.selectByPrimaryKey(Integer.valueOf(t.getTaskId()));
		checkDeleteSign(tt.getOrderNo());
		t.setAid(TokenManager.getAdminId()==null?"1":TokenManager.getAdminId());
		t.setId(UUID.randomUUID().toString());
		t.setCreateTime(new Date());
		if(taskHoursCountMapper.selectByAidAndTid(TokenManager.getAdminId(),t.getTaskId())>0) {
			taskHoursCountMapper.updateByAidAndTid(TokenManager.getAdminId(),t.getTaskId(),t.getHours());
		}else {
			TaskHoursCount tc=new TaskHoursCount();
			tc.setAid(TokenManager.getAdminId());
			tc.setTid(Integer.valueOf(t.getTaskId()));
			tc.setHours(t.getHours());
			taskHoursCountMapper.insertSelective(tc);
		}
		return tTaskHoursMapper.insertSelective(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderTaskListBo> taskHoursList(inuptTaskHoursListBo ib, Integer pageNo,
			Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if (StringUtils.isNotBlank(ib.getName())) params.put("name", ib.getName());
		if (StringUtils.isNotBlank(ib.getOrderNo())) params.put("orderNo", ib.getOrderNo());
		if (StringUtils.isNotBlank(ib.getTaskId())) params.put("taskId", ib.getTaskId());
		if (StringUtils.isNotBlank(ib.getStarTime())) params.put("starTime", ib.getStarTime());
		if (StringUtils.isNotBlank(ib.getEndTime())) params.put("endTime", ib.getEndTime()+" 23:59:59");
		if(StringUtils.isNotBlank(ib.getContractNo()))params.put("contractNo", ib.getContractNo());
		if(StringUtils.isNotBlank(ib.getDepId()))params.put("depId", ib.getDepId());
		if(StringUtils.isNotBlank(ib.getCid()))params.put("cid", ib.getCid());
		if(null!=ib.getOutsource())params.put("outsource", ib.getOutsource());
		Integer i=null;
	if (TokenManager.hasRole(AFTConstants.FINANCE))i=1;
		if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER))i=2;
		if (TokenManager.hasRole(AFTConstants.FINANCE_ADMIN)||TokenManager.hasRole(AFTConstants.VICE_CEO)||
				TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.CED)||
				TokenManager.hasRole(AFTConstants.APPROVAL_DECISION))i=3;
		if(TokenManager.getAdminId()!=null)params.put("aid", TokenManager.getAdminId());
		if(i!=null)params.put("shiroType", i);
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectTaskHoursListByPage", "selectTaskHoursListCount", params, pageNo, pageSize);
		
		return p;
	}

	
	
	



	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderTaskListBo> selectTaskList(String name, String orderNo, String taskId, Integer taskStatus,
			String adminName, Integer specially,String depId  , Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		params.put("aid", TokenManager.getAdminId()==null?"":TokenManager.getAdminId());
		if (StringUtils.isNotBlank(name)) params.put("name", name);
		if (StringUtils.isNotBlank(depId)) params.put("depId", depId);
		if (StringUtils.isNotBlank(orderNo)) params.put("orderNo", orderNo);
		if (StringUtils.isNotBlank(taskId)) params.put("taskId", taskId);
		if (StringUtils.isNotBlank(adminName)) params.put("adminName", adminName);
		if (null != taskStatus) params.put("taskStatus", taskStatus);
		Pagination<TOrderTaskListBo> p = (Pagination<TOrderTaskListBo>)findPage("selectTaskListByPage", "selectTaskListCount", params, pageNo, pageSize);
		return p;
	}
	@Override
	public List<TaskLogBo> TaskLogList(Integer id) {
		return taskLogMapper.selectTaskLogList(id);
	}
	@Override
	public int createTaskProgress(TaskProgressBo t) {
		TaskProgress tp=new TaskProgress();
		TOrderTask tt=tOrderTaskMapper.selectByPrimaryKey(t.getTaskId());
		int count =taskProgressMapper.AlreadyNuberCount(t.getTaskId());
		count +=t.getAlreadyNumber();
		if(tt.getCommodityQuantity()<count)throw new BusinessException(new Error( "数量不能大于总量！" ,"数量不能大于总量！"));
		tp.setAlreadyNumber(t.getAlreadyNumber());
		tp.setLicenceTime(DateUtils.StringToDate(t.getLicenceTimes(), AFTConstants.YYYYMMDD));
		tp.setTaskId(t.getTaskId());
		return taskProgressMapper.insertSelective(tp);
	}
	@Override
	public int delectTaskProgress(Integer id) {
		return taskProgressMapper.deleteByPrimaryKey(id);
	}
	@Override
	public List<TaskProgressBo> selectTaskProgress(Integer tid) {
		List<TaskProgressBo>  l=taskProgressMapper.selectTaskProgress(tid);
		int notcount=0;
		for (TaskProgressBo t : l) {
			notcount+=t.getAlreadyNumber();
			t.setNotCount(t.getIngCount()-notcount);
		}
		return l;
	}
	
	@Override
	public List<TTaskHours> taskHoursDetailsList(String taskId) {
		String aid=TokenManager.getAdminId();
		return tTaskHoursMapper.taskHoursDetailsList(taskId,aid);
	}
	@Override
	public void exportMyTaskList(HttpServletResponse response,inuptTaskHoursListBo ib, Integer pageNo, Integer pageSize) throws IOException {
		OutputStream out = response.getOutputStream();
		try {
			if(pageSize==null)pageSize=999999;
			@SuppressWarnings("unchecked")
			List<TOrderTaskListBo> list=(List<TOrderTaskListBo>) taskHoursList(ib,  pageNo, pageSize).getList();
			//合同编号  订单编号  客户名称    订单部门  订单负责人      项目类别   项目编号   项目名称     项目负责人  项目价格（万元）    数量（个）       任务状态   项目状态    工时   签单时间    派单时间   分配时间   完成时间
    		String[] comment = {"合同编号","订单编号","客户名称","订单部门","订单负责人","项目类别","项目编号","项目名称","项目负责人","项目价格（万元）",
    				"数量（个）","任务状态","项目状态","是否外包","工时","签单日期","派单日期","分配时间","完成时间" ,"成本(万元)","已付(万元)" };
    		String fileName ="工时信息记录表" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
    		//type 0 变更
    		XSSFWorkbook wb =ExportExcelUtil.exportTemplateInfoS(comment,"工时信息");
    		//根据列表编写文档
    		XSSFSheet sheet =wb.getSheetAt(0);
    		for (TOrderTaskListBo ob : (List<TOrderTaskListBo>)list) {
    			//新增一行
    			XSSFRow r = sheet.createRow(sheet.getLastRowNum()+1);
    			for (int i = 0; i < comment.length; i++) {
    				//当前列的只
    				String o = "";
    				switch (comment[i]) {
//    "合同编号","订单编号","客户名称","订单部门","订单负责人 ","项目类别","项目编号","项目名称","项目负责人","项目价格（万元）",
//    				" 数量（个）","任务状态","项目状态","工时","签单日期","派单日期","分配时间","完成时间"
    				case "合同编号": o = ob.getContractNo(); break;
    				case "订单编号": o = ob.getOrderNo().toString(); break;
    				case "客户名称": o = ob.getUserName(); break;
    				case "订单部门": o = ob.getDepName(); break;
    				case "订单负责人": o = ob.getSalesmanName(); break;
    				case "项目类别": o =ob.getCname(); break;
    				case "项目编号": o = ob.getId().toString(); break;
    				case "项目名称": o = ob.getTaskName(); break;
    				case  "是否外包": o = ob.getOutsource()==1?"是":"否"; break;
    				case "项目负责人": o = ob.getReceiverName(); break;
    				case "项目价格（万元）": o = ob.getCommodityPrice().toString(); break;
    				case "数量（个）": o = ob.getCommodityQuantity().toString(); break;
    				case "任务状态": o = TaskState.getValueByCode(ob.getTaskStatus()); break;
    				case "项目状态": o = ProjectNewStage.getValueByCode(ob.getProjectStatus()); break;
    				case "工时": o = ob.getHours().toString(); break;
    				case "分配时间": o = ob.getTaskDistributionTime(); break;
    				case "完成时间": o = ob.getTaskEndTime(); break;
    				case "签单日期": o = ob.getSignTime(); break;
    				case "派单日期": o = ob.getCreteTime();break;
    				case "成本(万元)": o = ob.getCostAmount().toString(); break;
    				case "已付(万元)": o = ob.getPartyAmount().toString(); break;
    				default: o = ""; break;
    				}
    				XSSFCell c = r.createCell(i);
    				c.setCellValue(o);
    			}
    		}
    		//返回名称及参数
			 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
			 response.setContentType("application/octet-stream;charset=utf-8");
    		 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		} catch (Exception e) {
			throw new BusinessException(new Error("表格生成错误。"));
		}finally {
			out.flush(); 
			 out.close(); 
		}
		
	}
	
	@Override
	public int pushSplitProject(Integer tid, String splitList) {
			String[] str=splitList.split(",");
			TOrderTask task=tOrderTaskMapper.selectByPrimaryKey(tid);
			checkDeleteSign(task.getOrderNo());
			TOrderTask usedTask=new TOrderTask();
			usedTask.setId(tid);
			usedTask.setSplitStatus(1);
			//计算拆分数量
			Integer x=0;
			for (String string : str) {
				x+=Integer.parseInt(string);
			}
			if (!task.getCommodityQuantity().equals(x)||str.length==1) {
				return -1;
			}
			tOrderTaskMapper.updateByPrimaryKeySelective(usedTask);
			int i=1;
			TOrderTask newTask=task;
			newTask.setCommodityPrice(new BigDecimal(0));
			newTask.setSplitAid(TokenManager.getAdminId());
			newTask.setSplitStatus(2);
			newTask.setSplitSuper(tid);
			newTask.setSplitTime(new Date());
			for (String string : str) {
				newTask.setId(null);
				newTask.setCommodityQuantity(Integer.parseInt(string));
				newTask.setSplitId(i);
				i++;
				tOrderTaskMapper.insertSelectiveGetId(newTask);
				TTaskMid tm=new TTaskMid(newTask.getId(),null);
				tTaskMidMapper.insertSelective(tm);
			}
		return 1;
	}
	
	@Override
	public List<TOrderTaskListBo> splitProjectList(Integer tid) {
		return tOrderTaskMapper.splitProjectList(tid);
	}



	@Override
	public void exporProjectList(HttpServletResponse response, inuptTaskListBo ib)
			throws IOException {

		OutputStream out = response.getOutputStream();
		try {
			if(ib.getPageSize()==null)ib.setPageSize(99999);
			String str="项目任务列表";
			if (ib.getOutsource()!=null&&ib.getOutsource()==1)str="外包项目任务";
			@SuppressWarnings("unchecked")
			List<TOrderTaskListBo> list=(List<TOrderTaskListBo>) orderTaskList(ib).getList();
    		String[] comment = {"项目编号","项目名称","项目数量","订单编号","合同编号","业务类别","客户名称（软著/下证数）","分配状态",
    				"项目状态","外包审核","分配时间","订单部门","累计工时","项目金额","成本(万元)","已付(万元)" };
    		String fileName =str+"记录表" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
    		//type 0 变更
    		XSSFWorkbook wb =ExportExcelUtil.exportTemplateInfoS(comment,str);
    		//根据列表编写文档
    		XSSFSheet sheet =wb.getSheetAt(0);
    		for (TOrderTaskListBo ob : (List<TOrderTaskListBo>)list) {
    			//新增一行
    			XSSFRow r = sheet.createRow(sheet.getLastRowNum()+1);
    			for (int i = 0; i < comment.length; i++) {
    				//当前列的只
    				String o = "";
    				switch (comment[i]) {
//    {"项目编号","项目名称","项目数量","订单编号","合同编号","业务类别","客户名称（软著/下证数）","分配状态",
//    				"项目状态","外包审核","分配时间","订单部门","累计工时","项目金额","成本(万元)","已付(万元)" };
    				case "项目编号": o = ob.getId().toString(); break;
    				case "项目名称": o = ob.getTaskName(); break;
    				case "项目数量": o = ob.getCommodityQuantity().toString(); break;
    				case "订单编号": o = ob.getOrderNo(); break;
    				case "合同编号": o = ob.getContractNo(); break;
    				case "业务类别": o =ob.getCname(); break;
    				case "客户名称（软著/下证数）": o =ob.getUserName(); 
    					break;
    				case "分配状态": o = TaskState.getValueByCode(ob.getTaskStatus()); break;
    				case  "项目状态": o = ProjectNewStage.getValueByCode(ob.getProjectStatus()); break;
    				case "外包审核": o = ob.getOutsource()==1?"是":"否"; break;
    				case "分配时间": o = ob.getTaskDate(); break;
    				case "订单部门": o =ob.getDepName(); break; 
    				case "累计工时": o = ob.getHours().toString(); break;
    				case "项目金额": o = ob.getCommodityPrice().toString(); break;
    				case "成本(万元)": o = ob.getCostAmount().toString(); break;
    				case "已付(万元)": o = ob.getPartyAmount().toString(); break;
    				default: o = ""; break;
    				}
    				XSSFCell c = r.createCell(i);
    				c.setCellValue(o);
    			}
    		}
    		//返回名称及参数
			 response.addHeader("Content-Disposition", "attachment;filename="  + new String(fileName.getBytes(),"iso-8859-1"));  
			 response.setContentType("application/octet-stream;charset=utf-8");
    		 // 返回数据流
			 wb.write(out); 
			 out.flush();
			 out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			out.flush(); 
			 out.close(); 
		}
		
	
		
	}
	
	
}
