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

import java.net.URLDecoder;

import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.web.BaseController;
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.entity.Disclose;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.FindTask;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.activiti.service.DiscloseService;
import com.jeeplus.modules.sg.managementcenter.activiti.service.UploadImagesService;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyImportUtils;
import org.activiti.engine.*;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 施工交底Controller
 *
 * @author
 * @version 2019-11-08
 */
@Controller
@RequestMapping(value = "${adminPath}/managementcenter/divide")

public class DivideController extends BaseController {

    @Autowired
    private ConstructionService constructionService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private DiscloseService discloseService;
    @Autowired
    private UploadImagesService uploadImagesService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;


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


//	/**
//	 * 文件管理列表数据
//	@ResponseBody
//	@RequestMapping(value = "data")
//	public Map<String, Object> data(UploadImages uploadImages, HttpServletRequest request, HttpServletResponse response, Model model) {
//		Page<UploadImages> page = uploadImagesService.findPage(new Page<UploadImages>(request, response), uploadImages);
//		return getBootstrapData(page);
//	}*/



    /**
     * 查看，增加，编辑请假申请表单页面
     */
    @RequestMapping(value = "divideForm")
    public String form(Construction construction, Model model) {
        model.addAttribute("construction", construction);
            //项目经理组织交底
            Disclose disclose = construction.getDisclose();
            if (disclose == null) {
                model.addAttribute("pass_construction7","0");
            } else {
                MyImportUtils.getTheEcho(construction,model);
            }
            return "modules/sg/managementcenter/activiti/divideForm";
    }

    /**
     * 保存请假申请
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(Disclose disclose, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(disclose);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }


        /**
         * 流程审批
         */
        /*if (StringUtils.isBlank(disclose.getId())) {
            //新增或编辑表单保存
            discloseService.save(disclose);//保存
            // 启动流程
            ProcessDefinition p = actProcessService.getProcessDefinition(disclose.getAct().getProcDefId());
            String title = disclose.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            actTaskService.startProcess(p.getKey(), "xm_construction_clarificaiton", disclose.getId(), title);
            j.setMsg("发起流程审批成功!");
            j.getBody().put("targetUrl", "/act/task/process/");
        } else {
            //新增或编辑表单保存
            discloseService.save(disclose);//保存
            disclose.getAct().setComment(("yes".equals(disclose.getAct().getFlag()) ? "[重新申请] " : "[销毁申请] "));
            // 完成流程任务
            Map<String, Object> vars = Maps.newHashMap();
            vars.put("reapply", "yes".equals(disclose.getAct().getFlag()) ? true : false);
            actTaskService.complete(disclose.getAct().getTaskId(), disclose.getAct().getProcInsId(), disclose.getAct().getComment(), disclose.getContent(), vars);
            j.setMsg("提交成功！");
            j.getBody().put("targetUrl", "/act/task/todo/");
        }*/
        return j;
    }


    /**
     * 项目经理审核时使用交底结论
     * */
    @ResponseBody
    @RequestMapping(value = "importConclusion")
    public AjaxJson importConclusion(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request,String procInsId,String projectName){
        AjaxJson j = new AjaxJson();
        /*try {
            projectName = URLDecoder.decode(projectName, "UTF-8");
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            int lastDataRowNum = ei.getLastDataRowNum();
            Disclose disclose = new Disclose();
            disclose.setProcInsId(procInsId);
            for (int i = 2; i < lastDataRowNum; i++) {
                Row row = ei.getRow(i);
                String requireName = ei.getCellValue(row, 1).toString();
                if (projectName.equals(requireName)) {
                    disclose.setRequireName(requireName);
                    disclose.setConId(requireName);
                    disclose.setProjectNumber(ei.getCellValue(row, 2).toString());
                    disclose.setProjectName(ei.getCellValue(row, 3).toString());
                    disclose.setProjectId(ei.getCellValue(row, 4).toString());
                    disclose.setChannel(ei.getCellValue(row, 5).toString());
                    disclose.setCapacity(ei.getCellValue(row, 6).toString());
                    disclose.setSceneSize(ei.getCellValue(row, 7).toString());
                    disclose.setCapacitySize(ei.getCellValue(row, 8).toString());
                    disclose.setHiddenDanger(ei.getCellValue(row, 9).toString());
                    disclose.setInfluenceConstruction(ei.getCellValue(row, 10).toString());
                    disclose.setProjectRepetition(ei.getCellValue(row, 11).toString());
                    disclose.setImplemented(ei.getCellValue(row, 12).toString());
                    disclose.setTransformer(ei.getCellValue(row, 13).toString());
                    disclose.setExplanationOfNecessity(ei.getCellValue(row, 14).toString());
                    disclose.setLineName(ei.getCellValue(row, 15).toString());
                    disclose.setQuantities(ei.getCellValue(row, 16).toString());
                    disclose.setInconsistentDescription(ei.getCellValue(row, 17).toString());
                    disclose.setAdministrationType(ei.getCellValue(row, 18).toString());
                    disclose.setPolicyHandlingInstructions(ei.getCellValue(row, 19).toString());
                    disclose.setPrecondition(ei.getCellValue(row, 20).toString());
                    disclose.setPlacementMode(ei.getCellValue(row, 21).toString());
                    disclose.setProductionDate(ei.getCellValue(row, 22).toString());
                    disclose.setIntegrateModule(ei.getCellValue(row, 23).toString());
                    disclose.setNeedReplace(ei.getCellValue(row, 24).toString());
                    disclose.setOverallTransformation(ei.getCellValue(row, 25).toString());
                    disclose.setOtherProblem(ei.getCellValue(row, 26).toString());
                }
            }
            try {
                if (null!=disclose.getRequireName()&&!"".equals(disclose.getRequireName())){
                    String humanReviewJudge = MyImportUtils.getHumanReviewJudge(disclose);
                    if (!"".equals(humanReviewJudge)){
                        j.setSuccess(false);
                        j.setMsg(humanReviewJudge);
                        return j;
                    }
                }else {
                    j.setSuccess(false);
                    j.setMsg("导入数据不符合规范");
                    return j;
                }
                discloseService.updateById(disclose);
                successNum++;
            } catch (Exception ex) {
                failureNum++;
                ex.printStackTrace();
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 记录。");
            }
            j.setMsg("已成功导入 " + successNum + " 记录" + failureMsg);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }*/
        return j;
    }



    /**
     * 项目经理组织交底使用导入
     */
//    @RequiresPermissions("modules:sg:information:information:import")
    @ResponseBody
    @RequestMapping(value = "importConclusion1")
    public AjaxJson importConclusion1(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        int successNum = 0;
        boolean flag = true;
        String failureMsg = "";
        //将当前经理负责的项目导入的交底结论循环
        //做数据验证，验证成功的记录，不成功的抛出异常
        //验证成功的list插入数据库
        List<Disclose> discloseList = new ArrayList<>();
        //获取当前登陆用户所有在《交底:项目经理组织交底》节点的流程

        //读取文件记录在数组中
        /*try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            int lastDataRowNum = ei.getLastDataRowNum();
            Disclose disclose;
            //将所有项目信息存入list
            for (int i = 2; i < lastDataRowNum; i++) {
                disclose = new Disclose();
                Row row = ei.getRow(i);
                disclose.setRequireName(ei.getCellValue(row, 1).toString());//需求项目名称
                disclose.setConId(ei.getCellValue(row, 1).toString());//项目信息id
                disclose.setProjectNumber(ei.getCellValue(row, 2).toString());//工程编号
                disclose.setProjectName(ei.getCellValue(row, 3).toString());//项目名称
                disclose.setProjectId(ei.getCellValue(row, 4).toString());//项目定义号
                disclose.setChannel(ei.getCellValue(row, 5).toString());//施工通道
                disclose.setCapacity(ei.getCellValue(row, 6).toString()); //设备基础是否可以扩容
                disclose.setSceneSize(ei.getCellValue(row, 7).toString());//现场设备尺寸
                disclose.setCapacitySize(ei.getCellValue(row, 8).toString());//最多可扩容尺寸
                disclose.setHiddenDanger(ei.getCellValue(row, 9).toString());//方案安全隐患
                disclose.setInfluenceConstruction(ei.getCellValue(row, 10).toString());//是否存在低压或通信线等影响施工
                disclose.setProjectRepetition(ei.getCellValue(row, 11).toString());//立项重复
                disclose.setImplemented(ei.getCellValue(row, 12).toString());//是否已实施
                disclose.setTransformer(ei.getCellValue(row, 13).toString());//变压器无负荷
                disclose.setExplanationOfNecessity(ei.getCellValue(row, 14).toString());//必要性问题说明
                disclose.setLineName(ei.getCellValue(row, 15).toString());//线路名称、设备、开关、杆号一致性
                disclose.setQuantities(ei.getCellValue(row, 16).toString());//工程量是否一致
                disclose.setInconsistentDescription(ei.getCellValue(row, 17).toString()); //图纸现场不一致说明
                disclose.setAdministrationType(ei.getCellValue(row, 18).toString());//政处类型
                disclose.setPolicyHandlingInstructions(ei.getCellValue(row, 19).toString());//政策处理说明
                disclose.setPrecondition(ei.getCellValue(row, 20).toString());//前置条件
                disclose.setPlacementMode(ei.getCellValue(row, 21).toString()); //DTU安放方式核查
                disclose.setProductionDate(ei.getCellValue(row, 22).toString());//核查环网柜生产日期
                disclose.setIntegrateModule(ei.getCellValue(row, 23).toString()); //二次是否是集成模块
                disclose.setNeedReplace(ei.getCellValue(row, 24).toString());//PT是否需要更换
                disclose.setOverallTransformation(ei.getCellValue(row, 25).toString());//设备是否有整体改造的必要
                disclose.setOtherProblem(ei.getCellValue(row, 26).toString());//其它问题描述
                discloseList.add(disclose);
            }
            //记录所有符合情况的数据
            Map<String,Object> stringListMap = MyImportUtils.errorTips(discloseList);
            String fin = (String)stringListMap.get("fin");
            //所有填写标准的数据
            List<Disclose> discloseList1 = (List<Disclose>) stringListMap.get("newDiscloseList");
            MyActiviUtils myActiviUtils = new MyActiviUtils();
            //所有当前用户项目经理组织交底的流程信息
            List<FindTask> activity = myActiviUtils.findActivity("交底:项目经理组织交底");

            List<Disclose> taskList = new ArrayList<>();
            for (FindTask f : activity) {
                String projectName = f.getProjectName();
                for (Disclose d: discloseList1) {
                    String requireName = d.getRequireName();
                    if (projectName.equals(requireName)) {
                        d.setProcInsId(f.getPrInsId());
                        d.setTaskId(f.getTaskId());
                        taskList.add(d);
                    }
                }
            }
            if (taskList.size() > 0) {
                //存入数据库
                int i = discloseService.newInsert(taskList);
                for (Disclose d : taskList) {
                    Map<String, Object> vars = Maps.newHashMap();
                    String precondition = d.getPrecondition();
//                    Project user = MyActiviUtils.findUser(d.getProcInsId());
                    //通过页面修改施工交底
                    vars.put("self", false);
                    //完成施工交底
                    vars.put("finish", false);
                    //完成施工交底
                    vars.put("problem",false);
                    //前置条件，人工判断
                    vars.put("pass4",false);
                    //判断是否有前置条件
                    if ((d.getOtherProblem() != null && !"".equals(d.getOtherProblem()))
                        ||(precondition != null && !"".equals(precondition))
                        || (d.getChannel() != null && !"".equals(d.getChannel()) && !"无".equals(d.getChannel()))
                    ) {
                        vars.put("problem", false);
                        vars.put("pass4", true);
//                        vars.put("processer", UserUtils.getByUserName(user.getProjectManageRole()).getLoginName());
                    } else {
                        //没有前置条件，判断是否为无问题
                        if (
                                "无".equals(d.getHiddenDanger()) &&
                                        "否".equals(d.getInfluenceConstruction()) &&
                                        "否".equals(d.getProjectRepetition()) &&
                                        "否".equals(d.getImplemented()) &&
                                        "有".equals(d.getTransformer()) &&
                                        "一致".equals(d.getLineName()) &&
                                        "是".equals(d.getQuantities()) &&
                                        "4.无".equals(d.getAdministrationType())
                        ) {
                            vars.put("finish", true);
                        } else {
                            vars.put("pass4", false);
                            vars.put("problem", true);
//                            vars.put("processer", UserUtils.getByUserName(user.getProjectManageRole()).getLoginName());
                        }
                    }
                    actTaskService.complete(d.getTaskId(), d.getProcInsId(), "系统判断成功，请自行查看", vars);
                }
            }
            j.setMsg("已成功导入 " + taskList.size() + " 记录" + fin);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息：" + e.getMessage());
        }*/
        return j;
    }

}