/**
 * 
 */
package cn.gtmap.estateplat.config.core.service.impl;

import cn.gtmap.estateplat.config.core.service.BdcCompanyService;
import cn.gtmap.estateplat.config.utils.ArdExcelUtil;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.core.ex.AppException;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.page.repository.Repo;
import cn.gtmap.estateplat.model.server.core.BdcQlrbqh;
import cn.gtmap.estateplat.model.server.core.BdcXtQy;
import com.google.common.collect.Maps;
import com.gtis.common.util.UUIDGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author wangtao
 * @version 2016年4月20日
 * @description
 */
@Service
public class BdcCompanyServiceImpl implements BdcCompanyService {

	@Autowired
	private EntityMapper entityMapper;
	@Autowired
	private Repo repository;

	/**
	 * @author wangtao
	 * @description 根据企业ID对企业信息进行删除
	 * @param
	 * @return
	 */
	@Override
	public void deleteCompanyByPrimaryKey(String ids) {

		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			entityMapper.deleteByPrimaryKey(BdcXtQy.class, id[i]);
		}
	}

	/**
	 * @author wangtao
	 * @description 增加或者修改企业信息
	 * @param
	 * @return
	 */
	@Override
	public void insertOrUpdateByPrimaryKey(BdcXtQy bdcXtQy) {

		if (StringUtils.isBlank(bdcXtQy.getQyid())) {
			bdcXtQy.setQyid(UUIDGenerator.generate18());
		}
		entityMapper.saveOrUpdate(bdcXtQy, bdcXtQy.getQyid());

	}

	@Override
	public Map<String, String> getExcelAsInputStream(InputStream inputStream) {
		InputStream ins = null;
		Workbook wb = null;
		StringBuilder result = new StringBuilder();
		StringBuilder msg = new StringBuilder();
		Map<String, String> resultMap = Maps.newHashMap();
		try {
			//获取文件的输入流
			ins = inputStream;
			//创建工作簿
			wb = WorkbookFactory.create(ins);
			//关闭输入流
			ins.close();
			//循环获取Excel的Sheet
			Boolean validateTrue = false;
			Sheet nameSheet = wb.getSheetAt(0);
			if (StringUtils.equals(nameSheet.getSheetName(), "Sheet1")) {
				validateTrue = true;
			}
			if (validateTrue) {
				//第一个sheet存放信息
				Sheet sheet = wb.getSheetAt(0);
				//获取第一行
				Row topRow = sheet.getRow(0);
				//获取第一行的列数,即这个sheet的最大列数
				int lineNum = topRow.getLastCellNum();
				//获取行的迭代器,通过循环每一行进行赋值操作
				Iterator<Row> rowIterator = sheet.rowIterator();

				int j = 0;
				int total = sheet.getLastRowNum();
				int failTotal = 0;
				while (rowIterator.hasNext()) {
					Row row = rowIterator.next();
					row.getLastCellNum();
					//因为Excel第一行存放的是列名,跳过第一行数据
					if (j == 0) {
						j++;
						continue;
					}
					String saveMsg = initBdcCompany(row, lineNum, j);
					if (StringUtils.isNoneBlank(saveMsg)) {
						failTotal++;
						msg.append(saveMsg);
					}
				}
				result.append("共计").append(total).append("行数据，其中导入成功").append(total - failTotal).append("行，失败").append(failTotal).append("行");
			} else {
				throw new AppException("无效的格式!");
			}
		} catch (IOException e) {
			throw new AppException("创建工作簿出错!");
		} catch (InvalidFormatException e) {
			throw new AppException("无效的格式!");
		}
		resultMap.put("result", result.toString());
		resultMap.put("msg", msg.toString());
		return resultMap;
	}

	private String initBdcCompany(Row row, int colNum , int j) {
		StringBuilder resultBuilder = new StringBuilder();
		BdcXtQy bdcXtQy = new BdcXtQy();
		BdcQlrbqh bdcQlrbqh = new BdcQlrbqh();
		Cell currentCell;

		for (int i = 0; i < colNum; i++) {
			currentCell = row.getCell(i);
			if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
				if (i == 0) {
					bdcXtQy.setQymc(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
					continue;
				}
				if (i == 1) {
					bdcXtQy.setTyshxydm(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
					continue;
				}
				if (i == 2) {
					bdcXtQy.setZjbh(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
				}
				bdcXtQy.setZjlx(Constants.QLRZJHLX_ZZJG);
				bdcXtQy.setSfxwqy("1");
			}
		}
		//判断时候已经存在同样的数据，存在则不再导入
		if (bdcXtQy != null) {
			HashMap queryMap = new HashMap();
			queryMap.put("qymc", bdcXtQy.getQymc());
			queryMap.put("sfxwqy", "1");
			List<Map> dataPaging = repository.selectList("getCompanyListByPage", queryMap);
			if (CollectionUtils.isEmpty(dataPaging)) {
				bdcXtQy.setQyid(UUIDGenerator.generate18());
				entityMapper.saveOrUpdate(bdcXtQy,bdcXtQy.getQyid());
			} else {
				resultBuilder.append("行号：").append((j+1)).append("导入失败！").append("原因：存在相同数据！").append("\n");
			}

		}
		return resultBuilder.toString();
	}
}
