package com.jeeplus.modules.sg.picking.activiti.web;

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.Construction;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.materialInventory.entity.MaterialInventory;
import com.jeeplus.modules.sg.managementcenter.materialProvided.entity.MaterialProvided;
import com.jeeplus.modules.sg.managementcenter.materialProvided.service.MaterialProvidedService;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.materialmodule.activiti.entity.MaterialModule;
import com.jeeplus.modules.sg.materialmodule.activiti.service.MaterialModuleService;
import com.jeeplus.modules.sg.picking.activiti.entity.*;
import com.jeeplus.modules.sg.picking.activiti.service.PickIngService;
import com.jeeplus.modules.sg.picking.activiti.service.ShowListService;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

@Controller
@RequestMapping(value = "${adminPath}/picking/activiti")
public class PickIngController extends BaseController {
    @Autowired
    private PickIngService pickIngService;
    @Autowired
    private ShowListService showListService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private ConstructionService constructionService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private MaterialProvidedService materialProvidedService;
    @Autowired
    private MaterialModuleService materialModuleService;

    /**
     * 填写项目表
     */
    @RequestMapping(value = "list")
    public String form(ShowList showList, Model model) {
        String procInsId = showList.getAct().getProcInsId();
        String s = pickIngService.selectVersion(procInsId);
        ProjectNumber projectNumber = pickIngService.projectNumber(procInsId);
        PickIng pickIng = new PickIng();
        List<PickList> pickListList = pickIngService.newAllList(pickIng, s);
        model.addAttribute("showList", showList);
        model.addAttribute("projectNumber", projectNumber);
        model.addAttribute("pickListList", pickListList);
        return "modules/sg/picking/activiti/pickIng";
    }

    /**
     * 施工单位领导审核
     */
    @RequestMapping(value = "constructionLeader")
    public String constructionLeader(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        ProjectNumber projectNumber = pickIngService.projectNumber(showList.getProcInsId());
        model.addAttribute("projectNumber", projectNumber);
        return "modules/sg/picking/activiti/constructionLeader";
    }

    /**
     * 配网项目经理审核
     */
    @RequestMapping(value = "managerAudit")
    public String managerAudit(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        ProjectNumber projectNumber = pickIngService.projectNumber(showList.getProcInsId());
        model.addAttribute("projectNumber", projectNumber);
        return "modules/sg/picking/activiti/managerAudit";
    }

    /**
     * 配网物资专职审核领料单
     */
    @RequestMapping(value = "netExamine")
    public String netExamine(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        ProjectNumber projectNumber = pickIngService.projectNumber(showList.getProcInsId());
        model.addAttribute("projectNumber", projectNumber);
        return "modules/sg/picking/activiti/netExamine";
    }

    /**
     * 施工单位物资专职审核
     */
    @RequestMapping(value = "fullExamine")
    public String fullExamine(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        ProjectNumber projectNumber = pickIngService.projectNumber(showList.getProcInsId());
        model.addAttribute("projectNumber", projectNumber);
        return "modules/sg/picking/activiti/fullExamine";
    }

    /**
     * 项目中心领导审核领料单
     */
    @RequestMapping(value = "leaderExamine")
    public String leaderExamine(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        ProjectNumber projectNumber = pickIngService.projectNumber(showList.getProcInsId());
        model.addAttribute("projectNumber", projectNumber);
        return "modules/sg/picking/activiti/leaderExamine";
    }

    /**
     * 新增物料
     */
    @RequestMapping(value = "netExamineUpload")
    public String netExamineUpload(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        return "modules/sg/picking/activiti/netExamineUpload";
    }

    /**
     * 新增物料-提资模块
     */
    @RequestMapping(value = "netRaise")
    public String netRaise(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        return "modules/sg/picking/activiti/netRaise";
    }

    /**
     * 临时表新增物料
     */
    @RequestMapping(value = "netExamineTemUpload")
    public String netExamineTemUpload(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        return "modules/sg/picking/activiti/netExamineTemUpload";
    }


//    materialModuleForm.jsp

    /**
     * 发起领料页面
     */
    @RequestMapping(value = "constructionLeaderForm")
    public String constructionLeaderForm(ShowList showList, Model model) {
        List<String> versions = pickIngService.allVersion();
        showList.setVersion(versions);
        model.addAttribute("showList", showList);
        return "modules/sg/picking/activiti/constructionLeaderForm";
    }

    @ResponseBody
    @RequestMapping(value = "data")
    public Map<String, Object> data(PickIng pickIng, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<PickIng> page = pickIngService.findPage(new Page<PickIng>(request, response), pickIng);
        List<PickIng> list = page.getList();
        for (PickIng p :
                list) {
            p.setMdUnit("pi");
        }
        return getBootstrapData(page);
    }

    /**
     * 领料申请发起
     * 对项目发起申请，使项目可以提前发起领料流程
     */
    @RequestMapping(value = "pickingApplication")
    public String pickingApplication(PickApplication pickApplication, Model model) {
        model.addAttribute("pickApplication", pickApplication);
        return "modules/sg/picking/activiti/pickingApplication";
    }

    /**
     * 项目经理审核
     * 政策处理专职发起项目，交与项目经理审核页面
     */
    @RequestMapping(value = "applicationAudit")
    public String applicationAudit(PickApplication pickApplication, Model model) {
        String id = pickApplication.getId();
        String projectId = showListService.selectProjectId(id);
//        Project project1 = projectService.get(projectId);
        model.addAttribute("pickApplication", pickApplication);
//        model.addAttribute("project", project1);
        return "modules/sg/picking/activiti/applicationAudit";
    }

    /**
     * 配网项目经理审核
     */
    @RequestMapping(value = "pickPic")
    public String pickPic(PickIng pickIng, Model model) {
        model.addAttribute("pickIng", pickIng);
        return "modules/sg/picking/activiti/pickPic";
    }

    @ResponseBody
    @RequestMapping(value = "pickPicData")
    public Map<String, Object> pickPicData(PickIng pickIng, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<PickIng> page = showListService.findNewImgPage(new Page<PickIng>(request, response), pickIng);
        //当判定系统为linux的时候
        if (Global.SYS_TYPE.equals("2")) {
            List<PickIng> list = page.getList();
            for (PickIng upload :
                    list) {
                String mdImg = upload.getMdImg();
                String newMdImg = "";
                String[] split = mdImg.split("\\|");
//            String reg = "(?i).+?\\.(jpg|gif|bmp)";
                for (int i = 0; i < split.length; i++) {
/*                if (split[i].matches(reg)) {
                    newMdImg += split[i] + "|";
                    continue;
                }*/
                    newMdImg += "http://" + request.getServerName() + split[i] + "|";
                }
                upload.setMdImg(newMdImg);
            }
        }
        return getBootstrapData(page);
    }

    /**
     * 库存对比
     */
    @RequestMapping(value = "inventoryComparison")
    @RequiresPermissions("picking:activiti:inventoryComparison")
    public String inventoryComparison(ShowList showList, Model model) {
        model.addAttribute("showList", showList);
        return "modules/sg/picking/activiti/inventoryComparison";
    }

    /**
     * 导出erp领料单
     */
    @RequiresPermissions("picking:activiti:exportErp")
    @RequestMapping(value = "exportErp")
    public String exportErp(Acquisition acquisition, Model model) {
        model.addAttribute("acquisition", acquisition);
        return "modules/sg/picking/activiti/exportErp";
    }

    @ResponseBody
    @RequestMapping(value = "exportData")
    public Map<String, Object> exportData(Acquisition acquisition, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Acquisition> page = showListService.acquisitionList(new Page<Acquisition>(request, response), acquisition);
        List<Acquisition> list = page.getList();
        for (Acquisition a : list) {
            a.setTheNumber("第" + a.getTheNumber() + "次领料单");
        }
        return getBootstrapData(page);
    }

    //    manager
    /**修改2020-09-23*/
    @ResponseBody
    @RequestMapping(value = "constructionData")
    public Map<String, Object> constructionData(ShowList showList, String procInsId, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ShowList> page = showListService.findNewPage(new Page<ShowList>(request, response), showList);
        List<ShowList> list = page.getList();
        //得到物料信息的可用库存数
        List<MaterialInventory> materialInventoryList = showListService.inventoryQuery(list);
        //查询在当前节点的所有流程实例编号
        List<String> activity = MyActiviUtils.findMdActivity("领料:配网物资专职审核领料单");
        if (activity != null && activity.size() > 0) {
            //根据编号查询到所有的物料信息
            List<ShowList> showLists = showListService.processListQuery(activity);
            //相同的物料信息相加
            HashMap<String, ShowList> tempMap = new HashMap<String, ShowList>();
            for (ShowList show : showLists) {
                String materialCode = show.getMaterialCode() + "|" + show.getExtensionDescription() + "|" + show.getExtensionDescription();
                if (tempMap.containsKey(materialCode)) {
                    ShowList needShow = new ShowList();
                    tempMap.get(materialCode).setMdTotalAmount(tempMap.get(materialCode).getMdTotalAmount() + show.getMdTotalAmount());
                } else {
                    tempMap.put(materialCode, show);
                }
            }
            //合并后的list
            List<ShowList> newShowList = new ArrayList<>();
            Iterator<Map.Entry<String, ShowList>> iterator = tempMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, ShowList> next = iterator.next();
                ShowList newShow = next.getValue();
                newShowList.add(newShow);
            }
            //返回定义物料编码的数据
            for (ShowList show : list) {
                //可用库存/
                for (MaterialInventory ava : materialInventoryList) {
                    if (show.getMaterialCode().equals(ava.getMaterialCode()) && show.getMaterialDescription().equals(ava.getMaterialDetail())) {
                        show.setAvailableStockQuantity(ava.getAvailableStockQuantity());
                    }
                }
                //当前节点的使用库存
                for (ShowList newShow : newShowList) {
                    if (show.getMaterialCode().equals(newShow.getMaterialCode()) && show.getExtensionDescription().equals(newShow.getExtensionDescription()) && show.getMaterialDescription().equals(newShow.getMaterialDescription())) {
                        show.setNowNumber(newShow.getMdTotalAmount());
                    }
                }
            }
        }
        Collections.sort(list);
        return getBootstrapData(page);
    }

    @ResponseBody
    @RequestMapping(value = "constructionTemData")
    public Map<String, Object> constructionTemData(ShowList showList, String procInsId, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<ShowList> page = showListService.findNewTemPage(new Page<ShowList>(request, response), showList);
        return getBootstrapData(page);
    }

    /**
     * 修改2020-09-23
     * */
    @ResponseBody
    @RequestMapping(value = "inventoryComparisonData")
    public Map<String, Object> inventoryComparisonData(ShowList showList, HttpServletRequest request, HttpServletResponse response, Model model) {
        //先查出所有在物资专职的节点的信息
        List<String> activity = MyActiviUtils.findMdActivity("领料:配网物资专职审核领料单");
/*        if (activity.size() >= 0) {
            activity.add("错误提示");
            Page<ShowList> page = showListService.inventoryComparisonData(new Page<ShowList>(request, response), showList, activity);
            return getBootstrapData(page);
        }*/
        Page<ShowList> page = showListService.inventoryComparisonData(new Page<ShowList>(request, response), showList, activity);
        List<ShowList> list = page.getList();
        //相同的物料信息相加
        HashMap<String, ShowList> tempMap = new HashMap<String, ShowList>();
        for (ShowList show : list) {

            String materialCode = show.getMaterialCode() + "|" + show.getExtensionDescription() + "|" + show.getExtensionDescription();
            if (tempMap.containsKey(materialCode)) {
                ShowList needShow = new ShowList();
                tempMap.get(materialCode).setMdTotalAmount(tempMap.get(materialCode).getMdTotalAmount() + show.getMdTotalAmount());
            } else {
                tempMap.put(materialCode, show);
            }
        }
        //合并后的list
        List<ShowList> newShowList = new ArrayList<>();
        Iterator<Map.Entry<String, ShowList>> iterator = tempMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, ShowList> next = iterator.next();
            ShowList newShow = next.getValue();
            newShowList.add(newShow);
        }
        List<MaterialInventory> materialInventoryList = showListService.inventoryQuery(newShowList);

        for (ShowList show : newShowList) {
            //可用库存/
            for (MaterialInventory ava : materialInventoryList) {
                if (show.getMaterialCode().equals(ava.getMaterialCode()) && show.getMaterialDescription().equals(ava.getMaterialDetail())) {
                    show.setAvailableStockQuantity(ava.getAvailableStockQuantity());
                }
            }
            if (null == show.getAvailableStockQuantity()) {
                show.setAvailableStockQuantity(0.0);
            }
        }
        page.setList(newShowList);
        return getBootstrapData(page);
    }

    /**
     * 物资领料流程发起
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(ShowList showList, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(showList);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        String projectId = showList.getProjectId();
        if (projectId == null || "".equals(projectId)) {
            j.setSuccess(false);
            j.setMsg("请选择项目");
            return j;
        }
        /**
         * 流程审批
         */
        Project byName = projectService.findByName(showList.getProjectName());
        projectId = byName.getProjectId();
        String projectName = byName.getProjectName();
        String reserveProjectName = byName.getReserveProjectName();

        if (StringUtils.isBlank(showList.getId())) {
            String number = showListService.findNumber(projectId);
            if (number == null || "".equals(number)) {
                showList.setsVersion(MyActiviUtils.findDic().getValue());
                showList.setProjectName(projectName);
                showList.setProjectId(projectId);
                showList.setReserveProjectName(reserveProjectName);
                showList.setTheNumber("1");
            } else {
                int i = Integer.parseInt(number);
                int a = i + 1;
                showList.setTheNumber(String.valueOf(a));
                DictValue dic = MyActiviUtils.findDic();
                String value = dic.getValue();
                showList.setsVersion(value);
                showList.setProjectName(projectName);
                showList.setProjectId(projectId);
                showList.setReserveProjectName(reserveProjectName);
                showList.setsVersion(MyActiviUtils.findDic().getValue());
            }
            //新增或编辑表单保存
            showListService.save(showList);//保存
            //变更项目领料状态，0未发起变更1发起
            if ("0".equals(byName.getAcquisitionStatus())) {
                showListService.updateAcqStatus(reserveProjectName);
            }
            //修改项目的状态
            // 启动流程
            Map<String, Object> vars = Maps.newHashMap();
            vars.put("manager", UserUtils.getByUserName(byName.getAssignment().getConstructionManage()).getLoginName());
            ProcessDefinition p = actProcessService.getProcessDefinition(showList.getAct().getProcDefId());
            String title = showList.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            actTaskService.startProcess(p.getKey(), "md_acquisition_process", showList.getId(), title, vars);
            j.setMsg("发起领料流程成功!");
            j.getBody().put("targetUrl", "/act/task/process/");

        }
        return j;
    }

    /**
     * 领料申请流程发起|
     */
    @ResponseBody
    @RequestMapping(value = "pickSave")
    public AjaxJson pickSave(PickApplication pickApplication, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(pickApplication);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        String projectId = pickApplication.getProjectId();
        if (projectId == null || "".equals(projectId)) {
            j.setSuccess(false);
            j.setMsg("请选择项目");
            return j;
        }

        //新增或编辑表单保存
        showListService.newSave(pickApplication);
        // 启动流程
        Map<String, Object> vars = Maps.newHashMap();
        vars.put("noFull", false);
        vars.put("full", false);
        String loginName = UserUtils.getUser().getLoginName();
        //配网政策处理专职
        List<String> strings = constructionService.nameFindOffice(loginName);
        boolean flag = false;
        for (String a : strings) {
            if ("配网政策处理专职".equals(a)) {
                flag = true;
            }
        }
        if (flag) {
            vars.put("full", true);
            Project project = new Project();
            project.setId(pickApplication.getProjectId());
            Project ass = projectService.getAss(project);
            vars.put("manager", ass.getAssignment().getOwnerManager());
            j.setMsg("发起流程审批成功!");
        } else {
            //更改项目提前领料标识
            showListService.projectUpdate(pickApplication);
            vars.put("noFull", true);
            j.setMsg("项目可发起领料流程!");
        }
        ProcessDefinition p = actProcessService.getProcessDefinition(pickApplication.getAct().getProcDefId());
        String title = pickApplication.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
        actTaskService.startProcess(p.getKey(), "md_picking_application", pickApplication.getId(), title, vars);
        j.getBody().put("targetUrl", "/act/task/process/");
        return j;
    }

    /**
     * 修改领料清单总量，自动计算总重
     */
    @ResponseBody
    @RequestMapping(value = "mdTotalAmount")
    public AjaxJson mdTotalAmount(ShowList showList, String mdTotalAmount, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        //获取新的数量
        Double aDouble = Double.valueOf(mdTotalAmount);
        showList.setMdTotalAmount(aDouble);
        //根据id查询领料清单中的需要修改的那条信息
        ShowList oneList = showListService.findOneList(showList);
        //获取单重
        Double mdSingleWeight = oneList.getMdSingleWeight();
        BigDecimal b1 = new BigDecimal(aDouble);
        BigDecimal b2 = new BigDecimal(mdSingleWeight);
        double v = b1.multiply(b2).doubleValue();
        showList.setMdTotalWeight(v);
        showListService.updateAmount(showList);
        j.setMsg("成功");
        return j;
    }

    /**
     * 修改领料清单总量，自动计算总重
     */
    @ResponseBody
    @RequestMapping(value = "raiseUpdate")
    public AjaxJson raiseUpdate(ShowList showList, String mdTotalAmount, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        showListService.raiseUpdate(showList);
        j.setMsg("成功");
        return j;
    }


    /**
     * 修改临时领料清单总量，自动计算总重
     */
    @ResponseBody
    @RequestMapping(value = "mdTotalTemAmount")
    public AjaxJson mdTotalTemAmount(ShowList showList, String mdTotalAmount, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        //获取新的数量
        Double aDouble = Double.valueOf(mdTotalAmount);
        showList.setMdTotalAmount(aDouble);
        //根据id查询领料清单中的需要修改的那条信息
        ShowList oneList = showListService.findOneTemList(showList);
        //获取单重
        Double mdSingleWeight = oneList.getMdSingleWeight();
        BigDecimal b1 = new BigDecimal(aDouble);
        BigDecimal b2 = new BigDecimal(mdSingleWeight);
        double v = b1.multiply(b2).doubleValue();
        showList.setMdTotalWeight(v);
        showListService.updateTemAmount(showList);
        j.setMsg("成功");
        return j;
    }

    /**
     * 施工项目经理审定领料清单
     */
    @RequestMapping(value = "managerExam")
    public String managerExam(ShowList showList, Model model, Act act) {
        model.addAttribute("showList", showList);
        ProjectNumber projectNumber = pickIngService.projectNumber(showList.getProcInsId());
        model.addAttribute("projectNumber", projectNumber);
        model.addAttribute("act", act);
        return "modules/sg/picking/activiti/managerExam";
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            showListService.deleteData(id);
        }
        j.setMsg("删除成功！");
        return j;
    }

    /**
     * 批量删除-提资模块
     */
    @ResponseBody
    @RequestMapping(value = "deleteRaiseAll")
    public AjaxJson deleteRaiseAll(String ids) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            showListService.deleteRaiseAll(id);
        }
        j.setMsg("删除成功！");
        return j;
    }

    /**
     * 批量删除-提资模块
     */
    @ResponseBody
    @RequestMapping(value = "trunCate")
    public AjaxJson trunCate (String projectName) {
        AjaxJson j = new AjaxJson();
        showListService.trunCate(projectName);
        j.setMsg("删除成功！");
        return j;
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping(value = "deleteAllTem")
    public AjaxJson deleteAllTem(String ids) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            showListService.deleteTemData(id);
        }
        j.setMsg("删除成功！");
        return j;
    }

    /**
     * 添加甲供物资信息到流程中
     */
    @ResponseBody
    @RequestMapping(value = "netSave")
    public AjaxJson netSave(String project, Double mdTotalAmount, String procInsId) {
        AjaxJson j = new AjaxJson();
        try {
            ShowList showList = new ShowList();
            //根据id查询甲供物资的信息
            MaterialProvided materialProvided = materialProvidedService.get(project);
            //设置id
            showList.preInsert();
            //物料编码
            showList.setMaterialCode(materialProvided.getMaterialCode());
            //流程实例编号
            showList.setProcInsId(procInsId);
            //物料描述
            showList.setMaterialDescription(materialProvided.getMaterialDescription());
            //扩展描述
            showList.setExtensionDescription(materialProvided.getExtendedDescription());
            //单位
            showList.setMdUnits(materialProvided.getMeasuringUnit());
            //总量
            showList.setMdTotalAmount(mdTotalAmount);
            //单重
            showList.setMdSingleWeight(0.0);
            //总重
            showList.setMdTotalWeight(0.0);
            //甲乙供
            showList.setMdTheParty("");
            //备注
            showList.setMdText("");

            List<ShowList> insertList = new ArrayList<>();
            insertList.add(showList);
            //将信息和数量存入对应表
            pickIngService.processList(insertList);
            j.setSuccess(true);
            j.setMsg("添加成功！");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("添加失败");
            e.printStackTrace();
        }
        return j;
    }


    /**
     * 添加甲供物资信息到流程中-提资模块
     */
    @ResponseBody
    @RequestMapping(value = "raiseSave")
    public AjaxJson raiseSave(String project, String projectName,Double mdTotalAmount) {
        AjaxJson j = new AjaxJson();
        try {
            ShowList showList = new ShowList();
            //根据id查询甲供物资的信息
            MaterialProvided materialProvided = materialProvidedService.get(project);
            //设置id
            showList.preInsert();
            showList.setProjectName(projectName);
            //物料编码
            showList.setMaterialCode(materialProvided.getMaterialCode());
            //物料描述
            showList.setMaterialDescription(materialProvided.getMaterialDescription());
            //扩展描述
            showList.setExtensionDescription(materialProvided.getExtendedDescription());
            //单位
            showList.setMdUnits(materialProvided.getMeasuringUnit());
            //总量
            showList.setMdTotalAmount(mdTotalAmount);
            //单重
            showList.setMdSingleWeight(0.0);
            //总重
            showList.setMdTotalWeight(0.0);
            //甲乙供
            showList.setMdTheParty("");
            //备注
            showList.setMdText("");

            List<ShowList> insertList = new ArrayList<>();
            insertList.add(showList);
            //将信息和数量存入对应表
            showListService.replaceData(insertList);
            j.setMsg("添加成功！");
            j.setSuccess(true);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("添加失败");
            e.printStackTrace();
        }
        return j;
    }


    /**
     * 添加甲供物资信息到流程中
     */
    @ResponseBody
    @RequestMapping(value = "netTemSave")
    public AjaxJson netTemSave(String project, Double mdTotalAmount, String procInsId) {
        AjaxJson j = new AjaxJson();
        try {
            ShowList showList = new ShowList();
            //根据id查询甲供物资的信息
            MaterialProvided materialProvided = materialProvidedService.get(project);
            //设置id
            showList.preInsert();
            //物料编码
            showList.setMaterialCode(materialProvided.getMaterialCode());
            //流程实例编号
            showList.setProcInsId(procInsId);
            //物料描述
            showList.setMaterialDescription(materialProvided.getMaterialDescription());
            //扩展描述
            showList.setExtensionDescription(materialProvided.getExtendedDescription());
            //单位
            showList.setMdUnits(materialProvided.getMeasuringUnit());
            //总量
            showList.setMdTotalAmount(mdTotalAmount);
            //单重
            showList.setMdSingleWeight(0.0);
            //总重
            showList.setMdTotalWeight(0.0);
            //甲乙供
            showList.setMdTheParty("");
            //备注
            showList.setMdText("");

            List<ShowList> insertList = new ArrayList<>();
            insertList.add(showList);
            //将信息和数量存入对应表
            pickIngService.processTemList(insertList);
            j.setMsg("添加成功！");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("添加失败");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 成本（修改）2020-09-22
     */
    @ResponseBody
    @RequestMapping(value = "exportErpData")
    public AjaxJson exportErpData(String id, String projectName, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            projectName = URLDecoder.decode(projectName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<String> beforeId = new ArrayList<>();
        if (id != null && !"".equals(id)) {
            String[] split = id.split(",");
            for (String a : split) {
                beforeId.add(a);
            }
        } else {
            beforeId = showListService.selectAllId();
        }
        //获取选择的id查询出属于什么项目
        List<Acquisition> erpType = pickIngService.findErpType(beforeId);
        //成本项目列表
        List<Acquisition> cbList = new ArrayList<>();
        //循环数据，根据类型分组
        for (Acquisition acquisition : erpType) {
            String itemType = acquisition.getProType();
            if (itemType.contains("成本")) {
                cbList.add(acquisition);
            }
        }
        if (cbList.size() > 0) {
            try {
                String fileName = "导出成本ERP" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
                List<CapitalExport> capitalExports = pickIngService.cbList(cbList, projectName);
                new ExportExcel("导出成本ERP", CapitalExport.class).setDataList(capitalExports).write(response, fileName).dispose();
                List<Acquisition> updateList = new ArrayList<>();
                List<String> selectList = new ArrayList<>();
                //修改项目状态可以进场
                for (Acquisition acquisition : cbList
                ) {
                    //获取可以进场的项目信息
                    if ("1".equals(acquisition.getCanEnter())) {
                        updateList.add(acquisition);
                        selectList.add(acquisition.getId());
                    }
                }
                //变更状态
                if (updateList.size() > 0) {
                    pickIngService.updateEnterList(updateList);
                }
                if (selectList.size() > 0) {
                    //根据变更的id，查询改同储备项目名称下的领料单，判断是否已经都可进场，若可以进场，修改对应项目的项目状态
                    List<Acquisition> erpType1 = pickIngService.findErpAll(selectList);
                    Map<String, String> map = new HashMap<>();
                    for (Acquisition acquisition : erpType1
                    ) {
                        if (map.containsKey(acquisition.getReserveProjectName())) {
                            //获得key值对应的value值，如果是1-未完成领料，不修改值，如果是2-完成领料，判断该项目下的其它领料单状态，修改状态
                            String keyValue = map.get(acquisition.getReserveProjectName());
                            if ("2".equals(keyValue)) {
                                if ("2".equals(acquisition.getCanEnter())) {
                                    map.put(acquisition.getReserveProjectName(), "2");
                                } else {
                                    map.put(acquisition.getReserveProjectName(), "1");
                                }
                            }
                        } else {
                            if ("2".equals(acquisition.getCanEnter())) {
                                map.put(acquisition.getReserveProjectName(), "2");
                            } else {
                                map.put(acquisition.getReserveProjectName(), "1");
                            }
                        }
                    }
                    List<String> updateProjectList = new ArrayList<>();
                    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> next = iterator.next();
                        String key = next.getKey();
                        String value = next.getValue();
                        if ("2".equals(value)) {
                            updateProjectList.add(key);
                        }
                    }
                    if (updateProjectList.size() > 0) {
                        pickIngService.updateProjectEnter(updateProjectList);
                        for (String name :
                                updateProjectList) {
                            //判断项目是否发送过电气流程
                            Project byName = projectService.findByName(name);
                            if ("0".equals(byName.getConstructionStatus())) {
                                boolean electric = false;
                                //判单钢管杠，水泥杠，存在电气，判断是否包含
                                List<MaterialInfo> allInfo = projectService.findAllInfo(byName.getId());
                                if (allInfo.size() > 0) {
                                    for (MaterialInfo mi : allInfo
                                    ) {
                                        String materialName = mi.getMaterialName();
                                        if (null != materialName && !"".equals(materialName)) {
                                            //判断项目是否包含描述为钢管杆或水泥杠的物料，存在步入电气流程
                                            if (materialName.contains("钢管杆") || materialName.contains("水泥杆")) {
                                                electric = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                //查询出项目的基础信息，停电线路（如果纯在），人员流转信息
                                Construction blockAss = projectService.findBlockAss(byName.getId());
                                Map<String, Object> vars = Maps.newHashMap();
                                //没用电气及涉电 运行条件
                                vars.put("no", false);
                                //没有电气，有涉电 运行条件
                                vars.put("notContain", false);
                                //包含电气/涉电-优先电气 运行条件
                                vars.put("electrical", false);
                                if (electric) {
                                    //发送开始电气流程
                                    vars.put("electrical", true);
                                } else {
                                    //没用电气进行涉电
                                    //获取项目的领料单，查询停电线路
                                    String blackoutLine = blockAss.getQuantity().getBlackoutLine();
                                    if (null != blackoutLine && !"".equals(blackoutLine) && !"不涉电".equals(blackoutLine)) {
                                        //填写停电线路,不为空，-步入发起涉电流程
                                        vars.put("notContain", true);
                                    } else {
                                        vars.put("no", true);
                                    }
                                }
                                MaterialModule materialModule = new MaterialModule();
                                if (StringUtils.isBlank(materialModule.getId())) {
                                    vars.put("manager", UserUtils.getByUserName(blockAss.getAssignment().getConstructionManage()).getLoginName());
                                    materialModule.setProjectId(blockAss.getProjectId());
                                    materialModule.setProjectName(blockAss.getProjectName());
                                    materialModule.setReserveProjectName(blockAss.getReserveProjectName());
                                    //保存项目储备项目名称，项目定义号，项目名称
                                    materialModuleService.save(materialModule);
                                    //修改项目状态
                                    materialModuleService.updateConstructionStatus("1", blockAss.getReserveProjectName());
                                    String procDefId = projectService.findDefId("sgys");
                                    // 启动流程
                                    ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                                    String title = materialModule.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                                    actTaskService.startProcess(p.getKey(), "sg_construction_process", materialModule.getId(), title, vars);
                                }
                            }
                        }
                    }
                }
                j.setSuccess(true);
                j.setMsg("导出成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                String fileName = "没有对应的项目信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
                List<CapitalExport> nullExports = new ArrayList<>();
                new ExportExcel("没有对应的项目信息", CapitalExport.class).setDataList(nullExports).write(response, fileName).dispose();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //需改导出状态及导出时间
        return j;
    }

    /**
     * 资本（修改）2020-09-22
     */
    @ResponseBody
    @RequestMapping(value = "exportZb")
    public AjaxJson exportZb(String id, String projectId, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            projectId = URLDecoder.decode(projectId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        boolean flag = false;
        List<String> beforeId = new ArrayList<>();
        if (id != null && !"".equals(id)) {
            String[] split = id.split(",");
            for (String a : split) {
                beforeId.add(a);
            }
        } else {
            beforeId = showListService.selectAllId();
        }
        //获取选择的id查询出属于什么项目
        List<Acquisition> erpType = pickIngService.findErpType(beforeId);
        //资本项目列表
        List<Acquisition> zbList = new ArrayList<>();
        //循环数据，根据类型分组
        for (Acquisition acquisition : erpType) {
            String itemType = acquisition.getProType();
            if (itemType.contains("资本")) {
                zbList.add(acquisition);
            }
        }
        //根据不同类型导出不同的文件
        if (zbList.size() > 0) {
            try {
                String fileName = "导出资本ERP" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
                List<CapitalExport> capitalExports = pickIngService.zbList(zbList, projectId);
                new ExportExcel("导出资本ERP", CapitalExport.class).setDataList(capitalExports).write(response, fileName).dispose();
                List<Acquisition> updateList = new ArrayList<>();
                List<String> selectList = new ArrayList<>();
                //修改项目状态可以进场
                for (Acquisition acquisition : zbList
                ) {
                    //获取可以进场的项目信息
                    if ("1".equals(acquisition.getCanEnter())) {
                        updateList.add(acquisition);
                        selectList.add(acquisition.getId());
                    }
                }
                //变更状态
                if (updateList.size() > 0) {
                    pickIngService.updateEnterList(updateList);
                }
                if (selectList.size() > 0) {
                    //根据变更的id，查询改同储备项目名称下的领料单，判断是否已经都可进场，若可以进场，修改对应项目的项目状态
                    List<Acquisition> erpType1 = pickIngService.findErpAll(selectList);
                    Map<String, String> map = new HashMap<>();
                    for (Acquisition acquisition : erpType1
                    ) {
                        if (map.containsKey(acquisition.getReserveProjectName())) {
                            //获得key值对应的value值，如果是1-未完成领料，不修改值，如果是2-完成领料，判断该项目下的其它领料单状态，修改状态
                            String keyValue = map.get(acquisition.getReserveProjectName());
                            if ("2".equals(keyValue)) {
                                if ("2".equals(acquisition.getCanEnter())) {
                                    map.put(acquisition.getReserveProjectName(), "2");
                                } else {
                                    map.put(acquisition.getReserveProjectName(), "1");
                                }
                            }
                        } else {
                            if ("2".equals(acquisition.getCanEnter())) {
                                map.put(acquisition.getReserveProjectName(), "2");
                            } else {
                                map.put(acquisition.getReserveProjectName(), "1");
                            }
                        }
                    }
                    List<String> updateProjectList = new ArrayList<>();
                    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> next = iterator.next();
                        String key = next.getKey();
                        String value = next.getValue();
                        if ("2".equals(value)) {
                            updateProjectList.add(key);
                        }
                    }
                    if (updateProjectList.size() > 0) {
                        pickIngService.updateProjectEnter(updateProjectList);
                        for (String name :
                                updateProjectList) {
                            //查询出所有更改项目状态的信息，判断是否完成土建流程，发送施工流程
                            Project byName = projectService.findByName(name);
                            if ("0".equals(byName.getConstructionStatus())) {
                                //判断是否包含电气
                                boolean electric = false;
                                //判单钢管杠，水泥杠，存在电气，判断是否包含
                                List<MaterialInfo> allInfo = projectService.findAllInfo(byName.getId());
                                if (allInfo.size() > 0) {
                                    for (MaterialInfo mi : allInfo
                                    ) {
                                        String materialName = mi.getMaterialName();
                                        if (null != materialName && !"".equals(materialName)) {
                                            //判断项目是否包含描述为钢管杆或水泥杠的物料，存在步入电气流程
                                            if (materialName.contains("钢管杆") || materialName.contains("水泥杆")) {
                                                electric = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                //查询出项目的基础信息，停电线路（如果纯在），人员流转信息
                                Construction blockAss = projectService.findBlockAss(byName.getId());
                                Map<String, Object> vars = Maps.newHashMap();
                                //没用电气及涉电 运行条件
                                vars.put("no", false);
                                //没有电气，有涉电 运行条件
                                vars.put("notContain", false);
                                //包含电气/涉电-优先电气 运行条件
                                vars.put("electrical", false);
                                if (electric) {
                                    //发送开始电气流程
                                    vars.put("electrical", true);
                                } else {
                                    //没用电气进行涉电
                                    //获取项目的领料单，查询停电线路
                                    String blackoutLine = blockAss.getQuantity().getBlackoutLine();
                                    if (null != blackoutLine && !"".equals(blackoutLine) && !"不涉电".equals(blackoutLine)) {
                                        //填写停电线路,不为空，-步入发起涉电流程
                                        vars.put("notContain", true);
                                    } else {
                                        vars.put("no", true);
                                    }
                                }
                                MaterialModule materialModule = new MaterialModule();
                                if (StringUtils.isBlank(materialModule.getId())) {
                                    vars.put("manager", UserUtils.getByUserName(blockAss.getAssignment().getConstructionManage()).getLoginName());
                                    materialModule.setProjectId(blockAss.getProjectId());
                                    materialModule.setProjectName(blockAss.getProjectName());
                                    materialModule.setReserveProjectName(blockAss.getReserveProjectName());
                                    //保存项目储备项目名称，项目定义号，项目名称
                                    materialModuleService.save(materialModule);
                                    //修改项目状态
                                    materialModuleService.updateConstructionStatus("1", blockAss.getReserveProjectName());
                                    String procDefId = projectService.findDefId("sgys");
                                    // 启动流程
                                    ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                                    String title = materialModule.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                                    actTaskService.startProcess(p.getKey(), "sg_construction_process", materialModule.getId(), title, vars);
                                }
                            }
                        }
                    }
                }
                j.setSuccess(true);
                j.setMsg("导出成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                String fileName = "没有对应的项目信息" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
                List<CapitalExport> nullExports = new ArrayList<>();
                new ExportExcel("没有对应的项目信息", CapitalExport.class).setDataList(nullExports).write(response, fileName).dispose();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //需改导出状态及导出时间
        return j;
    }

    /**
     * 导出领料清单
     */
    @ResponseBody
    @RequestMapping(value = "exportBlock")
    public AjaxJson exportBlock(String procInsId, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            procInsId = URLDecoder.decode(procInsId, "UTF-8");
            String fileName = "导出领料清单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            List<ExportBlock> exportBlock = pickIngService.findExportBlock(procInsId);
            new ExportExcel("导出领料清单", ExportBlock.class).setDataList(exportBlock).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
        } catch (IOException e) {
            j.setSuccess(false);
            j.setMsg("导出有误！");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 导出模块清单
     */
    @ResponseBody
    @RequestMapping(value = "exportListing")
    public AjaxJson exportListing(String procInsId, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            procInsId = URLDecoder.decode(procInsId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ArrayList<String> objects = new ArrayList<>();
        ArrayList<String> findList = new ArrayList<>();
        String item = showListService.itemQuery(procInsId);
        //返回给页面的list
        List<ShowList> myList = new ArrayList<>();
        if (item != null && !"".equals(item)) {
            String[] split = item.split(";");
            //回显list
            List<ExportListing> returnList = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                objects.add(split[i]);
            }
            for (String s : objects) {
                String[] split1 = s.split(":");
                ShowList myShow = new ShowList();
                myShow.setId(split1[0]);
                String s1 = split1[1];
                myShow.setNumber(Double.parseDouble(s1));
                findList.add(split1[0]);
                myList.add(myShow);
            }
            List<ExportListing> exportListings = showListService.exportListing(findList);
            for (ShowList my : myList) {
                //循环遍历
                for (ExportListing showList1 : exportListings) {
                    //选择的模块与查出来的一致
                    if (my.getId().equals(showList1.getBlockId())) {
                        Double mdSingleWeight = Double.valueOf(showList1.getMdSingleWeight());
                        Double number = my.getNumber();
                        Double mdCount = Double.valueOf(showList1.getMdCount());
                        Double i = mdSingleWeight * number;
                        BigDecimal b1 = new BigDecimal(Double.toString(number));
                        BigDecimal b2 = new BigDecimal(Double.toString(mdCount));
                        String s = b1.multiply(b2).toString();
                        ExportListing newShowList = new ExportListing();
                        newShowList.setMdBigClass(showList1.getMdBigClass());
                        newShowList.setMdTheClass(showList1.getMdTheClass());
                        newShowList.setMdName(showList1.getMdName());
                        newShowList.setMaterialCode(showList1.getMaterialCode());
                        newShowList.setMaterialDescription(showList1.getMaterialDescription());
                        newShowList.setExtensionDescription(showList1.getExtensionDescription());
                        newShowList.setMdUnits(showList1.getMdUnits());
                        newShowList.setMdTheParty(showList1.getMdTheParty());
                        newShowList.setMdText(showList1.getMdText());
                        newShowList.setMdTotalAmount(s);
                        newShowList.setMdSingleWeight(showList1.getMdSingleWeight());
                        BigDecimal b = new BigDecimal(i);
                        BigDecimal a = new BigDecimal(1000);
                        BigDecimal divide = b.divide(a, 4, BigDecimal.ROUND_HALF_UP);
                        newShowList.setMdTotalWeight(divide.toString());
                        returnList.add(newShowList);
                    }
                }
            }
            try {
                String fileName = "导出模块清单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
                new ExportExcel("导出模块清单", ExportListing.class).setDataList(returnList).write(response, fileName).dispose();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        j.setSuccess(true);
        j.setMsg("导出成功！");
        return j;
    }

    /**
     * 修改项目的是否可以经常状态
     */
    @ResponseBody
    @RequestMapping(value = "updateCanEnter")
    public AjaxJson updateCanEnter(Act act) {
        AjaxJson j = new AjaxJson();
        //获取流程定义号，更具定义号获取项目的储备项目名称
        String procInsId = act.getProcInsId();
        //修改项目信息中的是否可以进场
        pickIngService.updateEnter(procInsId);
        j.setMsg("进场成功！");
        return j;
    }
}


