/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.financial.settlement.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.erpcredit.entity.ErpCreditMaterial;
import com.jeeplus.modules.sg.financial.settlement.entity.Corresponding;
import com.jeeplus.modules.sg.financial.settlement.entity.CostCheck;
import com.jeeplus.modules.sg.financial.settlement.entity.DonorMaterial;
import com.jeeplus.modules.sg.financial.settlement.entity.ProjectBudget;
import com.jeeplus.modules.sg.financial.settlement.mapper.CorrespondingMapper;
import com.jeeplus.modules.sg.financial.settlement.mapper.CostCheckMapper;
import com.jeeplus.modules.sg.financial.settlement.mapper.DonorMaterialMapper;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.util.MaterialInfoUtil;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
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 java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 费用检查表Service
 *
 * @author user3
 * @date 2020-11-27
 */
@Service
@Transactional(readOnly = true)
public class DonorMaterialService extends CrudService<DonorMaterialMapper, DonorMaterial> {

    @Autowired
    private DonorMaterialMapper donorMaterialMapper;

    @Autowired
    private CorrespondingMapper correspondingMapper;

    public static Map<String, CellStyle> styles;

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

    @Override
    public List<DonorMaterial> findList(DonorMaterial donorMaterial) {
        return super.findList(donorMaterial);
    }


    @Override
    public Page<DonorMaterial> findPage(Page<DonorMaterial> page, DonorMaterial donorMaterial) {
        return super.findPage(page, donorMaterial);
    }

    @Override
    @Transactional(readOnly = false)
    public void save(DonorMaterial donorMaterial) {
        super.save(donorMaterial);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(DonorMaterial donorMaterial) {
        super.delete(donorMaterial);
    }

    @Transactional(readOnly = false)
    public String insertList(@Param("list") List<DonorMaterial> list) {
        String str = "";
        for (DonorMaterial d :
                list) {
            d.preInsert();
        }
        int i = donorMaterialMapper.insertList(list);
        //插入
        str += "概预算信息插入" + list.size() + "条-";
        return str;
    }

    /**
     * 在年度物资上报统计表中保存项目信息，在年度上报明细表中保存物资信息
     */
    @Transactional(readOnly = false)
    public void saveData(MultipartFile file) throws IOException, InvalidFormatException {
        try {
            ImportExcel module = new ImportExcel(file, 1, "预算封面");
            Row row = module.getRow(1);
            Object obj = module.getCellValue(row, 2);
            Row nameRow = module.getRow(2);
            Object nameObj = module.getCellValue(nameRow, 2);
            String projectId = ((String) obj).trim();
            String projectName = ((String) nameObj).trim();
            if (null != projectId && !"".equals(projectId) && null != projectName && !"".equals(projectName)) {
                int project = donorMaterialMapper.findByProjectId(projectId);
                if (project > 0) {
                    donorMaterialMapper.delByProjectId(projectId);
                }
                //保存
                ImportExcel pick = new ImportExcel(file, 6, "甲供材超（欠）供分析表");
                //获取领料清单数据
                List<DonorMaterial> donorMaterials = getData(pick, projectId, projectName);
                //所有领料清单数据
                Iterator<DonorMaterial> iterator = donorMaterials.iterator();
                HashMap<String, DonorMaterial> map = new HashMap<>();
                while (iterator.hasNext()) {
                    DonorMaterial next = iterator.next();
                    String materialCode = next.getMaterialCode();
                    String materialName = next.getMaterialName();
                    String materialDescribe = next.getMaterialDescribe();
                    String s = materialCode + materialName + materialDescribe;
                    if (!map.containsKey(s)) {
                        map.put(s, next);
                    } else {
                        DonorMaterial donorMaterial = map.get(s);
                        BigDecimal bigDecimal1 = BigDecimal.valueOf(donorMaterial.getExaminedNum());
                        BigDecimal bigDecimal = BigDecimal.valueOf(next.getExaminedNum());
                        double v = bigDecimal.add(bigDecimal1).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        donorMaterial.setExaminedNum(v);
                        map.put(s, donorMaterial);
                    }
                }
                List<DonorMaterial> insertList = new ArrayList<>();
                for (DonorMaterial d : map.values()) {
                    insertList.add(d);
                }
                insertList(insertList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据项目编号查询所有已经存在的项目甲供材信息
     */
    public List<DonorMaterial> findByList(List<DonorMaterial> list) {
        return donorMaterialMapper.findByList(list);
    }

    /**
     * excel文件数据读取-新增同一个表格中存在多个相同物料的情况
     */
    private List<DonorMaterial> getData(ImportExcel importExcel, String projectId, String projectName) throws ParseException {
        int lastRow = importExcel.getLastDataRowNum();
        List<DonorMaterial> list = new ArrayList<>();
        DonorMaterial donorMaterial;
        double aDouble;
        for (int i = 6; i < lastRow; i++) {
            donorMaterial = new DonorMaterial();
            Row row = importExcel.getRow(i);
            if (null != row) {
                String cellOne = this.getCellValue(row.getCell(1));
                Cell cell=row.getCell(2);
//                if (cell.getCellType()!=1){
//                    cell.setCellType(1);
//                }
//                String cellTwo = cell.getStringCellValue();
                String cellTwo = this.getCellValue(cell);
                if (null!=cellTwo  && !"".equals(cellTwo) && !"无".equals(cellTwo)  && !"0".equals(cellTwo)) {
                    donorMaterial.setProjectName(projectName);
                    donorMaterial.setProjectId(projectId);
                    String cellThree = this.getCellValue(row.getCell(3));
                    if ("0".equals(cellOne)) {
                        cellOne = "";
                    }
                    if ("0".equals(cellTwo)) {
                        cellTwo = "";
                    }
                    if ("0".equals(cellThree)) {
                        cellThree = "";
                    }
                    donorMaterial.setMaterialType(cellOne);
                    donorMaterial.setMaterialCode(cellTwo);
                    String cellFour = this.getCellValue(row.getCell(4));
                    String cellFive = this.getCellValue(row.getCell(5));
                    String cellSix = this.getCellValue(row.getCell(13));
                    if (null == cellSix || "0".equals(cellSix) || "0.0".equals(cellSix)) {
                        continue;
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(cellSix);
                        BigDecimal bigDecimal1 = bigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP);
                        aDouble = bigDecimal1.doubleValue();
                    }
                    donorMaterial.setMaterialName(cellThree);
                    donorMaterial.setMaterialDescribe(cellFour);
                    donorMaterial.setUnit(cellFive);
                    donorMaterial.setExaminedNum(aDouble);
                    list.add(donorMaterial);
                }
            }
        }
        return list;
    }

    /**
     * 获取excel double类型的值
     */
    private double getDouble(String myDouble) {
        double d = 0.00;
        if (!"".equals(myDouble)) {
            d = Double.parseDouble(myDouble);
        }
        return d;
    }

    /**
     * 获取excel double类型的值(折扣比率值，不能小于1.0)
     */
    private double getDisCount(ImportExcel importExcel, Row row, int col) {
        double d = 1.00;
        Object o = importExcel.getCellValue(row, col);
        if (!o.equals("")) {
            d = Double.parseDouble(o.toString());
        }
        return d;
    }

    /**
     * 获取excel date类型的值
     */
    private Date getDate(ImportExcel importExcel, Row row, int col) throws ParseException {
        Date d = null;
        Object o = importExcel.getCellValue(row, col);
        if (!o.equals("")) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            d = simpleDateFormat.parse(o.toString());
        }
        return d;
    }

    /**
     * 获取excel String类型的值
     */
    private String getString(ImportExcel importExcel, Row row, int col) throws ParseException {
        String str = "";
        Object o = importExcel.getCellValue(row, col);
        if (null != o && !"".equals(o)) {
            str = String.valueOf(o);
        }
        return str;
    }


    public String getCellValue(Cell cell) {
        String value = null;
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_FORMULA:
                    // cell.getCellFormula();
                    try {
                        value = String.valueOf(cell.getStringCellValue());
                    } catch (IllegalStateException e) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        value = String.valueOf(cell.getStringCellValue());
                    } catch (NullPointerException e) {
                        value = "";
                    }
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    value = String.valueOf(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    value = String.valueOf(cell.getRichStringCellValue());
                    break;
            }
        }
        return value;
    }

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    @Transactional(readOnly = false)
    public void updateRemarks(DonorMaterial donorMaterial) {
        donorMaterialMapper.updateRemarks(donorMaterial);
    }

    @Transactional(readOnly = false)
    public void updateImportRemarks(DonorMaterial donorMaterial) {
        mapper.updateImportRemarks(donorMaterial);
    }

    /***
     * 查询所有甲供欠供说明
     * */
    public List<DonorMaterial> findALLRemarks(DonorMaterial donorMaterial) {
        return donorMaterialMapper.findALLRemarks(donorMaterial);
    }

    /*
     * FINANCIAL INSPECTION
     * financialInspection
     * */
    /**/
    @Transactional(readOnly = false)
    public int verifyProjectMaterial(List<ErpCreditMaterial> list, String projectId,String projectName) {
        //成本，资本项目完成后，查询出所有的物料配置信息
        List<Corresponding> corrList = correspondingMapper.findList(new Corresponding());
        //返回值
        // 0：无甲供材数据
        //1：领料完成
        //2：领料未完成
        int a = 0;
        List<DonorMaterial> byId = donorMaterialMapper.findById(projectId);
//        donorMaterialMapper.updateErp(list, projectId);
        //通过项目定义号查询该项目是否存在甲供材信息
        if (null != byId && byId.size() > 0) {
            //通过项目定义号，物料描述更新项目的erp数量
            for (ErpCreditMaterial material : list) {
                String code = material.getEqmMaterialCode();
                String describe = material.getEqmMaterialDetails2();
                //通过设备物料描述，项目定义号，查询物料是否存在，存在更新，不存在插入
                int donor = donorMaterialMapper.findDonor(projectId, code,describe);
                //更新
                BigDecimal bigDecimal = new BigDecimal( material.getMtlNumbers());
                BigDecimal bigDecimal1 = bigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP);
                material.setMtlNumbers(bigDecimal1.doubleValue());
                if (donor <= 0) {
                    //插入
                    material.preInsert();
                    donorMaterialMapper.insertErpOne(material,projectId,projectName);
                } else {
//                    donorMaterialMapper.updateErpOne(material, projectId);
                    donorMaterialMapper.updateErpOne(material, projectId, code);
                }
            }
            //查找所有的
            byId = donorMaterialMapper.findById(projectId);
            for (Corresponding c :
                    corrList) {
                BigDecimal erp = new BigDecimal("0.0");
                BigDecimal exa = new BigDecimal("0.0");
                List<DonorMaterial> useList = new ArrayList<>();
                List<Corresponding> childList = correspondingMapper.findChildList(c);
                for (Corresponding corr :
                        childList) {
                    for (DonorMaterial don :
                            byId) {
                        String materialCode = don.getMaterialCode();
                        String materialDescribe = don.getMaterialDescribe();
                        String materialType = don.getMaterialType();
                        String materialCode1 = corr.getMaterialCode();
                        String materialType1 = corr.getMaterialType();
                        String materialDescription = corr.getMaterialDescription();
//                        if (null == materialType) {
//                            materialType = "";
//                        }
//                        if (null == materialType1) {
//                            materialType1 = "";
//                        }
//                        if (materialCode.equals(materialCode1) && materialType.equals(materialType1) && materialDescribe.equals(materialDescription)) {
//                            useList.add(don);
//                        }
                        if (materialCode.equals(materialCode1) && materialDescribe.equals(materialDescription)) {
                            useList.add(don);
                        }
                    }
                }
                if (useList.size() > 0) {
                    for (DonorMaterial use :
                            useList) {
                        BigDecimal bigDecimal = BigDecimal.valueOf(use.getErpNum());
                        BigDecimal bigDecimal1 = BigDecimal.valueOf(use.getExaminedNum());
                        erp = erp.add(bigDecimal);
                        exa = exa.add(bigDecimal1);
                    }
                    //将相加的erp数量与审定数量比对，如果相等，将对应的物料
                    int i = erp.compareTo(exa);
                    if (i == 0) {
                        for (DonorMaterial use :
                                useList) {
                            use.setRemarks("已匹配");
                            mapper.updateRemarks(use);
                        }
                    }
                }
            }
            byId = donorMaterialMapper.findById(projectId);
            for (DonorMaterial p :
                    byId) {
                if (a == 2) {
                    break;
                }
                String remarks = p.getRemarks();
                Double erpNum1 = p.getErpNum();
                Double examinedNum = p.getExaminedNum();
                if (null == erpNum1) {
                    erpNum1 = 0.0;
                }
                if (null == examinedNum) {
                    examinedNum = 0.0;
                }
                BigDecimal erpNum = new BigDecimal(erpNum1);
                BigDecimal exaNum = new BigDecimal(examinedNum);
                erpNum.setScale(4, BigDecimal.ROUND_HALF_UP);
                exaNum.setScale(4, BigDecimal.ROUND_HALF_UP);
                int i = erpNum.compareTo(exaNum);
                if (i != 0) {
                    if (null != remarks && !"".equals(remarks)) {
                        a = 1;
                    } else {
                        a = 2;
                    }
                } else {
                    a = 1;
                }
            }
        }
        return a;
    }


    @Transactional(readOnly = false)
    public int returnCorr(String projectId) {
        int a = 0;

        return a;
    }

    @Transactional(readOnly = false)
    public void updateErpZero(String projectId) {
        donorMaterialMapper.updateErpZero(projectId);
    }

    @Transactional(readOnly = false)
    public void delAll(List<String> list) {
        donorMaterialMapper.delAll(list);
    }

    /**
     * 更新状态
     * */
    @Transactional(readOnly = false)
    public void updateStatus(List<String> list) {
        donorMaterialMapper.updateStatus(list);
    }


    public List<DonorMaterial> findById(String projectId) {
        return mapper.findById(projectId);
    }
}