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

import cn.gtmap.estateplat.config.core.mapper.config.BdcXyGlMapper;
import cn.gtmap.estateplat.config.core.service.BdcXyGlService;
import cn.gtmap.estateplat.config.core.service.BdcZdGlService;
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.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 org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version 1.0, 2019/4/24.
 * @auto <a href="mailto:zhengqi@gtmap.cn">zhengqi</a>
 * @description 不动产信用管理
 */
@Service
public class BdcXyGlServiceImpl implements BdcXyGlService {

    @Autowired
    EntityMapper entityMapper;
    @Autowired
    private BdcXyGlMapper bdcXyGlMapper;
    @Autowired
    private BdcZdGlService bdcZdGlService;


    @Override
    public void insertOrUpdateByPrimaryKey(final BdcXygl bdcXygl) {
        if (bdcXygl != null) {
            if (StringUtils.isBlank(bdcXygl.getXyglid())) {
                bdcXygl.setXyglid(UUIDGenerator.generate18());
            }
            entityMapper.saveOrUpdate(bdcXygl, bdcXygl.getXyglid());
        }
    }

    @Override
    public void insertOrUpdateByPrimaryKey(final BdcXymx bdcXymx) {
        if (bdcXymx != null) {
            if (StringUtils.isBlank(bdcXymx.getXymxid())) {
                bdcXymx.setXymxid(UUIDGenerator.generate18());
            }
            entityMapper.saveOrUpdate(bdcXymx, bdcXymx.getXymxid());
        }
    }

    @Override
    @Transactional
    public void deleteBdcXyGlxx(final String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] id = ids.split(",");
            for (int i = 0; i < id.length; i++) {
                if (StringUtils.isNotBlank(id[i])) {
                    entityMapper.deleteByPrimaryKey(BdcXygl.class, id[i]);
                    List<BdcXymx> bdcXymxList = getBdcXymxListByXyglid(id[i]);
                    if (CollectionUtils.isNotEmpty(bdcXymxList)) {
                        for (BdcXymx bdcXymx : bdcXymxList) {
                            if (StringUtils.isNotBlank(bdcXymx.getXymxid())) {
                                entityMapper.deleteByPrimaryKey(BdcXymx.class, bdcXymx.getXymxid());
                            }
                        }
                    }
                }
            }
        }
    }


    @Override
    public List<BdcXygl> getBdcXyglListByMap(HashMap hashMap) {
        return bdcXyGlMapper.getBdcXyglListByMap(hashMap);
    }

    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) {
                for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                    //第一个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 = initBdcXyxx(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;
    }

    @Override
    @Transactional
    public void insertOrUpdateBdcXyGlxx(BdcXygl bdcXygl, BdcXymx bdcXymx) {
        if (bdcXygl != null && bdcXymx != null) {
            if (StringUtils.isBlank(bdcXygl.getXyglid())) {
                bdcXygl.setXyglid(UUIDGenerator.generate18());
            }
            insertOrUpdateByPrimaryKey(bdcXygl);
            if (StringUtils.isNotBlank(bdcXygl.getXyglid())) {

                bdcXymx.setXyglid(bdcXygl.getXyglid());
                if (StringUtils.isBlank(bdcXymx.getXymxid())) {
                    bdcXymx.setXymxid(UUIDGenerator.generate18());
                }
                insertOrUpdateByPrimaryKey(bdcXymx);
            }
        }
    }

    @Override
    public List<BdcXymx> getBdcXymxListByXyglid(String xyglid) {
        List<BdcXymx> bdcXymxList = new ArrayList<BdcXymx>();
        if (StringUtils.isNotBlank(xyglid)) {
            bdcXymxList = bdcXyGlMapper.getBdcXymxListByXyglid(xyglid);
        }
        if (CollectionUtils.isEmpty(bdcXymxList)) {
            bdcXymxList = Collections.emptyList();
        }
        return bdcXymxList;
    }

    private String initBdcXyxx(Row row, int lineNum, int j) {
        StringBuilder resultBuilder = new StringBuilder();
        BdcXygl bdcXygl = new BdcXygl();
        BdcXymx bdcXymx = new BdcXymx();
        Cell currentCell;
        boolean qlrmcFlag = false;
        boolean qlrsfzjzlFlag = false;
        boolean qlrxzFlag = false;
        boolean cfwhFlag = false;
        boolean qlrzjhFlag = false;
        boolean cfjgFlag = false;
        boolean fbrFlag = false;
        boolean cjsjFlag = false;
        boolean fbsjFlag = false;
        boolean fbztFlag = false;
        boolean jcsxsjFlag = false;
        boolean sxdqsjFlag = false;
        boolean nrFlag = false;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < lineNum; i++) {
            currentCell = row.getCell(i);
            if (!qlrmcFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXygl.setQlrmc(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                qlrmcFlag = true;
                continue;
            }
            if (!qlrxzFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXygl.setQlrxz(bdcZdGlService.parseNameToCode(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)), "QLRXZ"));
                }
                qlrxzFlag = true;
                continue;
            }
            if (!cfwhFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXymx.setCfwh(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                cfwhFlag = true;
                continue;
            }
            if (!qlrsfzjzlFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXygl.setQlrsfzjzl(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                qlrsfzjzlFlag = true;
                continue;
            }
            if (!qlrzjhFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXygl.setQlrzjh(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                qlrzjhFlag = true;
                continue;
            }
            if (!cfjgFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXymx.setCfjg(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                cfjgFlag = true;
                continue;
            }
            if (!fbrFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXymx.setFbr(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                fbrFlag = true;
                continue;
            }
            if (!cjsjFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    if (((HSSFCell) currentCell).getCellType() == 0) {
                        bdcXymx.setCjsj(currentCell.getDateCellValue());
                    } else {
                        try {
                            bdcXymx.setCjsj(sdf.parse(currentCell.getStringCellValue()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                cjsjFlag = true;
                continue;
            }
            if (!fbsjFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    if (((HSSFCell) currentCell).getCellType() == 0) {
                        bdcXymx.setFbsj(currentCell.getDateCellValue());
                    } else {
                        try {
                            bdcXymx.setFbsj(sdf.parse(currentCell.getStringCellValue()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                fbsjFlag = true;
                continue;
            }
            if (!fbztFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    if ("已发布".equals(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)))) {
                        bdcXymx.setFbzt("1");
                    } else {
                        bdcXymx.setFbzt("0");
                    }
                }
                fbztFlag = true;
                continue;
            }
            if (!jcsxsjFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    if (((HSSFCell) currentCell).getCellType() == 0) {
                        bdcXymx.setJcsxsj(currentCell.getDateCellValue());
                    } else {
                        try {
                            bdcXymx.setJcsxsj(sdf.parse(currentCell.getStringCellValue()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                jcsxsjFlag = true;
                continue;
            }
            if (!sxdqsjFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    if (((HSSFCell) currentCell).getCellType() == 0) {
                        bdcXymx.setSxdqsj(currentCell.getDateCellValue());
                    } else {
                        try {
                            bdcXymx.setSxdqsj(sdf.parse(currentCell.getStringCellValue()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                sxdqsjFlag = true;
                continue;
            }
            if (!nrFlag) {
                if (currentCell != null && StringUtils.isNotBlank(currentCell.toString())) {
                    bdcXymx.setNr(StringUtils.deleteWhitespace(ArdExcelUtil.getValue(currentCell)));
                }
                nrFlag = true;
                continue;
            }
        }

        if (bdcXygl != null && bdcXymx != null) {
            if (StringUtils.isNotBlank(bdcXygl.getQlrmc()) && StringUtils.isNotBlank(bdcXygl.getQlrzjh())) {
                try {
                    // 已存在则更新数据
                    HashMap hashMap = new HashMap();
                    hashMap.put("qlrmc", bdcXygl.getQlrmc());
                    hashMap.put("qlrzjh", bdcXygl.getQlrzjh());
                    List<BdcXygl> bdcXyglList = getBdcXyglListByMap(hashMap);
                    if (CollectionUtils.isNotEmpty(bdcXyglList) && bdcXyglList.get(0) != null
                            && StringUtils.isNotBlank(bdcXyglList.get(0).getXyglid())) {
                        bdcXygl.setXyglid(bdcXyglList.get(0).getXyglid());
                    }
                    if (StringUtils.isNotBlank(bdcXygl.getXyglid())) {
                        List<BdcXymx> bdcXymxList = getBdcXymxListByXyglid(bdcXygl.getXyglid());
                        if (CollectionUtils.isNotEmpty(bdcXymxList) && bdcXymxList.get(0) != null
                                && StringUtils.isNotBlank(bdcXymxList.get(0).getXymxid())) {
                            bdcXymx.setXymxid(bdcXymxList.get(0).getXymxid());
                        }
                    }
                    insertOrUpdateBdcXyGlxx(bdcXygl, bdcXymx);
                } catch (Exception e) {
                    resultBuilder.append("权利人:").append(bdcXygl.getQlrmc()).append(", 状态:导入失败, 失败原因:");
                    if (e.getCause() != null) {
                        resultBuilder.append(StringUtils.deleteWhitespace(e.getCause().getMessage())).append("<hr>");
                    } else {
                        resultBuilder.append(StringUtils.deleteWhitespace(e.getMessage())).append("<hr>");
                    }
                }
            } else {
                resultBuilder.append("行号:").append(j).append(", 状态:导入失败, 失败原因:权利人名称或证件号为空！");
            }
        }
        return resultBuilder.toString();
    }
}
