package com.palmnest.service.dinner.manager.impl;

import com.palmnest.application.bean.Page;
import com.palmnest.application.dto.input.DeptDto;
import com.palmnest.dao.dinner.DeptDao;
import com.palmnest.model.dinner.Department;
import com.palmnest.service.dinner.manager.DeptManager;
import com.palmnest.service.impl.GenericManagerImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author HIAPAD
 * @Description TODO
 * @Date 2019/1/3 17:48
 **/
@Slf4j
@Service("deptManager")
public class DeptManagerImpl extends GenericManagerImpl<Department, Long> implements DeptManager {


	private DeptDao deptDao;

	@Autowired
	public void setDeptDao(DeptDao deptDao) {
		this.deptDao = deptDao;
		this.dao = deptDao;
	}


	@Override
	public void saveUpdateDept(Department department) throws Exception {
		if (department.getId() == null) {
			deptDao.save(department);
		} else {
			deptDao.updateObj(department);
		}
	}

	@Override
	public Page deptList(int pageNo, int pageSize, HashMap<String, String> map) {
		return deptDao.deptList(pageNo, pageSize, map);
	}

	@Override
	public List<Map<String, String>> getDeptByVirIdAndDeptName(int virId, String deptName) {
		List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
		List<Department>          list    = deptDao.getDeptByVirIdAndDeptName(virId, deptName);
		if (list != null && list.size() > 0) {
			for (Department dept : list) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("id", dept.getId().toString());
				map.put("name", dept.getName());
				listMap.add(map);
			}
		}
		return listMap;
	}

	@Override
	public Map<String, Object> getDeptInfo(long deptId) {
		return deptDao.getDeptInfo(deptId);
	}


	@Override
	public List<Department> getAllDept(String orgId, String virId, String name) {
		return deptDao.getDeptByOrgIdAndVirId(orgId, virId, name);
	}

	@Override
	public void delDept(Department department) {
		// 将部门设置为禁用状态
		deptDao.updateObj(department);
		// 将此部门下的员工的部门字段置为null
		deptDao.delUserDept(department.getId());
	}

	@Override
	public Department getDeptByNameAndVirId(int virId, String name) {
		return deptDao.getDeptByNameAndVirId(virId, name);
	}


	@Override
	public Map<String, Object> importDept(InputStream ins, String orgId,
										  String virId) {
		Map<String, Object> retMap   = new HashMap<String, Object>();
		List<Object>        deptList = new ArrayList<Object>();
		int                 bugCount = 0;
		StringBuffer        bugStr   = new StringBuffer("");
		Sheet               sheet    = null;
		SimpleDateFormat    sdf      = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Workbook workbook = WorkbookFactory.create(ins);
			sheet = workbook.getSheet("DeptInfo");
		} catch (Exception e) {
			bugStr.append("模板格式有问题，请下载最新的模板");
		}
		try {
			if (sheet == null) {
				bugStr.append("模板格式有问题，请下载最新的模板");
			} else {
				int rows = sheet.getLastRowNum();
				//如果大于2000行数据
				if (rows > 20000) {
					bugStr.append("数据量太大，不能大于2w行");
				} else if (rows < 1) {
					bugStr.append("数据为空，请录入账单信息");
				} else {
					for (int i = 1; i <= rows; i++) {
						if (sheet.getRow(i) == null) {
							continue;
						}
						if (sheet.getRow(i).getCell(0) == null) {
							bugStr.append("第" + i + "列数据有问题，请检查，问题：部门名称必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						sheet.getRow(i).getCell(0).setCellType(Cell.CELL_TYPE_STRING);
						if (StringUtils.isBlank(sheet.getRow(i).getCell(0).getStringCellValue())) {
							bugStr.append("第" + i + "列数据有问题，请检查，问题：部门名称必填，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}
						//部门名称
						String name = sheet.getRow(i).getCell(0).getStringCellValue();
						//排序
						String orderNum = "";
						if (sheet.getRow(i).getCell(1) != null) {
							sheet.getRow(i).getCell(1).setCellType(Cell.CELL_TYPE_STRING);
							orderNum = sheet.getRow(i).getCell(1).getStringCellValue();
						}
						//简称
						String shortName = "";
						if (sheet.getRow(i).getCell(2) != null) {
							sheet.getRow(i).getCell(2).setCellType(Cell.CELL_TYPE_STRING);
							shortName = sheet.getRow(i).getCell(2).getStringCellValue();
						}
						List<Department> list = getAllDept(orgId, virId, name);
						if (list != null && list.size() > 0) {
							bugStr.append("第" + i + "列数据有问题，请检查，问题：部门名称重复，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						}

						int count = 0;
						if (deptList != null && deptList.size() > 0) {
							for (int k = 0; k < deptList.size(); k++) {
								DeptDto dept = (DeptDto) deptList.get(k);
								if (dept != null) {
									if (name.equals(dept.getName())) {
										count++;
									}
								}
							}
						}

						DeptDto department = new DeptDto();
						department.setName(name);
						department.setOrderNum(orderNum);
						department.setShortName(shortName);
						if (count > 0) {
							bugStr.append("第" + i + "行第2列数据有问题，请检查，问题：【" + name + "】部门名称在文件中重复，请导出系统模板匹配录入<br/>");
							bugCount++;
							continue;
						} else {
							deptList.add(department);
						}
					}
				}
			}
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("deptList", deptList);
			retMap.put("okCount", deptList.size());
			return retMap;

		} catch (Exception e) {
			log.error(e.getMessage());
			retMap.put("bugCount", bugCount);
			retMap.put("bugStr", bugStr.toString());
			retMap.put("deptList", deptList);
			retMap.put("okCount", deptList.size());
			e.printStackTrace();
			return retMap;
		}
	}

}
