/**
 * 版权所有 ©2021 莱欧有限公司
 * 工程名：yearBooks
 * 文件名：NyzbYdhxhService.java
 * 创建日期：2021年10月25日 下午3:58:15
 * 作者：mt.W
 */
package com.lion.service;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.lion.dao.NyzbYdhxhDao;
import com.lion.dao.OrganizationTreeDao;
import com.lion.entity.LoginUserInfo;
import com.lion.entity.NyzbYdhxh;
import com.lion.util.CheckUtil;
import com.lion.util.ExcelUtil;
import com.lion.util.TimeUtil;
import com.lion.util.Util;

import jodd.util.StringUtil;

/**
 * 类描述   农业技术装备统计指标-用电与农业化学化Service
 * @author mt.W
 * @since 2021年10月25日
 */
@Service
public class NyzbYdhxhService {

	@Autowired
	private NyzbYdhxhDao dao;
	@Autowired
	private OrganizationTreeDao oDao;
	
	public Map<String, Object> getRecordList(String rows,String page,String year,String orgid){
		int row=Integer.valueOf(rows);
		int start=(Integer.valueOf(page)-1)*row;
		List<Map<String,Object>> list=dao.getRecordList(start, row, year, orgid);
		int count=dao.getRecordCount(year, orgid);
		Map<String,Object> map=Util.responseMap("true", list, count);
		int totalpages=count/row;
		if(count%row!=0){
			totalpages++;
		}
		map.put("currPage", page);
		map.put("totalpages",totalpages);
		return map;
	}
	
	public Map<String,Object> saveRecord(NyzbYdhxh n,String userid,String orgid){
		n.setOrgid(orgid);
		int check=dao.checkIfExistByYearAndOrg(n);
		if(check>0){
			return Util.responseMap("false", n.getYear()+"年度的数据已存在，无需再次录入");
		}
		int count = 0;
		if(StringUtil.isNotEmpty(n.getId())){
			n.setUpdateTime(TimeUtil.getNowTime());
			n.setUpdateUser(userid);
			count = dao.editRecord(n);
		}else{
			
			n.setCreateTime(TimeUtil.getNowTime());
			n.setCreateUser(userid);
			count = dao.addRecord(n);
		}
		return Util.responseMap(count);
	}
	public Map<String,Object> deleteRecord(String id){
		int count = dao.deleteRecord(id);
		return Util.responseMap(count);
	}
	public Map<String,Object> exprotRecord(HttpServletRequest req,String year,String orgid){
		List<Map<String, Object>> list = dao.getRecordList(year, orgid);
		String[] title={"部门","年度","农村用电量(万千瓦时)","农用化肥施用量(万吨)","氮肥(万吨)","磷肥(万吨)","钾肥(万吨)","复合肥(万吨)","农用塑料薄膜使用量(吨)"};
		String[] cellValue={"orgname","year","ncydl","nyhfsyl","df","lf","jf","fhf","nyslbm"};
		String path=ExcelUtil.exportExcel(title, cellValue, list, "农业机械年末拥有量", req);
		return Util.responseMap("true","操作成功", path);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public Map<String,Object> importData(MultipartFile file,LoginUserInfo user){
		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Workbook work = ExcelUtil.getWorkbook(in, file.getOriginalFilename());// 根据文件后缀，自适应上传文件的版本
		if (null == work) {// 判定格式不支持
			return Util.responseMap("false", "创建工作簿失败，excel表格格式不支持","");
		}
		Sheet sheet = work.getSheetAt(0);// 获取第一个工作表
		Row row = null;
		if(sheet.getLastRowNum()<1){// 解析excel不足两行，说明是空表格
			return Util.responseMap("false", "无数据可导入");
		}
		int cellNum=sheet.getRow(0).getLastCellNum();// 获取工作表中第3行最后一个单元格编号
		if(cellNum!=9){// 不等于9代表跟预设模板格式不符
			return Util.responseMap("false", "excel表格式错误，请下载模板");
		}
		List<NyzbYdhxh> list = new ArrayList<NyzbYdhxh>();
		// 遍历当前sheet中的所有行
		List<Map<String,Object>> orgdeptList = new ArrayList<Map<String,Object>>();
		Map<String,Object> orgMap = new HashMap<String, Object>();
		if(user.getOrgid().length()==2){//市级
			orgdeptList = oDao.getAllOrgdeptNode();
			for(Map<String,Object> o:orgdeptList){
				orgMap.put(o.get("text").toString(), o.get("id"));
			}
		}
		for(int j = 1; j < sheet.getLastRowNum() + 1; j++){// 从第2行开始遍历
			NyzbYdhxh i = new NyzbYdhxh();
			i.setCreateTime(TimeUtil.getNowTime());
			i.setCreateUser(user.getUserId());
			row = sheet.getRow(j); // 获取第j行
			// 遍历所有的列
			if(user.getOrgid().length()>2){
				i.setOrgid(user.getOrgid());
			}else{
				String orgname = row.getCell(0) == null ?"":row.getCell(0).toString();
				if(StringUtil.isEmpty(orgname)){
					return Util.responseMap("false", "第"+(j+1)+"行,区县必填");
				}
				if(orgMap.get(orgname.toString().replaceAll(" ", ""))==null){
					return Util.responseMap("false", "第"+(j+1)+"行,区县不存在");
				}
				i.setOrgid(orgMap.get(orgname.trim()).toString());
			}
			String year = row.getCell(1) == null ?"":row.getCell(1).toString();
			if(StringUtil.isEmpty(year)){
				return Util.responseMap("false", "第"+(j+1)+"行,年度必填");
			}
			if(year.indexOf(".")>0){
				year=year.substring(0,year.indexOf("."));
			}
			if(year.length()!=4||!CheckUtil.checkStrIsNum(year)){
				return Util.responseMap("false", "第"+(j+1)+"行,年度请输入4位数字");
			}
			i.setYear(year);
			try{
				BigDecimal ncydl=row.getCell(2) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(2).getNumericCellValue());
				i.setNcydl(ncydl+"");
				BigDecimal nyhfsyl=row.getCell(3) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(3).getNumericCellValue());
				i.setNyhfsyl(nyhfsyl+"");
				BigDecimal nyslbm=row.getCell(8) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(8).getNumericCellValue());
				i.setNyslbm(nyslbm+"");
				BigDecimal df=row.getCell(4) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(4).getNumericCellValue());
				i.setDf(df+"");
				BigDecimal lf=row.getCell(5) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(5).getNumericCellValue());
				i.setLf(lf+"");
				BigDecimal jf=row.getCell(6) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(6).getNumericCellValue());
				i.setJf(jf+"");
				BigDecimal fhf=row.getCell(7) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(7).getNumericCellValue());
				i.setFhf(fhf+"");
			}catch(Exception e){
				e.printStackTrace();
				return Util.responseMap("true", "第"+(j+1)+"行，请输入数字");
			}
			list.add(i);
		}
		int count=0;
		if(list.size()>0){
			for(NyzbYdhxh i:list){
				count=dao.checkIfExistByYearAndOrg(i);
				if(count>0){
					return Util.responseMap("false", i.getYear()+"年度的数据已存在，无需再次录入");
				}
				dao.addRecord(i);
			}
		}
		return Util.responseMap(1);
			
	}		
	
}
