package com.goafanti.demandCollection.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
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.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ser.std.StdJdkSerializers;
import com.goafanti.common.bo.Error;
import com.goafanti.common.dao.DemandCollectionMapper;
import com.goafanti.common.dao.SkjtUserMapper;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.DemandCollection;
import com.goafanti.common.model.SkjtUser;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demandCollection.bo.InputDemandCollection;
import com.goafanti.demandCollection.bo.InputUserList;
import com.goafanti.demandCollection.bo.OutDemandCollection;
import com.goafanti.demandCollection.bo.OutUserList;
import com.goafanti.demandCollection.bo.SkjtConstants;
import com.goafanti.demandCollection.service.DemandCollectionService;

@Service
public class DemandCollectionServiceImpl extends BaseMybatisDao<DemandCollectionMapper> implements DemandCollectionService {

	protected final Log logger = LogFactory.getLog(DemandCollectionServiceImpl.class);
	@Autowired
	private DemandCollectionMapper	demandCollectionMapper;
	@Autowired
	private SkjtUserMapper	skjtUserMapper;
	
	@Resource(name = "passwordUtil")
	private PasswordUtil	passwordUtil;
	
	@Override
	public int addDemandCollection(DemandCollection d) {
		String aid=UUID.randomUUID().toString();
		SkjtUser su=new SkjtUser();
		SkjtUser user = skjtUserMapper.selectByAccount(d.getDwmc());
		if (user==null) {
			su.setId(aid);
			su.setAccount(d.getDwmc());
			su.setPassword("123456");
			Calendar c=Calendar.getInstance();
			c.set(Calendar.MILLISECOND, 0);
			su.setCreateTime(c.getTime());
			su.setNickname(d.getDwmc());
			su.setPassword(passwordUtil.getEncryptPwd(su));
			skjtUserMapper.insertSelective(su);
			skjtUserMapper.setUserRole(su.getId());
			d.setAid(aid);
		}else {
			d.setAid(user.getId());
		}
		return demandCollectionMapper.insertSelective(d);
	}
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutDemandCollection> demandCollectionList(InputDemandCollection i) {
		Map<String, Object> map=new HashMap<>();
		if(StringUtils.isNotBlank(i.getDwmc()))map.put("dwmc", i.getDwmc());
		if(StringUtils.isNotBlank(i.getDwxz()))map.put("dwxz", i.getDwxz());
		if(StringUtils.isNotBlank(i.getYysjjyspt()))map.put("yypt", i.getYysjjyspt());
		if(StringUtils.isNotBlank(i.getHtly()))map.put("htly", i.getHtly());
		if(StringUtils.isNotBlank(i.getStartTime())&&StringUtils.isNotBlank(i.getEndTime())) {
			map.put("startTime", i.getStartTime());
			map.put("endTime", i.getEndTime()+" 23:59:59");
		}
		if(StringUtils.isNotBlank(i.getHtly()))map.put("htly", i.getHtly());
		if(StringUtils.isNotBlank(i.getRygm()))map.put("rygm", i.getRygm());
		if(StringUtils.isNotBlank(i.getJjgm()))map.put("jjgm", i.getJjgm());
		if(StringUtils.isNotBlank(i.getSsszp()))map.put("ssszp", i.getSsszp());
		if(StringUtils.isNotBlank(i.getSsszc()))map.put("ssszc", i.getSsszc());
		if(StringUtils.isNotBlank(i.getSssza()))map.put("sssza", i.getSssza());
		if (TokenManager.hasRole(SkjtConstants.YBYH)) {
			map.put("aid", TokenManager.getAdminId());
		}else if (TokenManager.hasRole(SkjtConstants.DQGLY)) {
			SkjtUser su=skjtUserMapper.selectByPrimaryKey(TokenManager.getAdminId());
			map.put("region", su.getRegion());
		}
		return (Pagination<OutDemandCollection>) findPage("findDemandCollectionList","findDemandCollectionCount",
				map, i.getPageNo(), i.getPageSize());
	}
	@SuppressWarnings("unchecked")
	@Override
	public void exportDemandCollectionList(HttpServletResponse response, InputDemandCollection idc) throws IOException {
		OutputStream out = response.getOutputStream();
		try {
			String[] comment = { "编号", "单位名称", "单位性质", "行业领域", "所属市州", "所属园区", "拥有的省级及以上平台", "法人代表", "统一社会信用代码", "经济规模",
					"人员规模", "成立时间", "注册资本", "通讯地址", "邮编", "联系人", "联系电话", "email", "主营业务及核心产品（服务）", "2018年度项目主营业务收入（万元）",
					"2018年度项目净利润（万元）", "2019年度项目主营业务收入（万元）", "2019年度项目净利润（万元）", "年度研发投入", "年度研发投入占营业收入比例", "是否曾获银行贷款",
					"银行贷款", "是否为高新技术企业编号 ", "高企证书编号 ", "是否为科技型中小企业", "科企证书编号", "专利数量", "发明专利", "实用新型", "是否曾获科技专项资金",
					"是否有产学研合作", "是否已获机构投资者投资 ", "成果名称", "成果领域", "成果属性", "成果体现形式", "成果成熟度", "成果知识产权形式", "知识产权权属 ",
					"专利状态", "成果登记情况", "拟采取成果转移转化方式自主转化 ", "拟采取成果转移转化方式合作开发 ", "拟采取成果转移转化方式技术转让 ", "预计可转移转化时间", "成果简述",
					"是否有成果合作需求", "是否有意向合作单位", "意向合作单位", "意向合作方式", "企业已展开的国际与区域科技创新合作方式", "主要合作方式 ", "已享受的科技政策",
					"拟申请的省级项目", "是否授权省科技主管部门将上述有关信息对外公开发布", "技术负责人", "技术负责人手机", "需求名称", "需求类别", "技术需求类型", "需求领域",
					"目前产品技术现状", "研发难点", "预期达到的效果（主要技术指标、技术成熟度、条件、成本等）", "已经开展的工作", "现有研发条件情况（人员情况、仪器设备投入等）",
					"目前合作对象情况（合作对象、方式、已投入研发资金情况等）", "是否有下一步合作需求", "意向合作对象", "合作单位名称", "拟采取的合作方式", "需求解决截止时间",
					"需求是否可以公开 ", "为解决技术难题能提供的合作资金", "资金用途", "资金缺口", "需求解决方式", "企业产品是否有销往国外", "企业产品是否有意向出口", "创建时间" };
    		String fileName ="需求征集表" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + ".xls";
    		XSSFWorkbook wb =ExportExcelUtil.exportTemplateInfoS(comment,"需求征集表");
    		//根据列表编写文档
    		XSSFSheet sheet =wb.getSheetAt(0);
    		XSSFCellStyle styleTitle = wb.createCellStyle();
			styleTitle.setAlignment(HorizontalAlignment.CENTER);
			styleTitle.setWrapText(true);
			int x=0;
    		for (OutDemandCollection ob : (List<OutDemandCollection>)demandCollectionList(idc).getList()) {
    			//新增一行
    			XSSFRow r = sheet.createRow(sheet.getLastRowNum()+1);
    			for (int i = 0; i < comment.length; i++) {
    				//当前列的只
    				String o = "";
    					switch (comment[i]) {
    					case "编号" : o = ob.getId(); break; 
    					case "单位名称" : o = ob.getDwmc(); break;
    					case "单位性质" : o = ob.getDwxz(); break; 
    					case "行业领域" : o = ob.getHtly(); break; 
    					case "所属市州" : o = ob.getSsszc()+"-"+ob.getSssza(); break; 
    					case "所属园区" : o = ob.getSsyq(); break; 
    					case "拥有的省级及以上平台" : o = ob.getYysjjyspt(); break;
    					case "法人代表" : o = ob.getFrdb(); break; 
    					case "统一社会信用代码" : o = ob.getYysjjyspt(); break; 
    					case "经济规模" : o = ob.getJjgm(); break; 
    					case "人员规模" : o = ob.getRygm(); break;
    					case "成立时间" : o = ob.getClsj(); break; 
    					case "注册资本" : o = ob.getZczb(); break; 
    					case "通讯地址" : o = ob.getTxdz(); break; 
    					case "邮编" : o = ob.getYb(); break; 
    					case "联系人" : o = ob.getLxr(); break; 
    					case "联系电话" : o = ob.getLxdh(); break; 
    					case "email" : o = ob.getEmail(); break; 
    					case "主营业务及核心产品（服务）" : o = ob.getZyywjhxcp(); break; 
    					case "2018年度项目主营业务收入（万元）" : o = ob.getNdxmzyywsr18(); break; 
    					case "2018年度项目净利润（万元）" : o = ob.getNdxmjlr18(); break; 
    					case "2019年度项目主营业务收入（万元）" : o = ob.getNdxmzyywsr19(); break; 
    					case "2019年度项目净利润（万元）" : o = ob.getNdxmjlr19(); break; 
    					case "年度研发投入" : o = ob.getNdyftr(); break; 
    					case "年度研发投入占营业收入比例" : o = ob.getNdyftrzyysrbl(); break; 
    					case "是否曾获银行贷款" : o = ob.getSfchyhdk(); break;
    					case "银行贷款" : o = ob.getSfchyhdkValue(); break;
    					case "是否为高新技术企业编号 " : o = ob.getSfwgxjsqy(); break;
    					case "高企证书编号 " : o = ob.getSfwgxjsqyValue(); break;
    					case "是否为科技型中小企业" : o = ob.getSfwkjxzxqy(); break;
    					case "科企证书编号" : o = ob.getSfwkjxzxqyValue(); break;
    					case "专利数量" : o = ob.getZlsl(); break; 
    					case "发明专利" : o = ob.getZlslFmzl(); break; 
    					case "实用新型" : o = ob.getZlslSyxx(); break; 
    					case "是否曾获科技专项资金" : o = ob.getSfchkjzxzj(); break; 
    					case "是否有产学研合作" : o = ob.getSfycxyz(); break;
    					case "产学研合作" : o = ob.getSfycxyzValue(); break;
    					case "是否已获机构投资者投资 " : o = ob.getSfyhjgtzztz(); break;
    					case "机构投资者投资 " : o = ob.getSfyhjgtzztzValue(); break;
    					case "成果名称" : o = ob.getCgmc(); break;
    					case "成果领域" : o = ob.getCgly(); break; 
    					case "成果属性" : o = ob.getCgsx(); break; 
    					case "成果体现形式" : o = ob.getCgtxxs(); break; 
    					case "成果成熟度" : o = ob.getCgcsd(); break; 
    					case "成果知识产权形式" : o = ob.getCgzscqxs(); break; 
    					case "知识产权权属 " : o = ob.getZscqqs(); break; 
    					case "专利状态" : o = ob.getZlzt(); break; 
    					case "成果登记情况" : o = ob.getCgdjqk(); break;
    					case "成果登记编号" : o = ob.getCgdjqkValue(); break;
    					case "拟采取成果转移转化方式自主转化 " : o = ob.getNcqcgzyzhfszzzh(); break; 
    					case "拟采取成果转移转化方式合作开发 " : o = ob.getNcqcgzyzhfshzkf(); break; 
    					case "拟采取成果转移转化方式技术转让 " : o = ob.getNcqcgzyzhfsjszr(); break; 
    					case "预计可转移转化时间" : o = ob.getYjkzyzhsj(); break; 
    					case "成果简述" : o = ob.getCgjs(); 
    					if (x==0)sheet.setColumnWidth(i, 20000);
    					break; 
    					case "是否有成果合作需求" : o = ob.getSfycghzxq(); break; 
    					case "是否有意向合作单位" : o = ob.getSfyyxhzdw(); break;
    					case "意向合作单位" : o = ob.getSfyyxhzdwValue(); break;
    					case "意向合作方式" : o = ob.getYxhzfs(); break;
    					case "企业已展开的国际与区域科技创新合作方式" : o = ob.getQyyzkdgjqykjcxhzqk();
    					if (x==0)sheet.setColumnWidth(i, 20000);
    					break;
    					case "主要合作方式 " : o = ob.getZyhzfs(); break;
    					case "已享受的科技政策" : o = ob.getYssdkjzc(); break;
    					case "拟申请的省级项目" : o = ob.getNsqdsjxm(); break; 
    					case "是否授权省科技主管部门将上述有关信息对外公开发布" :
    						if (ob.getSqskjzgbmxxdwgkfb()!=null) {
    							o = ob.getSqskjzgbmxxdwgkfb().replace("\n", String.valueOf((char)10)); 
    						}
    						if (x==0)sheet.setColumnWidth(i, 10000);
    						break;
    					case "技术负责人" : o = ob.getJsfzr(); break; 
    					case "技术负责人手机" : o = ob.getJsfsj(); break; 
    					case "需求名称" : o = ob.getXqmc(); break; 
    					case "需求类别" : o = ob.getXqbl(); break; 
    					case "技术需求类型" : o = ob.getJsxqlx(); break; 
    					case "需求领域" : o = ob.getXqly(); break; 
    					case "目前产品技术现状" : o = ob.getMqcpjsxz();
    					if (x==0)sheet.setColumnWidth(i, 10000);
    					break; 
    					case "研发难点" : o = ob.getYfnd(); 
    					if (x==0)sheet.setColumnWidth(i, 10000);
    					break;
    					case "预期达到的效果（主要技术指标、技术成熟度、条件、成本等）" : o = ob.getYqdddxg(); 
    					if (x==0)sheet.setColumnWidth(i, 10000);
    					break; 
    					case "已经开展的工作" : o = ob.getYjzkdgz(); 
    					if (x==0)sheet.setColumnWidth(i, 10000);
    					break; 
    					case "现有研发条件情况（人员情况、仪器设备投入等）" : o = ob.getXyyftjqk();
    					if (x==0)sheet.setColumnWidth(i, 20000);
    					break; 
    					case "目前合作对象情况（合作对象、方式、已投入研发资金情况等）" : o = ob.getMqhzdxqk(); 
    					if (x==0)sheet.setColumnWidth(i, 20000);
    					break; 
    					case "是否有下一步合作需求" : o = ob.getSfyxybhzxq(); break; 
    					case "意向合作对象" : o = ob.getYxhzdx(); break; 
    					case "合作单位名称" : o = ob.getYxhzdxValue(); break;
    					case "拟采取的合作方式" : o = ob.getNcqdhzfs(); break; 
    					case "需求解决截止时间" : o = ob.getXqjjjzsj(); break; 
    					case "为解决技术难题能提供的合作资金" : o = ob.getWjjjsntntgdhzzj(); break; 
    					case "资金用途" : o = ob.getZjyt(); break; 
    					case "资金缺口" : o = ob.getZjqk(); break; 
    					case "需求解决方式" : o = ob.getXqjjfs(); break; 
    					case "企业产品是否有销往国外": o = ob.getSfxwgw(); break;
    					case "企业产品是否有意向出口": o = ob.getSfyxck(); break;
    					case "创建时间": o = ob.getCreateTime(); break;
    					default: o = ""; break;
    				}
    				XSSFCell c = r.createCell(i);
    				c.setCellStyle(styleTitle);
    				c.setCellValue(o);
    			}
    			x++;
    		}
    		//冻结
    		sheet.createFreezePane(2, 2, 2, 2);
    		//返回名称及参数
			 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();
			throw new BusinessException(new Error("表格生成错误。"),e);
		}finally {
			out.flush(); 
			 out.close(); 
		}
	}
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<OutUserList> userList(InputUserList in) {
		Map<String, Object> map=new HashMap<>();
		if(StringUtils.isNotBlank(in.getAccount()))map.put("account", in.getAccount());
		if(StringUtils.isNotBlank(in.getName()))map.put("name", in.getName());
		return (Pagination<OutUserList>) findPage("findUserList","findUserCount",
				map, in.getPageNo(), in.getPageSize());
	}
	@Override
	public int updateUserPassword( String account,String usedPassword, String newPassword) {
		SkjtUser  s;
		if (TokenManager.hasRole(SkjtConstants.GLY)) {
			s=skjtUserMapper.selectByAccount(account);
		}else {
			s=skjtUserMapper.selectByPrimaryKey(TokenManager.getAdminId());
		}
		if (s!=null) {
			String up=s.getPassword();
			String np="";
			Calendar c=Calendar.getInstance();
			c.setTime(s.getCreateTime());
			c.set(Calendar.MILLISECOND, 0);
			s.setCreateTime(c.getTime());
			s.setPassword(usedPassword);
			np=passwordUtil.getEncryptPwd(s);
			s.setPassword(newPassword);
			if (np.equals(up)) {
				SkjtUser us=new SkjtUser();
				us.setId(s.getId());
				us.setPassword(passwordUtil.getEncryptPwd(s));
				skjtUserMapper.updateByPrimaryKeySelective(us);
				return 1;
			}
		}
		
		return 0;
	}
}
