package com.unis.base.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unis.base.app.service.WarehouseService;
import com.unis.base.client.WarehouseFeign;
import com.unis.base.common.vo.DCfxxsjyVO;
import com.unis.base.common.vo.WarehouseDoorVO;
import com.unis.cbl.common.vo.RotateAcceptDetailVO;
import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.JsonUtils;
import com.unis.common.utils.ResponseWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WarehouseServiceImpl
 * @Description: 仓房信息 service实现类
 * @author WangZL
 * @date 2019年9月6日 上午11:18:54
 */
@Service
public class WarehouseServiceImpl implements WarehouseService {

	@Autowired
	private WarehouseFeign warehouseFeign;

	/**
	 * 新增仓房列表信息
	 * @param dCfxxsjyVOList
	 * @return
	 */
	@Override
	public ResponseWrapper insertList(List<DCfxxsjyVO> dCfxxsjyVOList) {
		if (dCfxxsjyVOList != null && dCfxxsjyVOList.size() > 0 ){
			ResponseWrapper responseWrapper = warehouseFeign.deleteList(dCfxxsjyVOList.get(0).getKddm());
			if (!responseWrapper.isSuccess()){
				return responseWrapper;
			}
			for (DCfxxsjyVO dCfxxsjyVO : dCfxxsjyVOList) {
				if (StringUtils.isEmpty(dCfxxsjyVO.getKddm())){
					ResponseWrapper.error("缺少必填字段，请联系管理员");
				}
				if (StringUtils.isEmpty(dCfxxsjyVO.getCfbh())){
					dCfxxsjyVO.setStatus(1);
					dCfxxsjyVO.setCreator(CurrentUtil.getUserName());
					dCfxxsjyVO.setCreateDate(new Date());
                    ResponseWrapper responseWrapperInsert = warehouseFeign.insert(dCfxxsjyVO);
                    if (!responseWrapperInsert.isSuccess()) {
                        return responseWrapperInsert;
                    }
				} else {
					dCfxxsjyVO.setStatus(1);
					dCfxxsjyVO.setRefresher(CurrentUtil.getUserName());
					dCfxxsjyVO.setRefreshTime(new Date());
                    ResponseWrapper responseWrapperUpdate = warehouseFeign.warehouseUpdate(dCfxxsjyVO);
                    if (!responseWrapperUpdate.isSuccess()) {
                        return responseWrapperUpdate;
                    }
				}
			}
			return ResponseWrapper.success();
		} else {
			return ResponseWrapper.success();
		}
	}

	public Workbook export(JSONObject resultObj) throws Exception {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet();
		sheet.setDefaultColumnWidth(12);
		sheet.setDefaultRowHeightInPoints(30);

		JSONObject data = JSON.parseObject(JsonUtils.serialize(resultObj));
		List<DCfxxsjyVO> dataList =data.getJSONArray("list").toJavaList(DCfxxsjyVO.class);

	    if(null != dataList && dataList.size() >0) {
			String qymc = dataList.get(0).getQymc();
			String zcr = null == dataList.get(0).getZcr()?"":(new DecimalFormat("0.00").format(new BigDecimal(dataList.get(0).getZcr().toString())).replace(".0",""));
			String qytxdz = dataList.get(0).getQytxdz().replace("\n","");
			String fddbr = dataList.get(0).getFddbr();
			Date refreshTime = dataList.get(0).getRefreshTime();
			Integer cfs = dataList.size();
			String refreshTimeStr="";
			if(null != refreshTime) {
				refreshTimeStr = new SimpleDateFormat("yyyy年MM月dd日").format(refreshTime);
			}


			String[][] propertyDes = {
					{"单位：","",""+qymc+"","","","","总库容：","",""+zcr+"吨","","","","总仓房数：","",""+cfs+"","","单位地址：","",""+qytxdz+"","","","","","","","单位负责人：","",""+fddbr+"","","填表日期：","",""+refreshTimeStr+"","","",""},
					{"编号","仓号","仓房基本情况","","","","","","","","","","","","","","","仓内设施情况","","","","","","","","","","","","","","","","",""},
					{"","","仓型","设计仓容（吨）","核定仓容(吨）","低温仓","建设年份","用途","验收合格","产权","内长","内宽","内径","大门","窗户","设计粮线高度","储存方式","保温门","保温窗","双层保温窗","外控内开窗","仓内吊顶","仓内保温吊顶","隔层排积热","仓顶外隔热层","保温墙体","保温涂料","制冷设备","地笼通风","轴流风机","电子测温","自动流粮口","环流熏蒸","内环流","仓内摄像头"},
					{"","","高大平房仓、楼房仓、立筒仓、浅圆仓、半地下仓、门架仓、钢板仓、简易仓、其他","仓房设计单位设计容量","仓房设计单位核定的容量","低温仓、准低温仓、普通仓、保温仓（见备注）","验收竣工年份（xxxx年xx月）","储粮、机械设备存放、闲置等","是否有竣工验收或验收备案","是否有不动产权证","仓内使用体积净长","仓内使用体积净宽","立筒仓、浅圆仓、油罐内直径","仓房大门数量","仓房窗户数量","仓房设计单位设计装粮高度","包存、散存、围包散存","仓房大门有隔热保温材料的","仓房窗户有隔热保温材料的","仓房有双层保温窗的","仓房有仓外控制仓内窗户开启的","仓内有吊顶隔层的","仓内吊顶隔层采用保温材料的","仓顶与吊顶间的空间有排风或换气设备的","仓顶有隔热顶（二层顶）","仓房墙体有保温材料围护的","仓房外墙涂刷保温涂料的","仓房有机械制冷的设备（空调）","仓房有地笼通风口有配套风机的","仓房墙壁装有轴流风机的","仓房装有联网电脑测温系统的","仓房墙壁装有自动流粮口的","装有环流熏蒸管路并配套环流熏蒸机的","仓房装有气体内部环流的","仓房已安装智能化粮库配套摄像头"}
			};

			int mergerNum = 0 ; //合并数

			Map<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();   // 合并行时要跳过的行列
			//合并列
			for(int i=0; i<propertyDes[propertyDes.length-1].length; i++){
				if("".equals(propertyDes[propertyDes.length-1][i])){
					for(int j=propertyDes.length-2; j >=0 ;j--){
						if(!"".equals(propertyDes[j][i])){
							sheet.addMergedRegion(new CellRangeAddress(j,propertyDes.length-1,i,i)); // 合并单元格
							break;
						}else{
							if(map.containsKey(j)){
								List<Integer> list = map.get(j);
								list.add(i);
								map.put(j, list);
							}else{
								List<Integer> list = new ArrayList<>();
								list.add(i);
								map.put(j, list);
							}
						}
					}
				}
			}
			//合并行
			for(int i=0; i< propertyDes.length-1; i++){
				for(int j=0; j<propertyDes[i].length; j++){
					List<Integer> list = map.get(i);
					if(list==null ||(list!=null&&!list.contains(j))){
						String a = propertyDes[i][j];
						if("".equals(propertyDes[i][j])){
							mergerNum++ ;
							if(mergerNum != 0 && j == (propertyDes[i].length-1)){
								sheet.addMergedRegion(new CellRangeAddress(i,i,j-mergerNum,j)); // 合并单元格
								mergerNum = 0 ;
							}
						}else {
							if(mergerNum != 0){
								sheet.addMergedRegion(new CellRangeAddress(i,i,j-mergerNum-1,j-1)); // 合并单元格
								mergerNum = 0 ;
							}
						}
					}
				}
			}

			//给单元格设置值
			CellStyle titleCell;
			Font titleFont = wb.createFont();
			for(int i=0; i< propertyDes.length; i++){
				Row row = sheet.createRow(i);
				row.setHeight((short)1400);
				titleCell = getTitleStyle(wb);
				if(i<propertyDes.length-1) {
					row.setHeight((short)600);
					titleFont.setBold(true);
					titleFont.setFontHeight((short) 12);
					titleFont.setFontHeightInPoints((short) 12);
					titleCell.setFont(titleFont);
				}
				for(int j=0; j<propertyDes[i].length; j++){
					Cell cell = row.createCell(j);
					cell.setCellValue(propertyDes[i][j]);
					cell.setCellStyle(titleCell);
				}
			}

			HashMap<String, String> isHave = new HashMap<>();
			isHave.put("1","有");
			isHave.put("0","无");

			HashMap<String, String> dwclxMap = new HashMap<>();
			dwclxMap.put("1","低温仓");
			dwclxMap.put("2","准低温仓");
			dwclxMap.put("3","普通仓");
			dwclxMap.put("4","保温仓");

			HashMap<String, String> cfsyqkMap = new HashMap<>();
			cfsyqkMap.put("0","停用");
			cfsyqkMap.put("1","闲置");
			cfsyqkMap.put("2","储粮");
			cfsyqkMap.put("3","物资");
			cfsyqkMap.put("4","他用");

            Map<String, String> cflxDict = new HashMap<>();
            cflxDict.put("10101", "平方仓");
            cflxDict.put("10102", "筒仓");
            cflxDict.put("10103", "浅圆仓");
            cflxDict.put("10104", "楼房仓");
            cflxDict.put("10105", "地下仓");

            DCfxxsjyVO detail = new DCfxxsjyVO();
            Double zrj = dataList.stream().mapToDouble(DCfxxsjyVO -> Objects.isNull(DCfxxsjyVO.getDczlrj()) ? 0D : DCfxxsjyVO.getDczlrj()).sum();
            Double sjcr = dataList.stream().mapToDouble(DCfxxsjyVO -> Objects.isNull(DCfxxsjyVO.getSjcr()) ? 0D : DCfxxsjyVO.getSjcr()).sum();
            detail.setDczlrj(zrj);
            detail.setSjcr(sjcr);
            dataList.add(detail);
            for (int j = 0; j < dataList.size(); j++) {
				detail = dataList.get(j);
				Row rowData = sheet.createRow(j+4);

				Cell cell = rowData.createCell(0);
				if(j == dataList.size()-1) {
					cell.setCellValue("");
				} else {
					cell.setCellValue(j + 1);
				}


				Cell cell2 = rowData.createCell(1);
				cell2.setCellValue(null == detail.getCfmc()?"":detail.getCfmc());

				Cell cell3 = rowData.createCell(2);
                cell3.setCellValue(null == detail.getCflx() ? "" : detail.getCflx());

				Cell cell36 = rowData.createCell(3);
				cell36.setCellValue(null == detail.getSjcr()?"":detail.getSjcr().toString());

				Cell cell4 = rowData.createCell(4);
				cell4.setCellValue(null == detail.getDczlrj()?"":detail.getDczlrj().toString());

				Cell cell5 = rowData.createCell(5);
				cell5.setCellValue(null == detail.getDwclx()?"":dwclxMap.get(detail.getDwclx().toString())); //

				Cell cell6 = rowData.createCell(6);
				cell6.setCellValue(null == detail.getJssj()?"":new SimpleDateFormat("yyyy.MM").format(detail.getJssj()));

				Cell cell7 = rowData.createCell(7); // 用途 储粮、机械设备存放、闲置等
                cell7.setCellValue(Optional.ofNullable(detail.getCfyt()).orElse(""));

				Cell cell8 = rowData.createCell(8);
				cell8.setCellValue(null == detail.getAcceptanceQualified()?"":isHave.get(detail.getAcceptanceQualified().toString()));

				Cell cell9 = rowData.createCell(9);
				cell9.setCellValue(null == detail.getRealEstateCertificate()?"":isHave.get(detail.getRealEstateCertificate().toString()));

				Cell cell10 = rowData.createCell(10);
				cell10.setCellValue(null == detail.getCnc()?"":(new DecimalFormat("0.00").format(new BigDecimal(detail.getCnc().toString())).replace(".0","")));

				Cell cell11 = rowData.createCell(11);
				cell11.setCellValue(null == detail.getCnk()?"":(new DecimalFormat("0.00").format(new BigDecimal(detail.getCnk().toString())).replace(".0","")));

				Cell cell12 = rowData.createCell(12);
				cell12.setCellValue(null == detail.getCntcnj()?"":(new DecimalFormat("0.00").format(new BigDecimal(detail.getCntcnj().toString())).replace(".0","")));

				Cell cell13 = rowData.createCell(13);
//				cell13.setCellValue(null == detail.getWarehouseDoorVOList()?"":String.valueOf((detail.getWarehouseDoorVOList().size()))); // 仓房大门数量
				cell13.setCellValue(Optional.ofNullable(detail.getCmsl()).orElse(0)); // 仓房大门数量

				Cell cell34 = rowData.createCell(14);
				cell34.setCellValue(null == detail.getWindowNum()?"":detail.getWindowNum().toString());

				Cell cell14 = rowData.createCell(15);
				cell14.setCellValue(null == detail.getZlxgd()?"":(new DecimalFormat("0.00").format(new BigDecimal(detail.getZlxgd().toString())).replace(".0","")));

				Cell cell15 = rowData.createCell(16);
				cell15.setCellValue(null == detail.getCcfs()?"":detail.getCcfs().toString());

				Cell cell16 = rowData.createCell(17);
				cell16.setCellValue(null == detail.getBwm()?"":isHave.get(detail.getBwm().toString()));

				Cell cell17 = rowData.createCell(18);
				cell17.setCellValue(null == detail.getBwc()?"":isHave.get(detail.getBwc().toString()));

				Cell cell18 = rowData.createCell(19);
				cell18.setCellValue(null == detail.getScbwc()?"":isHave.get(detail.getScbwc().toString()));

				Cell cell19 = rowData.createCell(20);
				cell19.setCellValue(null == detail.getWknkc()?"":isHave.get(detail.getWknkc().toString()));

				Cell cell20 = rowData.createCell(21);
				cell20.setCellValue(null == detail.getCndd()?"":isHave.get(detail.getCndd().toString()));

				Cell cell21 = rowData.createCell(22);
				cell21.setCellValue(null == detail.getCdbwdd()?"":isHave.get(detail.getCdbwdd().toString()));

				Cell cell22 = rowData.createCell(23);
				cell22.setCellValue(null == detail.getGcpjr()?"":isHave.get(detail.getGcpjr().toString()));

				Cell cell23 = rowData.createCell(24);
				cell23.setCellValue(null == detail.getCdwgrc()?"":isHave.get(detail.getCdwgrc().toString()));

				Cell cell24 = rowData.createCell(25);
				cell24.setCellValue(null == detail.getBwqt()?"":isHave.get(detail.getBwqt().toString()));

				Cell cell25 = rowData.createCell(26);
				cell25.setCellValue(null == detail.getBwtl()?"":isHave.get(detail.getBwtl().toString()));

				Cell cell26 = rowData.createCell(27);
				cell26.setCellValue(null == detail.getZlsb()?"":isHave.get(detail.getZlsb().toString()));

				Cell cell27 = rowData.createCell(28);
				cell27.setCellValue(null == detail.getDltf()?"":isHave.get(detail.getDltf().toString()));

				Cell cell28 = rowData.createCell(29);
				cell28.setCellValue(null == detail.getZlfj()?"":isHave.get(detail.getZlfj().toString()));

				Cell cell29 = rowData.createCell(30);
				cell29.setCellValue(null == detail.getDzcw()?"":isHave.get(detail.getDzcw().toString()));

				Cell cell30 = rowData.createCell(31);
				cell30.setCellValue(null == detail.getZdllk()?"":isHave.get(detail.getZdllk().toString()));

				Cell cell31 = rowData.createCell(32);
				cell31.setCellValue(null == detail.getHlxz()?"":isHave.get(detail.getHlxz().toString()));

				Cell cell32 = rowData.createCell(33);
				cell32.setCellValue(null == detail.getCnhl()?"":isHave.get(detail.getCnhl().toString()));

				Cell cell33 = rowData.createCell(34);
				cell33.setCellValue(null == detail.getCnsxt()?"":isHave.get(detail.getCnsxt().toString()));


			}

			CellStyle content = wb.createCellStyle();
			Font font = wb.createFont();
			for(int i=0; i< dataList.size(); i++){
				Row rowData = sheet.getRow(i+4);
				rowData.setHeight((short)500);
				for(int j=0; j<=34; j++){
					Cell cell = rowData.getCell(j);
					if(null != cell) {
						cell.setCellStyle(getContentStyle(content,font));
					}
				}
			}
		}
		return wb;
	}

	private static CellStyle getTitleStyle(Workbook wb) throws Exception {
		CellStyle head = wb.createCellStyle();
		head.setBorderTop(BorderStyle.THIN);
		head.setBorderRight(BorderStyle.THIN);
		head.setBorderBottom(BorderStyle.THIN);
		head.setBorderLeft(BorderStyle.THIN);
		head.setVerticalAlignment(VerticalAlignment.CENTER);
		head.setAlignment(HorizontalAlignment.CENTER);
		head.setWrapText(true);

		Font font = wb.createFont();
		font.setFontName("宋体");
		font.setFontHeight((short) 8);
		font.setFontHeightInPoints((short) 8);
		head.setFont(font);
		return head;
	}

	private static CellStyle getContentStyle(CellStyle content,Font font) throws Exception {
		content.setBorderTop(BorderStyle.THIN);
		content.setBorderRight(BorderStyle.THIN);
		content.setBorderBottom(BorderStyle.THIN);
		content.setBorderLeft(BorderStyle.THIN);
		content.setVerticalAlignment(VerticalAlignment.CENTER);
		content.setAlignment(HorizontalAlignment.CENTER);
		content.setWrapText(true);

		font.setFontName("宋体");
		font.setFontHeight((short) 11);
		font.setFontHeightInPoints((short) 11);
		content.setFont(font);
		return content;
	}

}
