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

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.core.persistence.Page;
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.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
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.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.util.ArrayList;
import java.util.List;
import java.util.Map;

@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;

    /**
     * 填写项目表
     */
    @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.getAct().getProcInsId());
        model.addAttribute("projectNumber",projectNumber);
        return "modules/sg/picking/activiti/constructionLeader";
    }

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

//    constructionLeaderForm.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 project = projectService.get(projectId);
        model.addAttribute("pickApplication", pickApplication);
        model.addAttribute("project", project);
        return "modules/sg/picking/activiti/applicationAudit";
    }


/*    //    manager
    @ResponseBody
    @RequestMapping(value = "constructionData")
    public Map<String, Object> constructionData(ShowList showList, String procInsId, HttpServletRequest request, HttpServletResponse response, Model model) {
        String item = pickIngService.findSelectNumber(procInsId);
        ArrayList<String> objects = new ArrayList<>();
        ArrayList<String> findList = new ArrayList<>();
        //返回给页面的list
        List<ShowList> myList = new ArrayList<>();
        if (item != null && !"".equals(item)) {
            String[] split = item.split(";");
            //回显list
            List<ShowList> 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);
            }
            showList.setFindList(findList);
            Page<ShowList> page = showListService.findPage(new Page<ShowList>(request, response), showList);
            //查询出来所有的模块清单数据
            List<ShowList> list = page.getList();
            //前端传来选择的模块与数量
            for (ShowList my : myList) {
                //循环遍历
                for (ShowList showList1 : list) {
                    //选择的模块与查出来的一致
                    if (my.getId().equals(showList1.getBlockId())) {
                        Double mdSingleWeight = showList1.getMdSingleWeight();
                        Double number = my.getNumber();
                        Double i = mdSingleWeight * number;
                        ShowList newShowList = new ShowList();
                        newShowList.setMaterialCode(showList1.getMaterialCode());
                        newShowList.setMaterialDescription(showList1.getMaterialDescription());
                        newShowList.setExtensionDescription(showList1.getExtensionDescription());
                        newShowList.setMdUnits(showList1.getMdUnits());
                        newShowList.setMeTheParty(showList1.getMeTheParty());
                        newShowList.setMdText(showList1.getMdText());
                        newShowList.setMdTotalAmount(number);
                        newShowList.setMdSingleWeight(showList1.getMdSingleWeight());
                        newShowList.setMdTotalWeight(i / 1000);
                        newShowList.setBlockId(showList1.getBlockId());
                        returnList.add(newShowList);
                    }
                }
            }
            List<ShowList> finalList = new ArrayList<>();
            boolean flag;
            for (ShowList turn : returnList) {
                flag = true;
                for (ShowList list1 : finalList) {
                    if (turn.getMaterialCode().equals(list1.getMaterialCode()) && turn.getMaterialDescription().equals(list1.getMaterialDescription()) && turn.getExtensionDescription().equals(list1.getExtensionDescription())) {
                        list1.setMdTotalAmount(list1.getMdTotalAmount() + turn.getMdTotalAmount());
                        list1.setMdTotalWeight(list1.getMdTotalWeight() + turn.getMdTotalWeight());
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    showList = new ShowList();
                    showList.setMaterialCode(turn.getMaterialCode());
                    showList.setMaterialDescription(turn.getMaterialDescription());
                    showList.setExtensionDescription(turn.getExtensionDescription());
                    showList.setMdUnits(turn.getMdUnits());
                    showList.setMeTheParty(turn.getMeTheParty());
                    showList.setMdText(turn.getMdText());
                    showList.setMdTotalAmount(turn.getMdTotalAmount());
                    showList.setMdSingleWeight(turn.getMdSingleWeight());
                    showList.setMdTotalWeight(turn.getMdTotalWeight());
                    showList.setBlockId(turn.getBlockId());
                    finalList.add(showList);
                }
            }
            page.setList(finalList);
            return getBootstrapData(page);
        } else {
            findList.add("没有数据");
            showList.setFindList(findList);
            Page<ShowList> page = showListService.findPage(new Page<ShowList>(request, response), showList);
            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;
        }
        /**
         * 流程审批
         */
        if (StringUtils.isBlank(showList.getId())) {
            String number = showListService.findNumber(showList.getProjectId());
            if (number == null || "".equals(number)) {
                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);
            }
            //新增或编辑表单保存
            showListService.save(showList);//保存
            // 启动流程
            Map<String, Object> vars = Maps.newHashMap();
            vars.put("manager", UserUtils.getUser().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();
        //配网政策处理专职
        String s = constructionService.nameFindOffice(loginName);
        if ("配网政策处理专职".equals(s)) {
            vars.put("full", true);
            vars.put("manager", "项目经理A");
            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;
    }


}

