/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.managementcenter.materialinfo.service;

import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.sg.financial.settlement.util.ExcelWriter;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.mapper.MaterialInfoMapper;
import com.jeeplus.modules.sg.managementcenter.materialinfo.util.MaterialReplaceUtil;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import com.jeeplus.modules.sg.managementcenter.materialproject.service.MaterialProjectService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


@Service
@Transactional(readOnly = true)
public class MaterialInfoService extends CrudService<MaterialInfoMapper, MaterialInfo> {

	@Autowired
	private MaterialInfoMapper materialInfoMapper;
	@Autowired
	private MaterialProjectService materialProjectService;

	@Override
	public MaterialInfo get(String id) {
		return super.get(id);
	}

	@Override
	public List<MaterialInfo> findList(MaterialInfo materialInfo) {
		return super.findList(materialInfo);
	}

	public List<MaterialInfo> findProjectName(){
		return materialInfoMapper.findProjectName();
	}
	
	@Override
	public Page<MaterialInfo> findPage(Page<MaterialInfo> page, MaterialInfo materialInfo) {
		return super.findPage(page, materialInfo);
	}
	
	@Transactional(readOnly = false)
	@Override
	public void save(MaterialInfo materialInfo) {
		super.save(materialInfo);
	}

	@Transactional(readOnly = false)
	public void saveList(List<MaterialInfo> list) {
		for(MaterialInfo maintainData : list){
			maintainData.preInsert();
		}
		materialInfoMapper.insertList(list);
	}

	@Transactional(readOnly = false)
	public void insertOldList(List<MaterialInfo> list) {
		for(MaterialInfo maintainData : list){
			maintainData.preInsert();
		}
		materialInfoMapper.insertOldList(list);
	}
	
	@Transactional(readOnly = false)
	@Override
	public void delete(MaterialInfo materialInfo) {
		super.delete(materialInfo);
	}

	/**
	 *根据项目名称删除物料信息
	 */
	@Transactional(readOnly = false)
	public void deleteByPro(String projectName) {
		materialInfoMapper.deleteByPro(projectName);
	}



	/**
	 *物料信息合并保存
	 */
    @Transactional(readOnly = false)
	public void export(MultipartFile file,String batch,String itemBatch) throws IOException, InvalidFormatException {
		ImportExcel mo = new ImportExcel(file,1,"模块表");
		ImportExcel importExcel = new ImportExcel(file,1,"领料清单");
			Row row = mo.getRow(0);
		String projectNam1 = (String) mo.getCellValue(row, 1);
		String projectName = projectNam1.trim();
		MaterialProject materialProject1 = new MaterialProject();
		materialProject1.setReserveProjectName(projectName);
		List<MaterialProject> materialProjects = materialProjectService.findList(materialProject1);
		if (materialProjects != null && materialProjects.size() > 0) {
			materialInfoMapper.deleteByPro(projectName);
			materialInfoMapper.deleteByOld(projectName);
		} else {
			MaterialProject materialProject = new MaterialProject();
			materialProject.setReserveProjectName(projectName);
			materialProjectService.save(materialProject);
		}
		List<MaterialInfo> materialInfos = getData(importExcel,projectName);   //sheet页数据
//		List<MaterialInfo> list = replaceDate(materialInfos);          //对比替换数据
		List<MaterialInfo> list = getNewData(materialInfos);      //合并后数据
//		List<MaterialInfo> standardList = materialInfoMapper.findSat(batch);     //标准库数据
//		List<MaterialInfo> newList = compareData(list,standardList);    //比对之后的数据
		saveList(list);
		insertOldList(list);
	}

	/**
	 *根据项目名称获取物料信息
	 */
	public List<MaterialInfo> findByBatch(List<MaterialProject> list){
		List<MaterialInfo> list1 = materialInfoMapper.findByList(list);
		 List<MaterialInfo> list2 = getNewData(list1); //合并数据
		Collections.sort(list2, new Comparator<MaterialInfo>() {
			@Override
			public int compare(MaterialInfo o1, MaterialInfo o2) {
				return o1.getMaterialCode().compareTo(o2.getMaterialCode());
			}
		});
		 return list2;
	}




	/**
	 * 获取sheet中数据
	 * @param importExcel
	 * @param projectName
	 * @return
	 */
	public List<MaterialInfo> getData(ImportExcel importExcel,String projectName)  {
		int lastRow = importExcel.getLastDataRowNum();
		List<MaterialInfo> list = new ArrayList<>();
		MaterialInfo maintainData = null;
		for(int i=2; i<lastRow;i++){
			maintainData = new MaterialInfo();
			Row row = importExcel.getRow(i);
			String materialCode = (String) importExcel.getCellValue(row,1);
			if(StringUtils.isNotBlank(materialCode)) {
				maintainData.setProjectName(projectName);
				maintainData.setMaterialCode(materialCode);
			    maintainData.setMaterialName((String) importExcel.getCellValue(row,2));
			    maintainData.setExtendDescription((String) importExcel.getCellValue(row,3));
			    maintainData.setUnit((String) importExcel.getCellValue(row,4));
			    maintainData.setTotalCount(getDouble(importExcel,row,5));
			    maintainData.setWeightKg(getDouble(importExcel,row,6));
			    maintainData.setWeightTon(getDouble(importExcel,row,7));
				maintainData.setSupplyType((String) importExcel.getCellValue(row,8));
				maintainData.setNote((String) importExcel.getCellValue(row,9));
				list.add(maintainData);
			}
		}
		return list;
	}

	/**
	 * 合并数据
	 * @param materialInfos
	 * @return
	 */
	public List<MaterialInfo> getNewData(List<MaterialInfo> materialInfos) {
		double totalCount = 0.00;
		double weightTon = 0.00;
		List<MaterialInfo> list = new ArrayList<>();
		for(int i=0;i<materialInfos.size();i++){
			MaterialInfo materialInfo = materialInfos.get(i);
            String projectName = materialInfo.getProjectName();
            String code = materialInfo.getMaterialCode();
            String name = materialInfo.getMaterialName();
            String des = materialInfo.getExtendDescription();
            totalCount = materialInfo.getTotalCount();
            weightTon = materialInfo.getWeightTon();
            String note = materialInfo.getNote();
            if(projectName != null){
            	for(int j=i+1;j<materialInfos.size();j++){
					MaterialInfo materialInfo1 = materialInfos.get(j);
					String code1 = materialInfo1.getMaterialCode();
					String name1 = materialInfo1.getMaterialName();
					String des1 = materialInfo1.getExtendDescription();
					String note1 = materialInfo1.getNote();
					double totalCount1 = materialInfo1.getTotalCount();
					double weightTon1 = materialInfo1.getWeightTon();
					if(code.equals(code1) && des.equals(des1) && name.equals(name1) && note.equals(note1)){
                          totalCount = totalCount + totalCount1;
                          weightTon = weightTon + weightTon1;
						  materialInfo1.setProjectName(null);
					}
				}
				materialInfo.setTotalCount(totalCount);
				materialInfo.setWeightTon(weightTon);
				list.add(materialInfo);
			}

		}
		return list;
	}

	/**
	 * 对比替换数据
	 * @param list
	 * @return
	 */
	private List<MaterialInfo> replaceDate(List<MaterialInfo> list) {
		for(MaterialInfo materialInfo : list){
			String code = materialInfo.getMaterialCode();
			String name = materialInfo.getMaterialName();
			String des = materialInfo.getExtendDescription();
			for(int i=0;i< MaterialReplaceUtil.exportCode.length;i++){
				if(code.equals(MaterialReplaceUtil.exportCode[i]) && name.equals(MaterialReplaceUtil.exportName[i])
						&& des.equals(MaterialReplaceUtil.exportDes[i])){
					materialInfo.setMaterialCode(MaterialReplaceUtil.replaceCode[i]);
					materialInfo.setMaterialName(MaterialReplaceUtil.replaceName[i]);
					materialInfo.setExtendDescription(MaterialReplaceUtil.replaceDes[i]);
					break;
				}
			}
		}
		return list;
	}

	/**
	 * 数据和标准库比对
	 * @param list
	 * @param standardList
	 * @return
	 */
	private List<MaterialInfo> compareData(List<MaterialInfo> list, List<MaterialInfo> standardList) {
		for(MaterialInfo materialInfo : list){
			String code = materialInfo.getMaterialCode();
			String name = materialInfo.getMaterialName();
			String des = materialInfo.getExtendDescription();
			materialInfo.setState("0");
			for(MaterialInfo materialInfo1 : standardList){
				String code1 = materialInfo1.getMaterialCode();
				String name1 = materialInfo1.getMaterialName();
				String des1 = materialInfo1.getExtendDescription();
				if(code.equals(code1) && name.equals(name1) && des.equals(des1)){
					materialInfo.setState("1");
					break;
				}
			}
		}
		return list;
	}


	private double getDouble(ImportExcel importExcel,Row row,int col){
		double d = 0.00;
		Object o = importExcel.getCellValue(row,col);
		if(!o.equals("")){
			d = Double.parseDouble(o.toString());
		}
		return d;
	}









	
}