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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.alterinfo.entity.AlterInfo;
import com.jeeplus.modules.alterinfo.service.AlterInfoService;
import com.jeeplus.modules.contractclient.service.WorkContractClientService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.RoleActivityEnname;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysimportinfo.entity.SysImportInfo;
import com.jeeplus.modules.sysimportinfo.service.SysImportInfoService;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractInfoCopyDao;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractReview;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workcontractinfo.service.WorkContractReviewService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workfullmanage.service.WorkFullRecordService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.Logical;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * 合同管理Controller
 *
 * @author 丁旭
 * @version 2017-03-21
 */
@Controller
@RequestMapping(value = "${adminPath}/workcontractinfoi/workContractInfoI")
public class WorkContractInfoInvalidateController extends BaseController {

    @Autowired
    private AlterInfoService alterInfoService;
    @Autowired
    private WorkContractInfoService workContractInfoService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private WorkClientInfoService workClientInfoService;
    @Autowired
    private WorkContractInfoCopyDao workContractInfoCopyDao;
    @Autowired
    private WorkContractClientService workContractClientService;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private WorkClientAttachmentDao workClientAttachmentDao;

    @Autowired
    private WorkFullRecordService workFullRecordService;

    @Autowired
    private OfficeService officeService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private WorkContractReviewService workContractReviewService;
    @Autowired
    private SysImportInfoService sysImportInfoService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

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

        }
        return entity;
    }

    //合同作废列表
    //@RequiresPermissions("workcontractinfo:workContractInfo:list")
    @RequestMapping(value = {"ilist", ""})
    public String ilist(WorkContractInfo workContractInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        workContractInfo.setCurrentUser(user);
        workContractInfo.setOfficeId(UserUtils.getSelectOffice().getId());
        Page<WorkContractInfo> page = workContractInfoService.ifindPage(new Page<WorkContractInfo>(request, response), workContractInfo);
        model.addAttribute("page", page);
        return "modules/workcontractinfo/workContractInfoInvalidateList";
    }
    /**
     * 合同作废：删除作废信息
     */
    @RequestMapping("deleteInvalidate")
    public String deleteInvalidate(WorkContractInfo workContractInfo,RedirectAttributes redirectAttributes){
        workContractInfoService.deleteInvalidate(workContractInfo);
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/list/?repage";

    }

    /**
     * 合同作废：强制撤销
     */
    @RequestMapping("cancelInvalidate")
    public String cancelInvalidate(WorkContractInfo workContractInfo,RedirectAttributes redirectAttributes){
        workContractInfoService.cancelInvalidate(workContractInfo);
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/list/?repage";

    }

    /**
     * 合同作废：重申|撤销
     */
    @RequestMapping("invalidateReapply")
    public String invalidateReapply(){


        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/list/?repage";
    }

    /**
     * 审批合同作废申请
     */
    @SuppressWarnings("all")
    @RequestMapping("invalidateContractSaveAudit")
    public String invalidateContractSaveAudit(WorkContractInfo workContractInfo,HttpServletRequest request, Model model,RedirectAttributes redirectAttributes){
        String reapply = request.getParameter("reapply");
        if(StringUtils.isNotBlank(reapply)){



            ProcessInstance processInstance = actTaskService.getProcIns(workContractInfo.getInvalidateProcessInstanceId());
            if (processInstance!=null) {
                Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                Act act = new Act();
                act.setTaskId(taskInfok.getId());
                act.setTaskName(taskInfok.getName());
                act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                act.setProcDefId(taskInfok.getProcessDefinitionId());
                act.setProcInsId(taskInfok.getProcessInstanceId());
                act.setTask(taskInfok);
                if("yes".equals(reapply)){act.setFlag("yes");}//重新申请
                //由于后期改成了"强制撤销"，这里的不用了
                //if("no".equals(reapply)){act.setFlag("no");}//撤销
                workContractInfo.setAct(act);
            }

        }

        //String message = workContractInfoService.invalidateContractSaveAudit(workContractInfo);
        //addMessage(redirectAttributes,message);

        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/list/?repage";
    }

    /**
     * 打开合同作废审批页面
     */
    @RequestMapping(value = "contractInvalidateAudit")
    public String contractInvalidateAudit(Act act, WorkContractInfo workContractInfo, Model model) {

        String view = "contractInvalidateAudit";

        if (act.getProcInsId() != null) {
            if (actTaskService.getProcIns(act.getProcInsId()) != null) {
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            } else {
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
            workContractInfo.setAct(act);
            model.addAttribute("processInstanceId", workContractInfo.getInvalidateProcessInstanceId());
        }
        // 环节编号,默认是 "bmzrAudit"
        String taskDefKey = workContractInfo.getAct().getTaskDefKey();

        model.addAttribute("workContractInfo", workContractInfo);
        return "modules/workcontractinfo/"+view;
    }



    /**
     * 启动合同作废invalidateProcessInstanceId
     */
    @RequestMapping("contractInvalidateStart")
    public String contractInvalidateStart(WorkContractInfo workContractInfo,HttpServletRequest request, Model model,RedirectAttributes redirectAttributes){
        String reason = request.getParameter("reason");
        //workContractInfoService.contractInvalidateStart(workContractInfo,reason);
        return "modules/workcontractinfo/contractInvalidateForm";
    }

    /**
     * 打开合同作废表单，填写作废理由
     */
    @RequestMapping("contractInvalidateForm")
    public String contractInvalidateForm(WorkContractInfo workContractInfo,Model model){
        AlterInfo alterInfo = alterInfoService.getByContractInfo(workContractInfo);
        model.addAttribute("workContractInfo",workContractInfo);
        model.addAttribute("alterInfo",alterInfo);
        return "modules/workcontractinfo/contractInvalidateForm";
    }

    /**
     * 查询已办列表
     *
     * @return
     */
    @RequestMapping("/HistoryList")
    public String queryCompleteList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {

        //合同申请
        act.setProcDefKey(ActUtils.PD_WORKCONTRACT[0]);
        List<WorkContractInfo> list = workContractInfoService.historicList(act);
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        List<Activity> activities = activityService.groupByActivityMenu("zth3125f1f194c82bdea93555c750905",companyId);
        for (Activity activity:activities){
            act.setProcDefKey(activity.getProcessKey());
            list.addAll(workContractInfoService.historicList(act));
        }

        //合同作废：默认流程
        act.setProcDefKey(ActUtils.PD_CONTRACTINVALIDATE[0]);
        List<WorkContractInfo> list2 = workContractInfoService.historicList(act);
        list.addAll(list2);
        //合同作废：自定义流程
        List<Activity> activitiesCustom = activityService.groupByActivityMenu("bbecad5bdefd46c48591166170fe6dce",companyId);
        for (Activity activity:activitiesCustom){
            act.setProcDefKey(activity.getProcessKey());
            list.addAll(workContractInfoService.historicList(act));
        }

        //合同变更
        act.setProcDefKey("contractalter");
        List<Activity> activities3 = activityService.groupByActivityMenu("1663125f1f194c82bdea93555c750904",companyId);
        for (Activity activity:activities3){
            act.setProcDefKey(activity.getProcessKey());
            list.addAll(workContractInfoService.historicList(act));
        }
       /* List<CaseInfo> lists = new ArrayList<CaseInfo>();
        for (Act a : list) {
            CaseInfo caseInfo = caseInfoService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
            if (caseInfo != null && caseInfo.getCompanyId().equals(companyId)) {
                if (a.getVars().getMap().get("applyUserId")!=null){
                    a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                }
                caseInfo.setAct(a);
				*//*if (com.jeeplus.common.	utils.StringUtils.isNotBlank(caseInfo.getId())){
					caseInfo.setName(officeService.get(companyId).getName());
				}*//*
                lists.add(caseInfo);
            }
        }*/


        model.addAttribute("list", list);
        return "modules/workcontractinfo/workContractHistoryList";
    }

    /**
     * 查询待办任务
     *
     * @param act
     * @param model
     * @return
     */
    @RequestMapping("/toDoList")
    public String queryToList(Act act, Model model) {

        //合同申请流程
        act.setProcDefKey(ActUtils.PD_WORKCONTRACT[0]);
        List<Act> list = actTaskService.todoList(act);
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        List<Activity> activities = activityService.groupByActivityMenu("zth3125f1f194c82bdea93555c750905",companyId);
        for (Activity activity:activities){
            act.setProcDefKey(activity.getProcessKey());
            list.addAll(actTaskService.todoList(act));
        }

        //合同作废：默认流程
        act.setProcDefKey(ActUtils.PD_CONTRACTINVALIDATE[0]);
        List<Act> list2 = actTaskService.todoList(act);
        list.addAll(list2);
        //合同作废，自定义流程
        List<Activity> activitiesCustom = activityService.groupByActivityMenu("bbecad5bdefd46c48591166170fe6dce",companyId);
        for (Activity activity:activitiesCustom){
            act.setProcDefKey(activity.getProcessKey());
            list.addAll(actTaskService.todoList(act));
        }

        Role role = UserUtils.getSelectRole().get(0);
        List<WorkContractInfo> lists = new ArrayList<WorkContractInfo>();
        for (Act a : list) {
            if (a.getTask().getTaskDefinitionKey()!=null && !"modifyApply".equals(a.getTask().getTaskDefinitionKey()) && !a.getTask().getTaskDefinitionKey().contains("audit")) {
                WorkContractInfo contractInfo = workContractInfoService.getByProcessInstanceId(a.getProcInsId());
                if(contractInfo == null){
                    //合同作废：默认流程
                    contractInfo = workContractInfoService.getByInvalidateProcessInstanceId(a.getProcInsId());
                    if(contractInfo == null){
                        continue;
                    }else {
                        contractInfo.setAuditType("合同作废");
                        contractInfo.setAct(a);
                        lists.add(contractInfo);
                    }
                }else {
                    contractInfo.setAuditType("合同申请");
                }
                if(contractInfo.getContractState() !=null && !contractInfo.getContractState().equals("5")) {
                    if (contractInfo != null && contractInfo.getCompanyId().equals(companyId)) {
                        contractInfo.setCreateBy(UserUtils.get(contractInfo.getCreateBy().getId()));
                        if (a.getVars().getMap().get("applyUserId") != null) {
                            User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
                            if (user != null) {
                                a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                            }
                        }
                        contractInfo.setAct(a);
                        lists.add(contractInfo);
                    }
                }
            }
        }
        /*------变更--------*/
        act.setProcDefKey("contractalter");
        List<Act> list3 = actTaskService.todoList(act);
        Office office3 = UserUtils.getSelectCompany();
        String companyId3 = office3==null?"":office3.getId();
        List<Activity> activities3 = activityService.groupByActivityMenu("1663125f1f194c82bdea93555c750904",companyId3);
        for (Activity activity:activities3){
            act.setProcDefKey(activity.getProcessKey());
            list3.addAll(actTaskService.todoList(act));
        }

        for (Act a : list3) {
			/*CaseInfo caseInfo = caseInfoService.getByProcessInstanceId(a.getProcInsId());*/
            WorkContractInfo workContractInfo = workContractInfoService.getByProcessInstanceId(a.getTask().getProcessInstanceId());
            if (workContractInfo != null && workContractInfo.getCompanyId().equals(companyId3)&& workContractInfo.getAlterState()!=null && workContractInfo.getAlterState().equals("2")) {
                if (workContractInfo.getRemarks()==null || !workContractInfo.getRemarks().equals("重新申请")) {
                    if (a.getVars().getMap().get("applyUserId") != null) {
                        User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
                        if (user != null) {
                            a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
                        }
                    }
                    workContractInfo.setAct(a);
                    workContractInfo.setAuditType("合同变更");
                    lists.add(workContractInfo);
                }
            }
        }

        /*Role role1 = UserUtils.getSelectRole().get(0);
        if(role1.getEnname().endsWith("glygd")){
            model.addAttribute("flag","1");
        }*/

        //排除 重新申请|撤销
        Iterator<WorkContractInfo> it = lists.iterator();
        while(it.hasNext()){
            WorkContractInfo w = it.next();
            if(w.getAct()!=null && w.getAct().getTaskDefKey().equals("reapply")){
                it.remove();
            }
        }

        model.addAttribute("list", lists);
        return "modules/workcontractinfo/workContractToDoList";
    }

    /**
     * 审核信息
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = "contractAlterAudit")
    public String contractAlterAudit(Act act, HttpServletResponse response, Model model) {
        // 获取流程XML上的表单KEY
        String formKey = "/workcontractinfo/workContractInfo/alterForm";
        //logger.info("------formKeys:"+formKeys);
        // 获取流程实例对象
        if (act.getProcInsId() != null){
            if(actTaskService.getProcIns(act.getProcInsId())!=null){
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            }else{
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        return "redirect:" + ActUtils.getFormUrl(formKey, act);
    }

    /**
     * 查看，增加，编辑合同管理表单页面
     */
    @RequiresPermissions(value = {"workcontractinfo:workContractInfo:view", "workcontractinfo:workContractInfo:add", "workcontractinfo:workContractInfo:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(WorkContractInfo workContractInfo, Model model) {
        //getSort(workContractInfo);
        String view = "workContractInfoFormAdd";
        //驳回状态数据操作
        if (StringUtils.isNotBlank(workContractInfo.getId())&&("4").equals(workContractInfo.getContractState())) {
            ProcessInstance processInstance = actTaskService.getProcIns(workContractInfo.getProcessInstanceId());
            if (processInstance != null) {
                Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                Act act = new Act();
                act.setTaskId(taskInfok.getId());
                act.setTaskName(taskInfok.getName());
                act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                act.setProcDefId(taskInfok.getProcessDefinitionId());
                act.setProcInsId(taskInfok.getProcessInstanceId());
                act.setTask(taskInfok);
                workContractInfo.setAct(act);
            }
            view = "workContractInfoFormEdit";
        } else {
            Office office = UserUtils.getSelectOffice();
            workContractInfo.setChargeCompany(office.getId());
            workContractInfo.setChargeCompanyName(office.getName());
            workContractInfo.setRecordState("1");
        }

        model.addAttribute("workContractInfo", workContractInfo);
        return "modules/workcontractinfo/" + view;
    }

    /**
     * 归档页面(暂弃)
     */
    @RequestMapping(value = "forms")
    public String forms(WorkContractInfo workContractInfo, Model model) {
        String view = "workContractInfoFormAdd";
        if (StringUtils.isNotBlank(workContractInfo.getId())) {
            ProcessInstance processInstance = actTaskService.getProcIns(workContractInfo.getProcessInstanceId());
            if (processInstance != null) {
                Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                Act act = new Act();
                act.setTaskId(taskInfok.getId());
                act.setTaskName(taskInfok.getName());
                act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                act.setProcDefId(taskInfok.getProcessDefinitionId());
                act.setProcInsId(taskInfok.getProcessInstanceId());
                act.setTask(taskInfok);
                workContractInfo.setAct(act);
            }
            view = "workContractInfoFormEdits";
        }
        model.addAttribute("workContractInfo", workContractInfo);
        return "modules/workcontractinfo/" + view;
    }

    /**
     * 变更页面
     */
    @RequestMapping(value = "alterForm")
    public String alterForm(WorkContractInfo workContractInfo, Model model) {
        String id = workContractInfo.getId();
        //已签状态且变更状态为空时设id为空。
        if(("5").equals(workContractInfo.getContractState())&&StringUtils.isBlank(workContractInfo.getAlterState())){
            workContractInfo.setAlterBeforeId(workContractInfo.getId());
            workContractInfo.setId(null);
        }
        //变更状态并且有驳回标记
        if(("8").equals(workContractInfo.getContractState())&&("3").equals(workContractInfo.getAlterSign())){
            workContractInfo = workContractInfoService.getByBeforeId(workContractInfo.getId());
        }
        //已签状态并且有暂存标记
        if(("5").equals(workContractInfo.getContractState())&&("1").equals(workContractInfo.getAlterSign())){
            workContractInfo = workContractInfoService.getByBeforeId(id);
        }
        //已签并且已变更
        if(("5").equals(workContractInfo.getContractState())&&("4").equals(workContractInfo.getAlterState())){
            workContractInfo.setAlterBeforeId(workContractInfo.getId());
            workContractInfo.setId(null);
        }
        model.addAttribute("workContractInfo", workContractInfo);
        if (workContractInfo.getAct()!=null && StringUtils.isNotBlank(workContractInfo.getAct().getTaskId())){
            return "modules/workcontractinfo/contractAlterAudit";
        }
        return "modules/workcontractinfo/workContractInfoAlterForm";
    }
    /**
     * 变更合同管理
     * 启动流程信息
     */
    @RequestMapping(value = "alterSave")
    public String alterSave(WorkContractInfo workContractInfo, Model model,
                            RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, workContractInfo)) {
            return form(workContractInfo, model);
        }
        try {
            //判断是否有总合同
            //判断是否有总合同
            if(!Strings.isNullOrEmpty(workContractInfo.getTotalContractId()) && !"0".equals(workContractInfo.getTotalContractId())){
                workContractInfo.setIsTotalName("子合同");
                workContractInfo.setIsTotal(null);
            }else{
                workContractInfo.setIsTotalName("总合同");
                workContractInfo.setIsTotal("1");
                workContractInfo.setTotalContractId("0");
                //workContractInfo.setCommonFlag(IdGen.uuid());
            }
            workContractInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            Role role = UserUtils.getSelectRole().get(0);
            StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
            Map<String, Object> variables = new HashMap<String, Object>();
           /* variables.put("SSRHbmzr", buffer.toString() + "bmzr"); //设置部门负责人
            variables.put("SSRHzjl", buffer.toString() + "zjl");
            variables.put("SSRHdsz", buffer.toString() + "dsz");
            variables.put("SSRHgdgly", buffer.toString() + "glygd");*/
            if (!workContractInfo.getIsNewRecord()) {//编辑表单保存
                WorkContractInfo t = workContractInfoService.get(workContractInfo.getId());//从数据库取出记录的值
                //将编辑表单中的非NULL值覆盖数据库记录中的值
                MyBeanUtils.copyBeanNotNull2Bean(workContractInfo, t);
                t.setCompanyId(UserUtils.getSelectCompany().getId());
                String remarks = t.getRemarks();
                String alterState = t.getAlterState();
                if(StringUtils.isNotBlank(remarks) && remarks.equals("重新申请")){
                    String processInstanceId = t.getProcessInstanceId();
                    HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                    if(historicProcessInstance!=null) {
                        t.setHistoricProcessInstance(historicProcessInstance);
                        t.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
                    } else {
                        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
                        if (processInstance != null){
                            t.setProcessInstance(processInstance);
                            t.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
                        }
                    }
                    ProcessInstance processInstance = actTaskService.getProcIns(t.getProcessInstanceId());
                    if (processInstance!=null) {
                        Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                        Act act = new Act();
                        act.setTaskId(taskInfok.getId());
                        act.setTaskName(taskInfok.getName());
                        act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                        act.setProcDefId(taskInfok.getProcessDefinitionId());
                        act.setProcInsId(taskInfok.getProcessInstanceId());
                        act.setTask(taskInfok);
                        act.setFlag("yes");
                        t.setAct(act);
                    }
                    t.setRemarks("");
                   // workContractInfoService.auditAlterSave(t);
                    workContractInfoService.saves(t);//保存
                    WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                    workContractReview.setContractName(workContractInfo.getName());
                    workContractReviewService.save(workContractReview);

                    addMessage(redirectAttributes, "合同变更已重新申请!");
                }else if(StringUtils.isNotBlank(alterState) && alterState.equals("1")){
                    /*String comId = UserUtils.getUser().getComId();
                    Office office = UserUtils.getSelectOffice();

                    workContractInfo.setCreateCompany(comId);
                    workContractInfo.setCompanyId(comId);
                    workContractInfo.setChargeCompany(office.getId());
                    workContractInfo.setChargeCompanyName(office.getName());*/
                    List<WorkClientAttachment> list = workContractInfo.getWorkAttachments();
                    List<WorkClientAttachment> list1 = new ArrayList<>();
                    List<WorkClientAttachment> list2 = new ArrayList<>();
                    List<WorkClientAttachment> list3 = new ArrayList<>();
                    for (WorkClientAttachment workClientAttachment:list){
                        if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("44")){
                            list1.add(workClientAttachment);
                        }else if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("80")){
                            list2.add(workClientAttachment);
                        }else{
                            list3.add(workClientAttachment);
                        }
                    }
                    workContractInfo.setWorkAttachments(list1);
                    workContractInfo.setWorkAttachments(list3);
                    workContractInfo.setAlterState("2");//变更状态--审批中
                    workContractInfoService.saves(workContractInfo);//保存
                    workContractInfoService.startProcess(workContractInfo,variables);
                    WorkContractInfo workContractInfo1 = workContractInfoService.get(workContractInfo.getAlterBeforeId());
                    workContractInfo1.setContractState("8");//合同状态--变更中
                    workContractInfo1.setAlterSign(null);//标记去除
                    workContractInfoService.saves(workContractInfo1);
                    WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                    workContractReview.setWorkAttachments(list2);
                    workContractReview.setContractName(workContractInfo.getName());
                    workContractReviewService.save(workContractReview);
                    AlterInfo alterInfo = workContractInfo.getAlterInfo();
                    alterInfoService.save(alterInfo);
                    addMessage(redirectAttributes, "变更合同管理送审成功");
                }else {
                    workContractInfoService.saves(t);//保存
                    WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                    workContractReview.setContractName(workContractInfo.getName());
                    workContractReviewService.save(workContractReview);
                    AlterInfo alterInfo = workContractInfo.getAlterInfo();
                    alterInfoService.save(alterInfo);
                    addMessage(redirectAttributes, "修改合同变更成功");
                }
            } else {//新增表单保存
                //第一次创建都只能给部门负责人审核
                WorkContractInfo workContractInfo1 = workContractInfoService.get(workContractInfo.getAlterBeforeId());
                if(workContractInfo1!=null){
                    workContractInfo.setCreateName(workContractInfo1.getCreateName());
                    workContractInfo.setCreateCompany(workContractInfo1.getCreateCompany());
                    workContractInfo.setCompanyId(workContractInfo1.getCompanyId());
                    workContractInfo.setChargeCompany(workContractInfo1.getChargeCompany());
                    workContractInfo.setChargeCompanyName(workContractInfo1.getChargeCompanyName());
                }
                List<WorkClientAttachment> list = workContractInfo.getWorkAttachments();
                List<WorkClientAttachment> list1 = new ArrayList<>();
                List<WorkClientAttachment> list2 = new ArrayList<>();
                List<WorkClientAttachment> list3 = new ArrayList<>();
                for (WorkClientAttachment workClientAttachment:list){
                    if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("44")){
                        list1.add(workClientAttachment);
                    }else if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("80")){
                        list2.add(workClientAttachment);
                    }else{
                        list3.add(workClientAttachment);
                    }
                }
                String aState = workContractInfo.getAlterState();//取出为copy表添值做判断
                workContractInfo.setWorkAttachments(list1);
                workContractInfo.setWorkAttachments(list3);
                workContractInfo.setAlterState("2");//变更状态--审批中
                workContractInfoService.saves(workContractInfo);//保存
                workContractInfoService.startProcess(workContractInfo,variables);
                //合同状态--变更
                workContractInfo1.setContractState("8");
                workContractInfoService.saves(workContractInfo1);
                WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                workContractReview.setId(null);
                String id = workContractInfo.getId();
                workContractReview.setContractId(id);
                workContractReview.setWorkAttachments(list2);
                workContractReview.setContractName(workContractInfo.getName());
                workContractReviewService.save(workContractReview);
                AlterInfo alterInfo = workContractInfo.getAlterInfo();
                alterInfo.setId(null);
                alterInfoService.save(alterInfo);
                //copy表填值
                if(!("1").equals(aState)){
                    workContractInfoCopyDao.insertCopy(workContractInfo);
                }
                if(StringUtils.isBlank(workContractInfo.getAlterBeforeId())){
                    workContractInfoCopyDao.insertCopy(workContractInfo1);
                }
                addMessage(redirectAttributes, "变更合同管理送审成功");
            }
        }catch (Exception e){
            addMessage(redirectAttributes, "变更合同管理送审失败");
            logger.error("Exception e:"+e);
            e.printStackTrace();
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 变更合同管理
     * 启动流程信息
     */
    @RequestMapping(value = "alterStore")
    public String alterStore(WorkContractInfo workContractInfo, Model model,
                             RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, workContractInfo)) {
            return form(workContractInfo, model);
        }
        try {
            //判断是否有总合同
            //判断是否有总合同
            if(!Strings.isNullOrEmpty(workContractInfo.getTotalContractId()) && !"0".equals(workContractInfo.getTotalContractId())){
                workContractInfo.setIsTotalName("子合同");
                workContractInfo.setIsTotal(null);
            }else{
                workContractInfo.setIsTotalName("总合同");
                workContractInfo.setIsTotal("1");
                workContractInfo.setTotalContractId("0");
                //workContractInfo.setCommonFlag(IdGen.uuid());
            }
            workContractInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            Role role = UserUtils.getSelectRole().get(0);
            StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
            Map<String, Object> variables = new HashMap<String, Object>();
           /* variables.put("SSRHbmzr", buffer.toString() + "bmzr"); //设置部门负责人
            variables.put("SSRHzjl", buffer.toString() + "zjl");
            variables.put("SSRHdsz", buffer.toString() + "dsz");
            variables.put("SSRHgdgly", buffer.toString() + "glygd");*/
            if (!workContractInfo.getIsNewRecord()) {//编辑表单保存
                WorkContractInfo t = workContractInfoService.get(workContractInfo.getId());//从数据库取出记录的值
                //将编辑表单中的非NULL值覆盖数据库记录中的值
                MyBeanUtils.copyBeanNotNull2Bean(workContractInfo, t);
                t.setCompanyId(UserUtils.getSelectCompany().getId());
                String remarks = t.getRemarks();
                workContractInfoService.saves(t);//保存
                WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                workContractReview.setContractName(t.getName());
                workContractReviewService.save(workContractReview);
                AlterInfo alterInfo = workContractInfo.getAlterInfo();
                alterInfoService.save(alterInfo);
                addMessage(redirectAttributes, "暂存合同变更成功");
            } else {//新增表单保存
                WorkContractInfo workContractInfo1 = workContractInfoService.get(workContractInfo.getAlterBeforeId());
                if(workContractInfo1!=null){
                    workContractInfo.setCreateName(workContractInfo1.getCreateName());
                    workContractInfo.setCreateCompany(workContractInfo1.getCreateCompany());
                    workContractInfo.setCompanyId(workContractInfo1.getCompanyId());
                    workContractInfo.setChargeCompany(workContractInfo1.getChargeCompany());
                    workContractInfo.setChargeCompanyName(workContractInfo1.getChargeCompanyName());
                }
                List<WorkClientAttachment> list = workContractInfo.getWorkAttachments();
                List<WorkClientAttachment> list1 = new ArrayList<>();
                List<WorkClientAttachment> list2 = new ArrayList<>();
                List<WorkClientAttachment> list3 = new ArrayList<>();
                for (WorkClientAttachment workClientAttachment:list){
                    if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("44")){
                        list1.add(workClientAttachment);
                    }else if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("80")){
                        list2.add(workClientAttachment);
                    }else{
                        list3.add(workClientAttachment);
                    }
                }
                workContractInfo.setWorkAttachments(list1);
                workContractInfo.setWorkAttachmentAlters(list3);
                workContractInfo.setAlterState("1");//变更状态--暂存
                workContractInfoService.saves(workContractInfo);//保存
                //原数据添加变更暂存标记
                workContractInfo1.setAlterSign("1");
                workContractInfoService.saves(workContractInfo1);
                WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                workContractReview.setId(null);
                String id = workContractInfo.getId();
                workContractReview.setContractId(id);
                workContractReview.setWorkAttachments(list2);
                workContractReview.setContractName(workContractInfo.getName());
                workContractReviewService.save(workContractReview);
                AlterInfo alterInfo = workContractInfo.getAlterInfo();
                alterInfo.setId(null);
                alterInfoService.save(alterInfo);

                workContractInfoCopyDao.insertCopy(workContractInfo);
                if(StringUtils.isBlank(workContractInfo.getAlterBeforeId())){
                    workContractInfoCopyDao.insertCopy(workContractInfo1);
                }
                addMessage(redirectAttributes, "变更合同管理暂存成功");
            }
        }catch (Exception e){
            addMessage(redirectAttributes, "变更合同管理暂存失败");
            logger.error("Exception e:"+e);
            e.printStackTrace();
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }
    /**
     * 工单执行（完成任务）
     * @param
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAlterAudit")
    public String saveAlterAudit(WorkContractInfo workContractInfo,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
       // String str = workContractInfoService.auditAlterSave(workContractInfo);
       // addMessage(redirectAttributes, str);
        model.addAttribute("workContractInfo", workContractInfo);
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/list/?repage";
    }

    /**
     * 查看
     */
    @RequiresPermissions(value = {"workcontractinfo:workContractInfo:view", "workcontractinfo:workContractInfo:add", "workcontractinfo:workContractInfo:edit"}, logical = Logical.OR)
    @RequestMapping(value = "lookForm")
    public String lookForm(WorkContractInfo workContractInfo, Model model) {

//        model.addAttribute("processInstanceId",workContractInfo.getProcessInstanceId());
//        model.addAttribute("invalidateProcessInstanceId",workContractInfo.getInvalidateProcessInstanceId());

        //合同作废信息
        AlterInfo alterInfo = alterInfoService.getByContractInfo(workContractInfo);
        model.addAttribute("alterInfo",alterInfo);
        model.addAttribute("workContractInfo", workContractInfo);
        return "modules/workcontractinfo/workContractInfoLookForm";
    }

    /*
    * 修改时弹出的页面
    * */
    @RequiresPermissions(value = {"workcontractinfo:workContractInfo:view", "workcontractinfo:workContractInfo:add", "workcontractinfo:workContractInfo:edit"}, logical = Logical.OR)
    @RequestMapping(value = "clinetInfo")
    public String getClinetInfo(WorkContractInfo workContractInfo, Model model) {
        String clientId = workContractInfo.getClient().getId();
        WorkClientInfo client = workContractInfoService.getClinetInfo(clientId);
        model.addAttribute("WorkClientInfo", client);
        return "modules/workcontractinfo/workContractClientInfo";
    }


    /*
    * 修改时弹出的页面
    * */
    @RequiresPermissions(value = {"workcontractinfo:workContractInfo:view", "workcontractinfo:workContractInfo:add", "workcontractinfo:workContractInfo:edit"}, logical = Logical.OR)
    @RequestMapping(value = "modifyform")
    public String getModifyFrom(WorkContractInfo workContractInfo, Model model) {
        WorkContractInfo t = workContractInfoService.get(workContractInfo.getId());//从数据库取出记录的值
        model.addAttribute("workContractInfo", t);
        return "modules/workcontractinfo/workContractInfoForm";
    }

    /**
     * 保存合同管理
     * 启动流程信息
     */
//	@RequiresPermissions(value={"workcontractinfo:workContractInfo:add","workcontractinfo:workContractInfo:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(WorkContractInfo workContractInfo, Model model,
                       RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, workContractInfo)) {
            return form(workContractInfo, model);
        }
        String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
        String contextPath = request.getContextPath();
        try {
            //判断是否有总合同
            //判断是否有总合同
            if(!Strings.isNullOrEmpty(workContractInfo.getTotalContractId()) && !"0".equals(workContractInfo.getTotalContractId())){
                workContractInfo.setIsTotalName("子合同");
                workContractInfo.setIsTotal(null);
            }else{
                workContractInfo.setIsTotalName("总合同");
                workContractInfo.setIsTotal("1");
                workContractInfo.setTotalContractId("0");
                //workContractInfo.setCommonFlag(IdGen.uuid());
            }
            String enname = "";
            workContractInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            if (!workContractInfo.getIsNewRecord()) {
                WorkContractInfo t = workContractInfoService.get(workContractInfo.getId());//从数据库取出记录的值
                if (t.getContractState().equals("2")) {
                    addMessage(redirectAttributes, "审核中的合同不能修改");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if (t.getContractState().equals("5")) {
                    addMessage(redirectAttributes, "已通过合同不能修改");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                //将编辑表单中的非NULL值覆盖数据库记录中的值
                MyBeanUtils.copyBeanNotNull2Bean(workContractInfo, t);
                t.setContractState("2");
                t.setRecordState("1");
                Map<String, Object> variables = new HashMap<String, Object>();
                List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
                List<String> assigneeLists=new ArrayList<String>(); //分配任务的人员
                List<String> ywbzrList=new ArrayList<String>(); //分配任务的人员
                List<String> gzrList=new ArrayList<String>(); //分配任务的人员
                //businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
                // 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 ; 1公司2部门3分公司
                String officeId = UserUtils.getSelectOffice().getId();
                List<User>  uList = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.BMZR,2,officeId,"2",workContractInfo.getCreateBy());
                List<User>  uLists = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.FGLD,2,officeId,"2",workContractInfo.getCreateBy());
                List<User>  ywbzrLists = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.YWBZR,2,officeId,"2",workContractInfo.getCreateBy());
                List<User>  gzrLists = UserUtils.getByRoleActivityEnname(enname + "gzr",2,officeId,"2",workContractInfo.getCreateBy());

                if(uList!=null&&uList.size()>0){
                    for (User u:
                            uList) {
                        assigneeList.add(u.getId());
                    }
                }
                if(uLists!=null&&uLists.size()>0){
                    for (User u:
                            uLists) {
                        assigneeLists.add(u.getId());
                    }
                }
                if(ywbzrLists!=null&&ywbzrLists.size()>0){
                    for (User u:
                            ywbzrLists) {
                        ywbzrList.add(u.getId());
                    }
                }
                if(gzrLists!=null&&gzrLists.size()>0){
                    for (User u:
                            gzrLists) {
                        gzrList.add(u.getId());
                    }
                }
                variables.put("assigneeList", assigneeList);
                variables.put("count",assigneeList.size());
                variables.put("fgldList", assigneeLists);
                variables.put("counts",assigneeLists.size());
                variables.put("ywbzrList", ywbzrList);
                variables.put("ywbzrcount",ywbzrList.size());
                variables.put("gzrList", gzrList);
                variables.put("gzrcount",gzrList.size());
                if(assigneeList==null||assigneeList.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色部门负责人下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if(assigneeLists==null||assigneeLists.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色分管领导下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if(ywbzrList==null||ywbzrList.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if(gzrList==null||gzrList.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色盖章人下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                workContractInfoService.save(t, variables,contextPath,url);//保存
                workContractInfoService.updateWorkContractInfo(workContractInfo);
                WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                workContractReview.setContractName(t.getName());
                workContractReviewService.save(workContractReview);
                addMessage(redirectAttributes, "修改保存合同管理成功");
            } else {//新增表单保存
                //第一次创建都只能给部门负责人审核
                String comId = UserUtils.getUser().getComId();
                Office office = UserUtils.getSelectOffice();
                String name = UserUtils.getUser().getName();

                workContractInfo.setCreateName(name);
                workContractInfo.setCreateCompany(comId);
                workContractInfo.setCompanyId(comId);
                workContractInfo.setChargeCompany(office.getId());
                workContractInfo.setChargeCompanyName(office.getName());
                List<WorkClientAttachment> list = workContractInfo.getWorkAttachments();
                List<WorkClientAttachment> list1 = new ArrayList<>();
                List<WorkClientAttachment> list2 = new ArrayList<>();
                for (WorkClientAttachment workClientAttachment:list){
                    if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("44")){
                        list1.add(workClientAttachment);
                    }else {
                        list2.add(workClientAttachment);
                    }
                }
                workContractInfo.setWorkAttachments(list1);
                workContractInfo.setContractState("1");
                workContractInfo.setRecordState("1");
                workContractInfoService.save(workContractInfo);
                Map<String, Object> variables = new HashMap<String, Object>();
                List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
                List<String> assigneeLists=new ArrayList<String>(); //分配任务的人员
                List<String> ywbzrList=new ArrayList<String>(); //分配任务的人员
                List<String> gzrList=new ArrayList<String>(); //分配任务的人员
                //businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
                // 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 ; 1公司2部门3分公司
                String officeId = UserUtils.getSelectOffice().getId();
                List<User>  uList = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.BMZR,2,officeId,"2",workContractInfo.getCreateBy());
                List<User>  uLists = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.FGLD,2,officeId,"2",workContractInfo.getCreateBy());
                List<User>  ywbzrLists = UserUtils.getByRoleActivityEnname(enname + RoleActivityEnname.YWBZR,2,officeId,"2",workContractInfo.getCreateBy());
                List<User>  gzrLists = UserUtils.getByRoleActivityEnname(enname + "gzr",2,officeId,"2",workContractInfo.getCreateBy());

                if(uList!=null&&uList.size()>0){
                    for (User u:
                            uList) {
                        assigneeList.add(u.getId());
                    }
                }
                if(uLists!=null&&uLists.size()>0){
                    for (User u:
                            uLists) {
                        assigneeLists.add(u.getId());
                    }
                }
                if(ywbzrLists!=null&&ywbzrLists.size()>0){
                    for (User u:
                            ywbzrLists) {
                        ywbzrList.add(u.getId());
                    }
                }
                if(gzrLists!=null&&gzrLists.size()>0){
                    for (User u:
                            gzrLists) {
                        gzrList.add(u.getId());
                    }
                }
                variables.put("assigneeList", assigneeList);
                variables.put("count",assigneeList.size());
                variables.put("fgldList", assigneeLists);
                variables.put("counts",assigneeLists.size());
                variables.put("ywbzrList", ywbzrList);
                variables.put("ywbzrcount",ywbzrList.size());
                variables.put("gzrList", gzrList);
                variables.put("gzrcount",gzrList.size());
                if(assigneeList==null||assigneeList.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色部门负责人下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if(assigneeLists==null||assigneeLists.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色分管领导下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if(ywbzrList==null||ywbzrList.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色业务部负责人下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                if(gzrList==null||gzrList.size()==0){
                    addMessage(redirectAttributes, "合同申请提交失败:"+"流程审批人不能为空,角色盖章人下无用户,请联系管理员！");
                    return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
                }
                workContractInfoService.save(workContractInfo, variables,contextPath,url);//保存
                workContractInfoService.updateWorkContractInfo(workContractInfo);
                WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
                String id = workContractInfo.getId();
                workContractReview.setContractId(id);
                workContractReview.setWorkAttachments(list2);
                workContractReview.setContractName(workContractInfo.getName());
                workContractReviewService.save(workContractReview);
                addMessage(redirectAttributes, "保存合同管理成功");
            }
        }catch (Exception e){
            addMessage(redirectAttributes, "保存合同管理失败");

            logger.error("Exception e:"+e);
            e.printStackTrace();
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

   /* public WorkContractInfo getSort(WorkContractInfo workContractInfo){
        if (StringUtils.isNotBlank(workContractInfo.getTotalContractId()) && 30 == workContractInfo.getSort()){
            // 获取排序号，最末节点排序号+30
            if (StringUtils.isBlank(workContractInfo.getId())){
                WorkContractInfo workContractInfoChild = new WorkContractInfo();
                workContractInfoChild.setTotalContractId(workContractInfo.getTotalContractId());
                List<WorkContractInfo> list = workContractInfoService.findByList(workContractInfo);
                if (list.size() > 0){
                    workContractInfo.setSort(list.get(list.size()-1).getSort());
                    if (workContractInfo.getSort() != null){
                        workContractInfo.setSort(workContractInfo.getSort() + 1);
                    }
                }
            }
        }
        return workContractInfo;
    }*/



    /**
     * 暂存合同管理
     */
    @RequestMapping(value = "store")
    public String store(HttpServletRequest request,WorkContractInfo workContractInfo, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, workContractInfo)){
            return form(workContractInfo, model);
        }
        //判断是否有总合同（暂弃）
        //判断是否有总合同
        if(!Strings.isNullOrEmpty(workContractInfo.getTotalContractId()) && !"0".equals(workContractInfo.getTotalContractId())){
            workContractInfo.setIsTotalName("子合同");
            workContractInfo.setIsTotal(null);
        }else{
            workContractInfo.setIsTotalName("总合同");
            workContractInfo.setIsTotal("1");
            workContractInfo.setTotalContractId("0");
            //workContractInfo.setCommonFlag(IdGen.uuid());
        }
        workContractInfo.setOfficeId(UserUtils.getSelectOffice().getId());
        if(!workContractInfo.getIsNewRecord()){//编辑表单保存
            WorkContractInfo t = workContractInfoService.get(workContractInfo.getId());//从数据库取出记录的值
            if (t.getContractState().equals("2")) {
                addMessage(redirectAttributes, "审核中的合同不能修改");
                return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
            }
            if (t.getContractState().equals("5")) {
                addMessage(redirectAttributes, "已通过合同不能修改");
                return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
            }
            //将编辑表单中的非NULL值覆盖数据库记录中的值
            MyBeanUtils.copyBeanNotNull2Bean(workContractInfo, t);
            /*String state = request.getParameter("state");
            if(!("3").equals(t.getContractState())){
                t.setContractState(state.toString());
            }*/
            workContractInfoService.save(t);//保存
            workContractInfoService.updateWorkContractInfo(workContractInfo);
            WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
            workContractReview.setContractName(workContractInfo.getName());
            workContractReviewService.save(workContractReview);
            addMessage(redirectAttributes, "暂存合同管理成功");
            return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
        }else{//新增表单保存
            //第一次创建都只能给部门负责人审核
            String comId = UserUtils.getUser().getComId();
            Office office = UserUtils.getSelectOffice();
            String name = UserUtils.getUser().getName();

            workContractInfo.setCreateName(name);
            workContractInfo.setCreateCompany(comId);
            workContractInfo.setCompanyId(comId);
            workContractInfo.setChargeCompany(office.getId());
            workContractInfo.setChargeCompanyName(office.getName());
            List<WorkClientAttachment> list = workContractInfo.getWorkAttachments();
            List<WorkClientAttachment> list1 = new ArrayList<>();
            List<WorkClientAttachment> list2 = new ArrayList<>();
            for (WorkClientAttachment workClientAttachment:list){
                if (StringUtils.isNotBlank(workClientAttachment.getAttachmentFlag()) && workClientAttachment.getAttachmentFlag().equals("44")){
                    list1.add(workClientAttachment);
                }else {
                    list2.add(workClientAttachment);
                }
            }
            workContractInfo.setWorkAttachments(list1);
            workContractInfo.setContractState("1");
            workContractInfo.setRecordState("1");
            workContractInfoService.save(workContractInfo);//暂存
            workContractInfoService.updateWorkContractInfo(workContractInfo);
            WorkContractReview workContractReview = workContractInfo.getWorkContractReview();
            String id = workContractInfo.getId();
            workContractReview.setContractId(id);
            workContractReview.setWorkAttachments(list2);
            workContractReview.setContractName(workContractInfo.getName());
            workContractReviewService.save(workContractReview);
            addMessage(redirectAttributes, "暂存合同管理成功");
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 启动流程
     * @return
     */
    @RequestMapping(value = "startposs")
    public String startposs(WorkContractInfo workContractInfo, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
        String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
        String contextPath = request.getContextPath();
        Role role = UserUtils.getSelectRole().get(0);
        StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("SSRHbmzr", buffer.toString() + "bmzr"); //设置部门负责人
        variables.put("SSRHzjl", buffer.toString() + "zjl");
        variables.put("SSRHdsz", buffer.toString() + "dsz");
        variables.put("SSRHgdgly", buffer.toString() + "glygd");

        WorkContractInfo t = workContractInfoService.get(workContractInfo.getId());//从数据库取出记录的值
        MyBeanUtils.copyBeanNotNull2Bean(workContractInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
        t.setContractState("2");
        t.preUpdate();
        workContractInfoService.update(t);
        workContractInfoService.save(t,variables,contextPath,url);
        addMessage(redirectAttributes, "启动流程成功");
        return "redirect:"+Global.getAdminPath()+"/workinvoice/workInvoice/?repage";
    }

    /*
    * 废弃合同
    * */
    @RequestMapping(value = "abandoned")
    public String abandonedContract(WorkContractInfo workContractInfo, RedirectAttributes redirectAttributes) {

        workContractInfo.setContractState("3");
        workContractInfoService.abandoned(workContractInfo);
        addMessage(redirectAttributes, "废弃合同管理成功");
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 合同管理撤销
     * @param
     * @return
     */
    @RequestMapping(value = "revoke")
    public String revoke(WorkContractInfo workContractInfo,HttpServletRequest request, RedirectAttributes redirectAttributes) {
        //workContractInfoService.auditInvalidate(workContractInfo);
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 删除合同管理
     */
    @RequiresPermissions("workcontractinfo:workContractInfo:del")
    @RequestMapping(value = "delete")
    public String delete(WorkContractInfo workContractInfo, RedirectAttributes redirectAttributes) {
        workContractInfoService.delete(workContractInfo);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workContractInfo.getId());
        workProjectNotifyService.readByNotifyId(notify);
        if (workContractInfo.getWorkAttachments().size() > 0) {
            String file = workContractInfo.getWorkAttachments().get(0).getUrl();
            String aliyunUrl = Global.getAliyunUrl();
            String aliDownloadUrl = Global.getAliDownloadUrl();
            String cons = "";
            if (file.contains(aliyunUrl)){
                cons = aliyunUrl;
            }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
                cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
            }else {
                cons = aliDownloadUrl;
            }
            String s = file.split(cons + "/")[1];
            workContractInfoService.deleteFile(s, workContractInfo.getId());
        }
        addMessage(redirectAttributes, "删除合同管理成功");
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 批量删除合同管理
     */
    @RequiresPermissions("workcontractinfo:workContractInfo:del")
    @RequestMapping(value = "deleteAll")
    public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            workContractInfoService.delete(workContractInfoService.get(id));
        }
        addMessage(redirectAttributes, "删除合同管理成功");
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 导出excel文件
     */
    @RequiresPermissions("workcontractinfo:workContractInfo:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(WorkContractInfo workContractInfo, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "合同管理" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            User user = UserUtils.getUser();
            //只是普通员工
            if(!UserUtils.getSelectRoleInfo()){
                String id = UserUtils.getUser().getId();
                workContractInfo.setQueryCon(id);
            }
            workContractInfo.setCurrentUser(user);
            workContractInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            workContractInfo.setIsTotal("1");
            Page<WorkContractInfo> page = workContractInfoService.findPage(new Page<WorkContractInfo>(request, response, -1), workContractInfo);
            new ExportExcel(true,"合同管理", WorkContractInfo.class,1).setDataList(page.getList()).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出合同管理记录失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("workcontractinfo:workContractInfo:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            String date = DateUtils.getDate("yyyyMMddHHmmss");
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<WorkContractInfo> list = ei.getDataList(WorkContractInfo.class);
            List<WorkContractInfo> errlist = new ArrayList<>();
            for (WorkContractInfo workContractInfo : list) {
                try {
                    String validator = beanValidatorImport(workContractInfo);
                    if (StringUtils.isNotBlank(validator)){
                        failureMsg.append("<br/>"+validator+"!");
                        failureNum++;
                        workContractInfo = toWorkEntity(workContractInfo,date,validator);
                        errlist.add(workContractInfo);
                    }else {
                        workContractInfoService.save(workContractInfo);
                        successNum++;
                    }
                } catch (ConstraintViolationException ex) {
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList){
                        failureMsg.append(message+"; ");
                        failureNum++;
                    }
                    workContractInfo = toWorkEntity(workContractInfo,date,"导入失败!");
                    errlist.add(workContractInfo);
                } catch (Exception ex) {
                    workContractInfo = toWorkEntity(workContractInfo,date,ex+"!");
                    failureNum++;
                    errlist.add(workContractInfo);
                    failureMsg.append(ex+"!");
                }
            }
            SysImportInfo sysImportInfo = new SysImportInfo();
            sysImportInfo.setCompanyId(UserUtils.getSelectCompany().getId());
            sysImportInfo.setOfficeId(UserUtils.getSelectOffice().getId());
            sysImportInfo.setModular("2");
            if (failureNum>0){
                failureMsg.insert(0, "，失败 "+failureNum+" 个错误信息记录。");
                ExportExcel exportExcel= new ExportExcel(false,"合同信息数据", WorkContractInfo.class, 1).setDataList(errlist);
                OSSClientUtil ossUtil = new OSSClientUtil();

                String fileName=date+"合同信息错误导入日志.xlsx";
                String fileDir = "importInfo/workContractInfoImport/";
                fileDir = fileDir+System.nanoTime()+"/";
                try {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    exportExcel.write(os);
                    byte[] content = os.toByteArray();
                    InputStream inputStream = new ByteArrayInputStream(content);
                    ossUtil.uploadFile2OSS(inputStream,fileDir, fileName);
                }catch (IOException e){
                    e.printStackTrace();
                }catch (Exception e1){
                    e1.printStackTrace();
                    System.out.println("合同信息错误导入日志文件上传失败！");
                }

                String name = Global.getAliyunUrl()+"/"+fileDir+fileName;
                logger.info("name:"+name);
                sysImportInfo.setUrl(name);
                sysImportInfo.setFileName(fileName);
                sysImportInfo.setErrCount(failureNum+"");
                sysImportInfo.setIsTrue("0");
            }else {
                sysImportInfo.setIsTrue("1");
                sysImportInfo.setErrCount("0");
            }
            /*if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条合同管理记录。");
            }*/
            String info = "已成功导入 "+successNum+" 条合同信息记录，失败 "+failureNum+" 个错误信息记录。";
            sysImportInfo.setErrInfo(info);
            sysImportInfoService.save(sysImportInfo);
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条合同信息记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入合同信息失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 下载导入合同管理数据模板
     */
    @RequiresPermissions("workcontractinfo:workContractInfo:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "合同管理数据导入模板.xlsx";
            List<WorkContractInfo> list = Lists.newArrayList();
            String agent = request.getHeader("USER-AGENT");
            new ExportExcel(true,"合同管理数据", WorkContractInfo.class, 1).setDataList(list).write(response, fileName,agent).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/?repage";
    }

    /**
     * 查看导入客户管理数据信息
     */
    //@RequiresPermissions("importInfo:importInfo:importInfoErr")
    @RequestMapping(value = "importInfoErr")
    public String importInfoErr(SysImportInfo sysImportInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
        SysImportInfo importInfo = new SysImportInfo();
        importInfo.setModular("2");
        Page<SysImportInfo> page = sysImportInfoService.findPage(new Page<SysImportInfo>(request, response), importInfo);
        model.addAttribute("page", page);
        model.addAttribute("modular", "2");
        return "modules/sysimportinfo/sysimportinfoList";
    }


    /**
     * 选择客户ID
     */
    @RequestMapping(value = "selectclient")
    public String selectclient(WorkClientInfo client, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1,String type, HttpServletRequest request, HttpServletResponse response, Model model) {
        String id = UserUtils.getSelectCompany().getId();
        client.setCompanyId(id);
        Page<WorkClientInfo> page = workContractInfoService.findPageByclient(new Page<WorkClientInfo>(request, response), client);
        try {
            fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
            fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
            searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("labelNames", fieldLabels.split("\\|"));
        model.addAttribute("labelValues", fieldKeys.split("\\|"));
        model.addAttribute("fieldLabels", fieldLabels);
        model.addAttribute("fieldKeys", fieldKeys);
        model.addAttribute("url", url);
        model.addAttribute("searchLabel", searchLabel);
        model.addAttribute("searchKey", searchKey);
        model.addAttribute("searchLabel1", searchLabel1);
        model.addAttribute("searchKey1", searchKey1);
        model.addAttribute("obj", client);
        model.addAttribute("type", type);
        model.addAttribute("page", page);
        return "modules/sys/gridselectclientinfo";
    }

    /**
     * 选择客户ID
     */
    @RequestMapping(value = "selectclientAhref")
    public String selectclientAhref(WorkClientInfo client, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String searchLabel1, String searchKey1, HttpServletRequest request, HttpServletResponse response, Model model) {
        String id = UserUtils.getSelectCompany().getId();
        client.setCompanyId(id);
        Page<WorkClientInfo> page = workContractInfoService.findPageByclient(new Page<WorkClientInfo>(request, response), client);
        try {
            fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
            fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
            searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
            searchLabel1 = URLDecoder.decode(searchLabel1, "UTF-8");
            searchKey1 = URLDecoder.decode(searchKey1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("labelNames", fieldLabels.split("\\|"));
        model.addAttribute("labelValues", fieldKeys.split("\\|"));
        model.addAttribute("fieldLabels", fieldLabels);
        model.addAttribute("fieldKeys", fieldKeys);
        model.addAttribute("url", url);
        model.addAttribute("searchLabel", searchLabel);
        model.addAttribute("searchKey", searchKey);
        model.addAttribute("searchLabel1", searchLabel1);
        model.addAttribute("searchKey1", searchKey1);
        model.addAttribute("obj", client);
        model.addAttribute("page", page);
        return "modules/sys/gridselectAhref";
    }

    @RequestMapping(value = "getProcess")
    public String getProcess(WorkContractInfo workContractInfo, Model model,HttpServletRequest request) {
        String auditType = request.getParameter("auditType");

        if("合同作废".equals(auditType)){
            model.addAttribute("processInstanceId", workContractInfo.getInvalidateProcessInstanceId());
        }else{
            model.addAttribute("processInstanceId", workContractInfo.getProcessInstanceId());
        }
        return "modules/workcontractinfo/workContractTask";

    }

    //	审批
    @RequestMapping(value = "workContractInfoAudit")
    public String workContractInfoAudit(Act act, WorkContractInfo workContractInfo, Model model) {

        String formKey = "/modules/workcontractinfo/workContractAudit";

        String view = "workContractAudit";

        if (act.getProcInsId() != null) {
            if (actTaskService.getProcIns(act.getProcInsId()) != null) {
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            } else {
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
            workContractInfo.setAct(act);
            model.addAttribute("processInstanceId", workContractInfo.getProcessInstanceId());
        }
        // 环节编号
        String taskDefKey = workContractInfo.getAct().getTaskDefKey();
        if("gdgly".equals(taskDefKey)){
            view = "workContractAuditRecord";
            HashMap<Object, Object> map = workFullRecordService.queryWjgly(UserUtils.getSelectCompany().getId(), "glygd");
            if(map != null){
                WorkFullRecord workFullRecord = new WorkFullRecord();
                workFullRecord.setManageUser(map.get("login_name")+"");
                workFullRecord.setManageId(map.get("id")+"");
                workContractInfo.setWorkFullRecord(workFullRecord);
            }
            model.addAttribute("flag","1");
        }
        model.addAttribute("workContractInfo", workContractInfo);
        return "modules/workcontractinfo/"+view;
    }



    /**
     * 工单执行（完成任务）
     *
     * @param workContractInfo
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkContractInfo workContractInfo, Model model,
                            @RequestParam(value = "upload_files", required = false) MultipartFile[] upload_files,
                            RedirectAttributes redirectAttributes) {
        String taskDefKey = workContractInfo.getAct().getTaskDefKey();
        //当状态为未通过时，重新修改数据
        if ("modifyApply".equals(taskDefKey)) {
            workContractInfo.getAct().setComment("重新申请");
            List<WorkClientAttachment> workClientAttachments = workClientInfoService.uploadFile(request, upload_files, workContractInfo.getId(), "44");
            List<WorkClientAttachment> workClientAttachmentList = workContractInfo.getWorkAttachments();
            workClientAttachments.addAll(workClientAttachmentList);
            workContractInfo.setWorkAttachments(workClientAttachments);
        }
        //String str = workContractInfoService.auditSave(workContractInfo, VarStr.CONTRACT_STATUS);
        //addMessage(redirectAttributes, str);

        return "redirect:" + Global.getAdminPath() + "/workcontractinfo/workContractInfo/list/?repage";
    }

    /**
     * 下载附件
     */
    @RequestMapping("/downLoadAttach")
    public void downLoadAttach(@RequestParam("file") String file, HttpServletResponse response) throws IOException {
//        file = file.replace("amp;","");
//        String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
//        String aliyunUrl = Global.getAliyunUrl();
//        String aliDownloadUrl = Global.getAliDownloadUrl();
//        String cons = "";
//        if (file.contains(aliyunUrl)){
//            cons = aliyunUrl;
//        }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
//            cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
//        }else {
//            cons = aliDownloadUrl;
//        }
//        final String[] arr = file.split(cons + "/");
//        String key = arr[1];
//        new OSSClientUtil().downByStream(key, fileName, response,request.getHeader("USER-AGENT"));
        OutputStream out = null;
        InputStream in = null;
        try {
            file = URLDecoder.decode(file,"UTF-8");
            String path = file.substring(file.indexOf(".com") + 4, file.length());
            String fileName = URLEncoder.encode(file.substring(file.lastIndexOf("/") + 1, file.length()),"UTF-8");
            BOSClientUtil bosClientUtil = new BOSClientUtil();
            in = bosClientUtil.getObject(path);
            response.reset();//重置 响应头
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            out = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            in.close();
            out.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param file
     */
    @RequestMapping("/deleteFile")
    public String deleteFile(@RequestParam("file") String file, WorkContractInfo workContractInfo, Model model, RedirectAttributes redirectAttributes) {
        HashMap<Object, Object> map = Maps.newHashMap();
        String aliyunUrl = Global.getAliyunUrl();
        String aliDownloadUrl = Global.getAliDownloadUrl();
        String cons = "";
        if (file.contains(aliyunUrl)){
            cons = aliyunUrl;
        }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
            cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
        }else {
            cons = aliDownloadUrl;
        }
        String s = file.split(cons+ "/")[1];
        workClientAttachmentDao.delete(workContractInfo.getWorkAttachments().get(0));
        workContractInfoService.deleteFile(s, workContractInfo.getId());
        List<WorkClientAttachment> workContractAnnexList = workContractInfo.getWorkAttachments();
        for (int i = 0; i < workContractAnnexList.size(); i++) {
            if (workContractAnnexList.get(i).getUrl().equals(file)) {
                workContractAnnexList.remove(i);
            }
        }
        model.addAttribute("workContractInfo", workContractInfo);
        return "modules/workcontractinfo/workContractInfoFormAdd";
    }

    /**
     * 异步上传文件
     *
     * @return
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(WorkContractInfo workContractInfo,
                                          Model model, RedirectAttributes redirectAttributes,
                                          HttpServletRequest request,
                                          @RequestParam(value = "myFile") CommonsMultipartFile myFile) {
        String attchmentFlag = request.getParameter("file_type");
        WorkClientAttachment workClientAttachment = workClientInfoService.uploadFileSingle(request, myFile, workContractInfo.getId(), attchmentFlag);
        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            workClientAttachment.setId(ids);
        }
        String s = workClientInfoService.save(workClientAttachment);
        Map map = new HashMap();
        map.put("msg", "success");
        map.put("s", s);
        return map;
    }


    private String toChinese(String string) {
        String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

        String result = "";

        int n = string.length();
        for (int i = 0; i < n; i++) {

            int num = string.charAt(i) - '0';

            if (i != n - 1 && num != 0) {
                result += s1[num] + s2[n - 2 - i];
            } else {
                result += s1[num];
            }
            System.out.println("  "+result);
        }
        return result;

    }

    /**
     * 同步WorkClientInfo
     * @return
     */
    public WorkContractInfo toWorkEntity(WorkContractInfo workContractInfo, String date , String errInfo){
        workContractInfo.setNowDate(date);
        workContractInfo.setUserName(UserUtils.getUser().getName());
        workContractInfo.setErrInfo(errInfo);
        return workContractInfo;
    }
    /**
     * 选择合同外键id
     */
    @RequestMapping(value = "selectcontract")
    public String selectcontract(WorkContractInfo contractId, String url,String type,String isTotal, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
        if(!"1".equals(UserUtils.getSelectCompany().getId())){
            contractId.setCompanyId(UserUtils.getSelectCompany().getId());
        }
        contractId.setContractState("5");
        //contractId.setContractType(type);(合同类型限制解除)
        contractId.setIsTotal(isTotal);
        contractId.setParentIds(UserUtils.getSelectCompany().getParentIds());
        Page<WorkContractInfo> page = workContractInfoService.findPage(new Page<WorkContractInfo>(request, response),  contractId);
        try {
            fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
            fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
            searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        model.addAttribute("labelNames", fieldLabels.split("\\|"));
        model.addAttribute("labelValues", fieldKeys.split("\\|"));
        model.addAttribute("fieldLabels", fieldLabels);
        model.addAttribute("fieldKeys", fieldKeys);
        model.addAttribute("url", url);
        model.addAttribute("searchLabel", searchLabel);
        model.addAttribute("searchKey", searchKey);
        model.addAttribute("type", type);
        model.addAttribute("isTotal", isTotal);
        model.addAttribute("obj", contractId);
        model.addAttribute("page", page);
        return "modules/sys/gridselectContract";
    }
}