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

import cn.gtmap.estateplat.config.core.mapper.config.BdcQlrMapper;
import cn.gtmap.estateplat.config.core.service.BdcQlrbqhService;
import cn.gtmap.estateplat.config.utils.ArdExcelUtil;
import cn.gtmap.estateplat.core.ex.AppException;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.model.server.core.BdcQlrbqh;
import cn.gtmap.estateplat.model.server.core.BdcXygl;
import cn.gtmap.estateplat.model.server.core.BdcXymx;
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.hssf.usermodel.HSSFCell;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0, 2019/8/27.
 * @auto <a href="mailto:zhuwei@gtmap.cn">zhuwei</a>
 * @description 不动产移民搬迁户
 */

@Service
public class BdcQlrbqhServiceImpl implements BdcQlrbqhService {
    @Autowired
    BdcQlrMapper bdcQlrMapper;
    @Autowired
    EntityMapper entityMapper;

    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(), "移民搬迁户")) {
                validateTrue = true;
            }
            if (validateTrue) {
                //默认第一个sheet存放信息
                Sheet sheet = wb.getSheetAt(0);
                //获取第一行
                Row topRow = sheet.getRow(0);
                //获取第一行的列数,即这个sheet的最大列数
                int colNum = topRow.getLastCellNum();
                //获取行的迭代器,通过循环每一行进行赋值操作
                Iterator<Row> rowIterator = sheet.rowIterator();

                int j = 0;
                int total = sheet.getLastRowNum() - 4;
                int failTotal = 0;
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    //因为Excel前五行存的不是数据,跳过前五行数据
                    if (j < 5) {
                        j++;
                        continue;
                    }
                    String saveMsg = initBdcQlrbqh(row, colNum, j);
                    if (StringUtils.isNoneBlank(saveMsg)) {
                        failTotal++;
                        msg.append(saveMsg);
                    }
                    j++;
                }
                result.append("共计").append(total).append("行数据，其中导入成功").append(total - failTotal).append("行，失败").append(failTotal).append("行").append("\n");
            } 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 initBdcQlrbqh(Row row, int colNum , int j) {
        StringBuilder resultBuilder = new StringBuilder();
        BdcQlrbqh bdcQlrbqh = new BdcQlrbqh();
        Cell currentCell;

        for (int i = 1; i < colNum; i++) {
            //索引0默认存放序号，不进行处理
            currentCell = row.getCell(i);
            if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                if (i == 1) {
                    bdcQlrbqh.setZm(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 2) {
                    bdcQlrbqh.setCm(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 3) {
                    bdcQlrbqh.setQlrmc(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                if (i == 4) {
                    try {
                        bdcQlrbqh.setXszcrs(Integer.parseInt(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell))));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                if (i == 5) {
                    bdcQlrbqh.setYhzgx(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 6) {
                    bdcQlrbqh.setSfzjh(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 7) {
                    bdcQlrbqh.setBqnd(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 8) {
                    bdcQlrbqh.setAzfs(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 9) {
                    bdcQlrbqh.setQrd(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 10) {
                    bdcQlrbqh.setSfsc(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 11) {
                    bdcQlrbqh.setBqlx(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
                if (i == 12) {
                    bdcQlrbqh.setBz(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                    continue;
                }
            }
        }
        //判断时候已经存在同样的数据，存在则不再导入
        if (bdcQlrbqh != null) {
            HashMap queryMap = new HashMap();
            if (StringUtils.isNotBlank(bdcQlrbqh.getZm())) {
                queryMap.put("zm", bdcQlrbqh.getZm());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getCm())) {
                queryMap.put("cm", bdcQlrbqh.getCm());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getQlrmc())) {
                queryMap.put("qlrmc", bdcQlrbqh.getQlrmc());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getXszcrs().toString())) {
                queryMap.put("xszcrs", bdcQlrbqh.getXszcrs());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getYhzgx())) {
                queryMap.put("yhzgx", bdcQlrbqh.getYhzgx());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getSfzjh())) {
                queryMap.put("sfzjh", bdcQlrbqh.getSfzjh());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getBqnd())) {
                queryMap.put("bqnd", bdcQlrbqh.getBqnd());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getAzfs())) {
                queryMap.put("azfs", bdcQlrbqh.getAzfs());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getQrd())) {
                queryMap.put("qrd", bdcQlrbqh.getQrd());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getSfsc())) {
                queryMap.put("sfsc", bdcQlrbqh.getSfsc());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getBqlx())) {
                queryMap.put("bqlx", bdcQlrbqh.getBqlx());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getZlgjz())) {
                queryMap.put("zlgjz", bdcQlrbqh.getZlgjz());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getZlgjz2())) {
                queryMap.put("zlgjz2", bdcQlrbqh.getZlgjz2());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getZlgjz3())) {
                queryMap.put("zlgjz3", bdcQlrbqh.getZlgjz3());
            }
            if (StringUtils.isNotBlank(bdcQlrbqh.getBz())) {
                queryMap.put("bz", bdcQlrbqh.getBz());
            }
            List<BdcQlrbqh> bdcQlrbqhList = getBdcQlrbqhListByMap(queryMap);
            if (bdcQlrbqhList.size() == 0) {
                bdcQlrbqh.setQlrid(UUIDGenerator.generate18());
                entityMapper.saveOrUpdate(bdcQlrbqh,bdcQlrbqh.getQlrid());
            } else {
                resultBuilder.append("行号：").append((j+1)).append("导入失败！").append("原因：存在相同数据！").append("\n");
            }

        }
        return resultBuilder.toString();
    }


    public List<BdcQlrbqh> getBdcQlrbqhListByMap(Map map) {
        return bdcQlrMapper.getBdcQlrbqhListByMap(map);
    }
}
