/**
 * 版权所有 ©2021 莱欧有限公司
 * 工程名：yearBooks
 * 文件名：ZzySgService.java
 * 创建日期：2021年10月28日 上午11:11:45
 * 作者：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.CommentDao;
import com.lion.dao.FruitDao;
import com.lion.dao.OrganizationTreeDao;
import com.lion.dao.ZzySgDao;
import com.lion.entity.LoginUserInfo;
import com.lion.entity.ZzySg;
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月28日
 */
@Service
public class ZzySgService {

	@Autowired
	private ZzySgDao dao;
	@Autowired
	private FruitDao fDao;
	@Autowired
	private CommentDao cDao;
	@Autowired
	private OrganizationTreeDao oDao;
	
	public Map<String, Object> getRecordList(String rows,String page,String year,String orgid){
		if(StringUtil.isEmpty(year)){
			List<Map<String,Object>> years = cDao.loadYears("zzy_sg");
			if(years.size()>0){
				year = years.get(0).get("year").toString();
			}
		}
		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;
	}
	@Transactional(rollbackFor=Exception.class)
	public Map<String,Object> saveAddSgInfo(List<ZzySg> datalist,String orgid,String userid){
		for(ZzySg n:datalist){
			n.setOrgid(orgid);
			int check=dao.checkDataIsExist(n);
			if(check>0){
				return Util.responseMap("false", n.getYear()+"年度"+n.getTypeName()+"的数据已存在，无需再次录入");
			}
		}
		for(ZzySg n:datalist){
			n.setOrgid(orgid);
			n.setCreateTime(TimeUtil.getNowTime());
			n.setCreateUser(userid);
			dao.addRecord(n);
		}
		return Util.responseMap(1);
	}
	public Map<String,Object> saveRecord(ZzySg n,String userid,String orgid){
		n.setOrgid(orgid);
		int check=dao.checkDataIsExist(n);
		if(check>0){
			return Util.responseMap("false", n.getYear()+"年度"+n.getTypeName()+"的数据已存在，无需再次录入");
		}
		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","typeName","bzmj","zcl"};
		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!=5){// 不等于5代表跟预设模板格式不符
			return Util.responseMap("false", "excel表格式错误，请下载模板");
		}
		List<Map<String,Object>> fruitList = fDao.getTypeList();
		Map<String,Object> fruitMap = new HashMap<String, Object>();
		for(Map<String,Object> f:fruitList){
			fruitMap.put(f.get("name").toString(), f.get("id"));
		}
		List<ZzySg> list = new ArrayList<ZzySg>();
		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"));
			}
		}

		// 遍历当前sheet中的所有行
		for(int j = 1; j < sheet.getLastRowNum() + 1; j++){// 从第2行开始遍历
			ZzySg i = new ZzySg();
			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);
			String fruitInfo = row.getCell(2) ==null?"":row.getCell(2).toString();
			if(fruitMap.get(fruitInfo)==null){
				return Util.responseMap("false", "第"+(j+1)+"行,水果类别不存在,请先添加该类别");
			}else{
				i.setTypeId(fruitMap.get(fruitInfo).toString());
			}
			try{
				BigDecimal bzmj=row.getCell(3) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(3).getNumericCellValue());
				i.setBzmj(bzmj+"");
				BigDecimal zcl=row.getCell(4) == null ? new BigDecimal(0.0) : BigDecimal.valueOf(row.getCell(4).getNumericCellValue());
				i.setZcl(zcl+"");
			}catch(Exception e){
				e.printStackTrace();
				return Util.responseMap("true", "第"+(j+1)+"行，请输入数字");
			}
			list.add(i);
		}
		int count=0;
		if(list.size()>0){
			for(ZzySg i:list){
				count=dao.checkDataIsExist(i);
				if(count>0){
					return Util.responseMap("false", i.getYear()+"年度的数据已存在，无需再次录入");
				}
				dao.addRecord(i);
			}
		}
		return Util.responseMap(1);
	}		
	public Map<String,Object> getSumHj(String orgid,String year){
		if(StringUtil.isEmpty(year)){
			List<Map<String,Object>> years = cDao.loadYears("zzy_sg");
			if(years.size()>0){
				year = years.get(0).get("year").toString();
			}
		}
		List<Map<String,Object>> list = dao.getSumHj(year, orgid);
		String bzmj = list.get(0).get("bzmj")==null?"0":list.get(0).get("bzmj").toString();
		String zcl = list.get(0).get("zcl")==null?"0":list.get(0).get("zcl").toString();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("bzmj", bzmj);
		map.put("zcl", zcl);
		return map;
	}
}
