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

import com.drew.metadata.jfif.JfifDescriptor;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.audit.information.utils.FreemarkerUtil;
import com.jeeplus.modules.sg.audit.information.utils.ResponseUtil;
import com.jeeplus.modules.sg.financial.erpcredit.entity.ErpAccount;
import com.jeeplus.modules.sg.financial.erpcredit.entity.ErpCredit;
import com.jeeplus.modules.sg.financial.erpcredit.entity.ErpCreditEquipment;
import com.jeeplus.modules.sg.financial.erpcredit.entity.ErpCreditMaterial;
import com.jeeplus.modules.sg.financial.erpcredit.util.ErpInfo;
import com.jeeplus.modules.sg.financial.erpcredit.util.ImportUtil;
import com.jeeplus.modules.sg.financial.erpcredit.util.Result;
import com.jeeplus.modules.sg.financial.erpcredit.util.ValidationUtils;
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.service.CorrespondingService;
import com.jeeplus.modules.sg.financial.settlement.service.CostCheckService;
import com.jeeplus.modules.sg.financial.settlement.service.DonorMaterialService;
import com.jeeplus.modules.sg.financial.settlement.service.ProjectBudgetService;
import com.jeeplus.modules.sg.financial.settlement.util.MyExportUtil;
import com.jeeplus.modules.sg.settActivi.entity.SettActivi;
import com.jeeplus.modules.sg.settActivi.entity.SettList;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.test.one.dialog.entity.Leave1;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;
import net.oschina.j2cache.redis.RedisCacheProvider;
import net.oschina.j2cache.redis.RedisClient;
import net.oschina.j2cache.redis.RedisUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nustaq.serialization.FSTObjectOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.json.Json;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 概预算基本信息维护
 */
@Controller
@RequestMapping(value = "${adminPath}/finance/budget")
public class ProjectBudgetController extends BaseController {

    @Autowired
    private ProjectBudgetService projectBudgetService;

    @Autowired
    private CostCheckService costCheckService;

    @Autowired
    private DonorMaterialService donorMaterialService;

    @Autowired
    private CorrespondingService correspondingService;

    @ModelAttribute
    public ProjectBudget get(@RequestParam(required = false) String id) {
        ProjectBudget entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = projectBudgetService.get(id);
        }
        if (entity == null) {
            entity = new ProjectBudget();
        }
        return entity;
    }

    /**
     * 列表页面
     */
    @RequiresPermissions("finance:budget:list")
    @RequestMapping(value = {"list", ""})
    public String list(ProjectBudget projectBudget, Model model) {
        model.addAttribute("projectBudget", projectBudget);
        return "modules/sg/financial/settlement/financeBudgetList";
    }


    /**
     * 列表数据
     */
    @ResponseBody
    @RequiresPermissions("finance:budget:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(ProjectBudget projectBudget, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {

        String st = "";
        String projectId = projectBudget.getProjectId();
        if (StringUtils.isNotBlank(projectId)) {
            st = projectId;
        }
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
        if (StringUtils.isNotBlank(st)) {
            String[] sts = st.split("\\s+");
            if (sts.length == 1) {
                projectBudget.setProjectId(sts[0]);
            } else {
                projectBudget.setProjectIds(sts);
                projectBudget.setProjectId(null);
            }
        }
        Page<ProjectBudget> page = projectBudgetService.findPage(new Page<ProjectBudget>(request, response), projectBudget);
        return getBootstrapData(page);
    }


    /**
     * 财务检查列表页面
     */
    @RequiresPermissions("finance:budget:list")
    @RequestMapping(value = "financeList")
    public String financeList(ProjectBudget projectBudget, Model model) {
        model.addAttribute("projectBudget", projectBudget);
        return "modules/sg/financial/settlement/financeList";
    }

    /**
     * 财务检查列表数据
     */
    @ResponseBody
    @RequiresPermissions("finance:budget:list")
    @RequestMapping(value = "financeData")
    public Map<String, Object> FinanceData(ProjectBudget projectBudget, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {
        String st = "";
        String projectId = projectBudget.getProjectId();
        if (StringUtils.isNotBlank(projectId)) {
            st = projectId;
        }
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
        if (StringUtils.isNotBlank(st)) {
            String[] sts = st.split("\\s+");
            if (sts.length == 1) {
                projectBudget.setProjectId(sts[0]);
            } else {
                projectBudget.setProjectIds(sts);
                projectBudget.setProjectId(null);
            }
        }
        Page<ProjectBudget> page = projectBudgetService.findFinancePage(new Page<ProjectBudget>(request, response), projectBudget);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑表单页面
     */
    @RequiresPermissions(value = {"finance:budget:view", "finance:budget:add", "finance:budget:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(ProjectBudget projectBudget, Model model) {
        model.addAttribute("projectBudget", projectBudget);
        return "modules/sg/financial/settlement/financeBudgetForm";
    }

    /**
     * 保存
     */
    @ResponseBody
    @RequiresPermissions(value = {"finance:budget:add", "finance:budget:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(ProjectBudget projectBudget, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(projectBudget);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }

        double designCost = getStaticDouble(projectBudget.getDesignCost());
        double supervisorCost = getStaticDouble(projectBudget.getSupervisorCost());
        double designContractDiscount = getStaticDouble(projectBudget.getDesignContractDiscount());
        double designTypicalDiscount = getStaticDouble(projectBudget.getDesignTypicalDiscount());
        double designTaxRate = getStaticDouble(projectBudget.getDesignTaxRate());
        double supervisorContractDiscount = getStaticDouble(projectBudget.getSupervisorContractDiscount());
        double supervisorTaxRate = getStaticDouble(projectBudget.getSupervisorTaxRate());
        //使用bigDecimal初始化数值，计算防止精度丢失问题
        //设计费
        BigDecimal designCostDecimal = BigDecimal.valueOf(designCost);
        //监理费
        BigDecimal supervisorCostDecimal = BigDecimal.valueOf(supervisorCost);
        //设计合同折扣
        BigDecimal desConDecimal = BigDecimal.valueOf(designContractDiscount);
        //设计典设折扣
        BigDecimal desTypeDecimal = BigDecimal.valueOf(designTypicalDiscount);
        //设计含税税率
        BigDecimal desTaxRateDecimal = BigDecimal.valueOf(designTaxRate);
        //监理费合同折扣
        BigDecimal supervisorDecimal = BigDecimal.valueOf(supervisorContractDiscount);
        //监理费含税税率
        BigDecimal supTaxRateDecimal = BigDecimal.valueOf(supervisorTaxRate);

        //计算项目设计费应付金额（设计费*设计合同折扣*设计典设折扣/设计含税税率）两位小数
        BigDecimal firResult = designCostDecimal.multiply(desConDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal secResult = firResult.multiply(desTypeDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal thirdResult = secResult.divide(desTaxRateDecimal,4,BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
        projectBudget.setDesignFeePayable(thirdResult.toString());
        //计算项目监理费应付金额（监理费*监理费合同折扣/监理含税税率）两位小数
        BigDecimal fourResult = supervisorCostDecimal.multiply(supervisorDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal fivResult = fourResult.divide(supTaxRateDecimal,4,BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
        projectBudget.setSupervisionFeePayable(fivResult.toString());
        //新增或编辑表单保存
        projectBudget.preUpdate();
        projectBudgetService.update(projectBudget);
        costCheckService.updateDesignSup(projectBudget);
        j.setSuccess(true);
        j.setMsg("保存成功");
        return j;
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequiresPermissions("finance:budget:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(ProjectBudget projectBudget) {
        AjaxJson j = new AjaxJson();
        projectBudgetService.delete(projectBudget);
        j.setMsg("删除成功");
        return j;
    }


    /**
     * 删除Model
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequiresPermissions("finance:budget:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids) {
        String idArray[] = ids.split(",");
        ProjectBudget projectBudget = new ProjectBudget();
        CostCheck costCheck = new CostCheck();
        for (String id : idArray) {
            projectBudget.setProjectId(id);
            costCheck.setProjectId(id);
            projectBudgetService.delete(projectBudget);
            costCheckService.delete(costCheck);
        }
        AjaxJson j = new AjaxJson();
        j.setMsg("删除成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequestMapping(value = "exportExcel")
    public void exportExcel(ProjectBudget projectBudget, HttpServletRequest request, HttpServletResponse response) {

        String st = "";
        String projectId = projectBudget.getProjectId();
        if (StringUtils.isNotBlank(projectId)) {
            st = projectId;
        }
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
        if (StringUtils.isNotBlank(st)) {
            String[] sts = st.split("\\s+");
            if (sts.length == 1) {
                projectBudget.setProjectId(sts[0]);
            } else {
                projectBudget.setProjectIds(sts);
                projectBudget.setProjectId(null);
            }
        }
        List<ProjectBudget> list = projectBudgetService.findList(projectBudget);
        MyExportUtil util = MyExportUtil.getOne();
        XSSFWorkbook workbook = util.getWorkbook("projectBudget");
        util.exportExcelTwo(response,workbook,list);
    }


    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("finance:budget:import")
    @RequestMapping(value = "import")
    public AjaxJson importFile(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel ei = new ImportExcel(file, 2, "概预算基本信息管理");
            List<ProjectBudget> list = getData(ei);
            List<ProjectBudget> costList = new ArrayList<>();
            costList.addAll(list);
            //保存概预算信息
            String s = projectBudgetService.saveList(list);
            //保存费用检查信息
            String b = costCheckService.insertList(costList);
            j.setMsg("导入成功" + s + b);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("finance:budget:import")
    @RequestMapping(value = "remarkImport")
    public AjaxJson remarkImport(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<DonorMaterial> list = ei.getDataList(DonorMaterial.class);
            for (DonorMaterial donorMaterial : list){
                try{
                    donorMaterialService.updateImportRemarks(donorMaterial);
                    successNum++;
                }catch(ConstraintViolationException ex){
                    failureNum++;
                }catch (Exception ex) {
                    failureNum++;
                }
            }
            j.setMsg("修改成功" + successNum + " 条备注记录");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导出财务检查excel文件
     */
    @ResponseBody
    @RequestMapping(value = "exportFinanceExcel")
    public void exportFinanceExcel(ProjectBudget projectBudget, HttpServletRequest request, HttpServletResponse response) {

        String st = "";
        String projectId = projectBudget.getProjectId();
        if (StringUtils.isNotBlank(projectId)) {
            st = projectId;
        }
//		对查询的id进行处理，若只有一个id设置projectId模糊匹配，若有多个设置projectIds精准匹配
        if (StringUtils.isNotBlank(st)) {
            String[] sts = st.split("\\s+");
            if (sts.length == 1) {
                projectBudget.setProjectId(sts[0]);
            } else {
                projectBudget.setProjectIds(sts);
                projectBudget.setProjectId(null);
            }
        }
        List<ProjectBudget> list = projectBudgetService.findFinancialInspection(projectBudget);
        MyExportUtil util = MyExportUtil.getOne();
        XSSFWorkbook workbook = util.getWorkbook("finance");
        util.exportExcelThree(response,workbook,list);
    }

    /**
     * excel文件数据读取
     */
    private List<ProjectBudget> getData(ImportExcel importExcel) throws ParseException {
        int lastRow = importExcel.getLastDataRowNum();
        List<ProjectBudget> list = new ArrayList<>();
        ProjectBudget projectBudget;
        String projectType;
        for (int i = 3; i < lastRow; i++) {
            projectBudget = new ProjectBudget();
            Row row = importExcel.getRow(i);
            String projectName = (String) importExcel.getCellValue(row, 0);
            String projectId = (String) importExcel.getCellValue(row, 1);
            if (StringUtils.isNotBlank(projectName) && StringUtils.isNotBlank(projectId)) {
                projectBudget.setProjectName(projectName);
                projectBudget.setProjectId(projectId);
                projectBudget.setDesignUnit(getString(importExcel, row, 2));
                projectBudget.setConstructionUnit(getString(importExcel, row, 3));
                projectBudget.setBuildingAddress(getString(importExcel, row, 4));
                projectBudget.setBuildingProperty(getString(importExcel, row, 5));
                projectBudget.setTotalInvestment(getString(importExcel, row, 6));
                projectBudget.setStartTime(getDate(importExcel, row, 7));
                projectBudget.setStopTime(getDate(importExcel, row, 8));
                projectBudget.setApprovalNumber(getString(importExcel, row, 9));
                projectBudget.setConstructionCost(getDouble(importExcel, row, 10));
                projectBudget.setInstallationCost(getDouble(importExcel, row, 11));
                projectBudget.setEquipmentCost(getDouble(importExcel, row, 12));
                projectBudget.setMaterialCost(getDouble(importExcel, row, 13));
                double designCost = getDouble(importExcel, row, 14);
                projectBudget.setDesignCost(designCost);
                double supervisorCost = getDouble(importExcel, row, 15);
                projectBudget.setSupervisorCost(supervisorCost);
                projectBudget.setPreliminaryWorkCost(getDouble(importExcel, row, 16));
                projectBudget.setCompensationCost(getDouble(importExcel, row, 17));
                projectBudget.setAdministrationCost(getDouble(importExcel, row, 18));
                double designContractDiscount = getDisCount(importExcel, row, 19);
                double designTypicalDiscount = getDisCount(importExcel, row, 20);
                double designTaxRate = getDisCount(importExcel, row, 21);
                double supervisorContractDiscount = getDisCount(importExcel, row, 22);
                double supervisorTaxRate = getDisCount(importExcel, row, 23);
                projectBudget.setDesignContractDiscount(designContractDiscount);
                projectBudget.setDesignTaxRate(designTaxRate);
                projectBudget.setDesignTypicalDiscount(designTypicalDiscount);
                projectBudget.setSupervisorContractDiscount(supervisorContractDiscount);
                projectBudget.setSupervisorTaxRate(supervisorTaxRate);
                //判断项目是否以b开头，以字母“B”开头，则该项目为成本项目，project_type为0；否则为资本项目，project_type为1
                if (projectId.startsWith("B")) {
                    projectType = "0";
                } else {
                    projectType = "1";
                }
                projectBudget.setProjectType(projectType);
                //使用bigDecimal初始化数值，计算防止精度丢失问题
                //设计费
                BigDecimal bigDecimal = new BigDecimal(designCost);
                BigDecimal designCostDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
                //监理费
                BigDecimal bigDecimal1 = new BigDecimal(supervisorCost);
                BigDecimal supervisorCostDecimal = bigDecimal1.setScale(2, BigDecimal.ROUND_HALF_UP);
                //设计合同折扣
                BigDecimal bigDecimal2 = new BigDecimal(designContractDiscount);
                BigDecimal desConDecimal = bigDecimal2.setScale(4, BigDecimal.ROUND_HALF_UP);
                //设计典设折扣
                BigDecimal bigDecimal3 = new BigDecimal(designTypicalDiscount);
                BigDecimal desTypeDecimal = bigDecimal3.setScale(4, BigDecimal.ROUND_HALF_UP);
                //设计含税税率
                BigDecimal bigDecimal5 = new BigDecimal(designTaxRate);
                BigDecimal desTaxRateDecimal = bigDecimal5.setScale(4, BigDecimal.ROUND_HALF_UP);

                //监理费合同折扣
                BigDecimal bigDecimal4 = new BigDecimal(supervisorContractDiscount);
                BigDecimal supervisorDecimal = bigDecimal4.setScale(4, BigDecimal.ROUND_HALF_UP);
                //监理含税税率
                BigDecimal bigDecimal6 = new BigDecimal(supervisorTaxRate);
                BigDecimal supTaxRateDecimal = bigDecimal6.setScale(4, BigDecimal.ROUND_HALF_UP);


                //计算项目设计费应付金额（设计费*设计合同折扣*设计典设折扣/设计含税税率）两位小数
                BigDecimal firResult = designCostDecimal.multiply(desConDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal secResult = firResult.multiply(desTypeDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal thirdResult = secResult.divide(desTaxRateDecimal,4,BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                projectBudget.setDesignFeePayable(thirdResult.toString());
                //计算项目监理费应付金额（监理费*监理费合同折扣/监理含税税率）两位小数
                BigDecimal fourResult = supervisorCostDecimal.multiply(supervisorDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal fivResult = fourResult.divide(supTaxRateDecimal,4,BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
                projectBudget.setSupervisionFeePayable(fivResult.toString());

                list.add(projectBudget);
            }
        }
        return list;
    }

    /**
     * 获取excel double类型的值
     */
    private double getDouble(ImportExcel importExcel, Row row, int col) {
        double d = 0.00;
        Object o = importExcel.getCellValue(row, col);
        if (!o.equals("") && !o.equals("-")) {
            d = Double.parseDouble(o.toString());
        }
        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 static Boolean getMainJudge(ImportExcel importExcel) {
        Boolean flag = false;
        Row row = importExcel.getRow(0);
        String mainCode = (String) importExcel.getCellValue(row, 0);
        if (!mainCode.contains("项目定义")) {
            flag = true;
        }
        String lineItem = (String) importExcel.getCellValue(row, 1);
        if (!lineItem.contains("单位")) {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取excel double类型的值(折扣比率值，不能小于1.0)
     */
    private double getStaticDouble(Double a) {
        double d = 1.00;
        if (null != a) {
            return a;
        }
        return d;
    }


    /**
     * 导入erp明细账
     */
    @ResponseBody
    @RequestMapping(value = "importErp")
    public Result importErp(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request, Model model) {
        Result j = new Result();
        try {
            StringBuilder nullMsg = new StringBuilder();
            StringBuilder notMsg = new StringBuilder();
            StringBuilder costNullMsg = new StringBuilder();
            StringBuilder costNotMsg = new StringBuilder();
            StringBuilder returnMsg = new StringBuilder();
//			读取第一个页签 根据表头两个字段判断是否符合规范。。
            ImportUtil importUtil = new ImportUtil(file, 0, 0);
            Boolean erpJugde = ErpInfo.getErpJugde(importUtil);
            if (erpJugde) {
                j.setSuccess(false);
                j.setMsg("导入失败！失败信息：" + "表不符合规范");
                return j;
            }

            //获取明细账数据 一个ErpAccount对象表示一行有效数据
            List<ErpAccount> erpAccounts = ErpInfo.getErpAccount(importUtil);
            //获取资本项目list循环
            List<ErpAccount> capitalList = new ArrayList<>();
            //获取成本项目list循环
            List<ErpAccount> costList = new ArrayList<>();
            for (ErpAccount c :
                    erpAccounts) {
                String itemId = c.getProjectDefinitionCode();
                if (itemId.startsWith("18")) {
                    capitalList.add(c);
                } else if (itemId.startsWith("B")) {
                    costList.add(c);
                }
            }
            //判断所有项目的甲供材审定数量是否存在，以及是否完成
            if (capitalList.size() > 0) {
                //获取单条数据
                List<ErpCredit> erpCredits = ErpInfo.getAllErpCreditList(capitalList);
                for (ErpCredit e :
                        erpCredits) {
                    //项目定义号
                    String itemId = e.getItemId();
                    String itemName = e.getItemName();
                    //将两个项目对应的
                    List<ErpCreditMaterial> erpCreditChild2s = e.getErpCreditChild2s();
                    List<ErpCreditEquipment> erpCreditChild1s = e.getErpCreditChild1s();
                    if (erpCreditChild1s.size() > 0) {
                        for (ErpCreditEquipment a :
                                erpCreditChild1s) {
                            ErpCreditMaterial material = new ErpCreditMaterial();
                            material.setMtlBookedFee2(a.getEqmBookedFee1());
                            material.setEqmMaterialDetails2(a.getEqmMaterialDetails1());
                            material.setMtlUnit(a.getEqmUnit());
                            material.setMtlNumbers(a.getEqmNumbers());
                            material.setMtlSupplierName(a.getEqmSupplierName());
                            material.setEqmMaterialCode(a.getEqmMaterialCode());
                            erpCreditChild2s.add(material);
                        }
                    }
                    /*将项目的物料信息传入，更新项目的erp数量（返回值，0-无甲供材数据;1-完成;2-领料未完成）
                    0：无甲供材数据
                    1：领料完成
                    2：领料未完成*/
                    //默认将该项目的物料erp数量都更新为0
                    donorMaterialService.updateErpZero(itemId);
                    if (erpCreditChild2s.size() > 0) {
                        int i = donorMaterialService.verifyProjectMaterial(erpCreditChild2s, itemId, itemName);
                        //将有问题的信息记录下来
                        if (i == 0) {
                            nullMsg.append("项目编号" + itemId + "无甲供材数据;");
                            //修改项目donor_material_check状态
                            projectBudgetService.updateCheck(itemId, "donor_material_check", "2");
                            e.setItemName(e.getItemName() + "(未通过甲供材检查)");
                        } else if (i == 2) {
//                            notMsg.append("项目编号" + itemId + "领料未完成;");
                            //修改项目donor_material_check状态
                            projectBudgetService.updateCheck(itemId, "donor_material_check", "2");
                            e.setItemName(e.getItemName() + "(未通过甲供材检查)");
                        } else {
                            //修改项目donor_material_check状态
                            projectBudgetService.updateCheck(itemId, "donor_material_check", "1");
                        }
                    }
                }
                /*判断项目费用检查对应情况
                * @return Map<String,List<String>> 包含两个对象list
                * notExit---存在没有对应的费用检查信息的项目id集合
                * notPass---验证不通过的项目id集合
                * */
                Map<String, List<String>> stringListMap = costCheckService.verifyProjectsCost(erpCredits);
                List<String> notExit = stringListMap.get("notExit");
                List<String> notPass = stringListMap.get("notPass");
                //费用检查缺少基础数据
                //判断是否存在缺失应付金额或者甲供材审定信息的项目

                //费用检查检查未通过
                if (notPass.size() > 0) {
                    for (String a :
                            notPass) {
                        for (ErpCredit e :
                                erpCredits) {
                            if (e.getItemId().equals(a)) {
                                e.setItemName(e.getItemName() + "(未通过费用检查)");
                            }
                        }
//                        notMsg.append("项目编号" + a + "费用入账有误;");
                    }
                }
                if (notExit.size() > 0) {
                    if (notExit.size() > 0) {
                        for (String a :
                                notExit) {
                            nullMsg.append("项目编号" + a + "缺少应付金额;");
                        }
                    }
                    if (null != nullMsg && !"".equals(nullMsg.toString())) {
                        returnMsg.append(nullMsg);
                    }
                    if (null != notMsg && !"".equals(notMsg.toString())) {
                        returnMsg.append(notMsg);
                    }
                    j.setMsg(returnMsg.toString());
                } else {
                    if (null != nullMsg && !"".equals(nullMsg.toString())) {
                        returnMsg.append(nullMsg);
                    }
                    if (null != notMsg && !"".equals(notMsg.toString())) {
                        returnMsg.append(notMsg);
                    }
                    j.setMsg(returnMsg.toString());
                }

                //判断可以生成结算书后保存信息
                ValidationUtils.storeListToRedis(request,erpCredits,ValidationUtils.CREDIT_KEY_PREFIX);
            } else {
                j.setErrorCode("9999");
                nullMsg.append("无资本项目，不生成对应文件");
            }

            //成本项目
            if (costList.size() > 0) {
                List<ErpCredit> erpCredits = ErpInfo.getCostErpList(costList);
                for (ErpCredit e :
                        erpCredits) {
                    //项目定义号
                    String itemId = e.getItemId();
                    String itemName = e.getItemName();
                    //将两个项目对应的
                    List<ErpCreditMaterial> erpCreditChild2s = e.getErpCreditChild2s();
                    List<ErpCreditEquipment> erpCreditChild1s = e.getErpCreditChild1s();
                    if (erpCreditChild1s.size() > 0) {
                        for (ErpCreditEquipment a :
                                erpCreditChild1s) {
                            ErpCreditMaterial material = new ErpCreditMaterial();
                            material.setMtlBookedFee2(a.getEqmBookedFee1());
                            material.setEqmMaterialDetails2(a.getEqmMaterialDetails1());
                            material.setMtlUnit(a.getEqmUnit());
                            material.setMtlNumbers(a.getEqmNumbers());
                            material.setMtlSupplierName(a.getEqmSupplierName());
                            material.setEqmMaterialCode(a.getEqmMaterialCode());
                            erpCreditChild2s.add(material);
                        }
                    }
                    /*将项目的物料信息传入，更新项目的erp数量（返回值，0-无甲供材数据;1-完成;2-领料未完成）
                    0：无甲供材数据
                    1：领料完成
                    2：领料未完成*/
                    donorMaterialService.updateErpZero(itemId);
                    if (erpCreditChild2s.size() > 0) {
                        int i = donorMaterialService.verifyProjectMaterial(erpCreditChild2s, itemId,itemName);
                        //将有问题的信息记录下来
                        if (i == 0) {
                            costNotMsg.append("成本项目编号" + itemId + "(无甲供材数据);");
                            //修改项目donor_material_check状态
                            projectBudgetService.updateCheck(itemId, "donor_material_check", "2");
                        } else if (i == 2) {
//                            costNotMsg.append("成本项目编号" + itemId + "领料未完成;");
                            //修改项目donor_material_check状态
                            projectBudgetService.updateCheck(itemId, "donor_material_check", "2");
                        } else {
                            //修改项目donor_material_check状态
                            projectBudgetService.updateCheck(itemId, "donor_material_check", "1");
                        }
                    }
                }

                Map<String, List<String>> stringListMap = costCheckService.verifyProjectsCost(erpCredits);
                List<String> notExit = stringListMap.get("notExit");
                List<String> notPass = stringListMap.get("notPass");
                //费用检查缺少基础数据
                //判断是否存在缺失应付金额或者甲供材审定信息的项目
                if (notExit.size() > 0 || notPass.size() > 0) {
                    if (notExit.size() > 0) {
                        for (String a :
                                notExit) {
                            costNullMsg.append("项目编号" + a + "缺少应付金额;");
                        }
                    }
                }
                if (null != costNullMsg && !"".equals(costNullMsg.toString())) {
                    returnMsg.append(costNullMsg);
                }
                if (null != costNotMsg && !"".equals(costNotMsg.toString())) {
                    returnMsg.append(costNotMsg);
                }
                j.setMsg(returnMsg.toString());
            }

            j.setSuccess(true);
            return j;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }
}