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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
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.iim.service.LayGroupService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.dao.CompanyDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
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.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.workcompanyinfo.dao.CompanyinfoDao;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公司管理Service
 * @author yangfan
 * @version 2017-07-25
 */
@Service
@Transactional(readOnly = true)
public class CompanyinfoService extends CrudService<CompanyinfoDao, Useroffice> {

    @Autowired
    private CompanyinfoDao companyinfoDao;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private UserofficeService userofficeService;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private PushinfoService pushinfoService;
    @Autowired
    private LayGroupService layGroupService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;

    /**
     * 获取流程详细及工作流参数
     * @param id
     */
    @SuppressWarnings("unchecked")
    public Useroffice get(String id) {
        Useroffice useroffice = companyinfoDao.get(id);
        if(useroffice==null){
            useroffice = companyinfoDao.getSimple(id);
            if(useroffice==null){
                return new Useroffice();
            }
        }
        Map<String,Object> variables= new HashMap<String,Object>();
        if (StringUtils.isNotBlank(useroffice.getProcessInstanceId())) {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(useroffice.getProcessInstanceId()).singleResult();
            if (historicProcessInstance != null) {
                variables = Collections3.extractToMap(historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).list(), "variableName", "value");
            } else {
                variables = runtimeService.getVariables(runtimeService.createProcessInstanceQuery().processInstanceId(useroffice.getProcessInstanceId()).active().singleResult().getId());
            }
            useroffice.setVariables(variables);
        }
        return useroffice;
    }

    /**
     * 获取流程详细及工作流参数
     * @param id
     */
    @SuppressWarnings("unchecked")
    public Useroffice getById(String id) {
        Useroffice Useroffice = companyinfoDao.get(id);
        return Useroffice;
    }
    public Useroffice getByCompanyAndUserId(String userId,String companyId) {
        Useroffice Useroffice = companyinfoDao.getByCompanyAndUserId(userId,companyId);
        return Useroffice;
    }
    /**
     * 获取流程详细及工作流参数
     */
    @SuppressWarnings("unchecked")
    public List<Useroffice> findListByCompany(Useroffice useroffice) {
        List<Useroffice> UserofficeList = companyinfoDao.findListByCompany(useroffice);
        return UserofficeList;
    }

    /**
     * 获取流程详细Leave
     * @param processInstanceId
     */
    @SuppressWarnings("unchecked")
    public Useroffice getByProcessInstanceId(String processInstanceId) {
        Useroffice Useroffice = companyinfoDao.getByProcessInstanceId(processInstanceId);
        return Useroffice;
    }

    /**
     * 启动流程
     * @param
     */
    @Transactional(readOnly = false)
    public void save(Useroffice useroffice, Map<String, Object> variables) {
        // 保存业务数据
        if (StringUtils.isBlank(useroffice.getId())){
            useroffice.preInsert();
            companyinfoDao.insert(useroffice);
            logger.debug("save entity: {}", useroffice);

            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(useroffice.getCurrentUser().getId());

            // 启动流程
            String businessKey = useroffice.getId().toString();
            variables.put("type", "joincompany");
            variables.put("busId", businessKey);
            variables.put("title", useroffice.getRemarks());//设置标题；
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_JOIN_COMPANY[0], businessKey, variables);
            useroffice.setProcessInstance(processInstance);

            // 更新流程实例ID
            useroffice.setProcessInstanceId(processInstance.getId());
            companyinfoDao.updateProcessInstanceId(useroffice);

            logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[] {
                    ActUtils.PD_JOIN_COMPANY[0], businessKey, processInstance.getId(), variables });
        }else{
            logger.info("---------------------");
            useroffice.preUpdate();
            useroffice.setRemarks(("yes".equals(useroffice.getAct().getFlag())?"[重申] ":"[销毁] ")+useroffice.getAct().getComment());
            companyinfoDao.update(useroffice);
            useroffice.getAct().setComment(("yes".equals(useroffice.getAct().getFlag())?"[重申] ":"[销毁] ")+useroffice.getAct().getComment());

            // 完成流程任务
            Map<String, Object> vars = Maps.newHashMap();
            vars.put("pass", "yes".equals(useroffice.getAct().getFlag())? true : false);
            actTaskService.complete(useroffice.getAct().getTaskId(), useroffice.getAct().getProcInsId(), useroffice.getAct().getComment(), useroffice.getComment(), vars);
            logger.info("---------------------");
        }


    }

    @Transactional(readOnly = false)
    public void saveFile(Useroffice Useroffice) {
        if (StringUtils.isBlank(Useroffice.getId())){
            Useroffice.preInsert();
            companyinfoDao.insert(Useroffice);
        }else{
            Useroffice.preUpdate();
            companyinfoDao.update(Useroffice);
        }
    }

    /**
     * 查询待办任务
     * @param userId 用户ID
     * @return
     */
    public List<Useroffice> findTodoTasks(String userId) {

        List<Useroffice> results = new ArrayList<Useroffice>();
        List<Task> tasks = new ArrayList<Task>();
        // 根据当前人的ID查询
        List<Task> todoList = taskService.createTaskQuery().processDefinitionKey(ActUtils.PD_JOIN_COMPANY[0]).taskAssignee(userId).active().orderByTaskPriority().desc().orderByTaskCreateTime().desc().list();
        // 根据当前人未签收的任务
        List<Task> unsignedTasks = taskService.createTaskQuery().processDefinitionKey(ActUtils.PD_JOIN_COMPANY[0]).taskCandidateUser(userId).active().orderByTaskPriority().desc().orderByTaskCreateTime().desc().list();
        // 合并
        tasks.addAll(todoList);
        tasks.addAll(unsignedTasks);
        // 根据流程的业务ID查询实体并关联
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
            String businessKey = processInstance.getBusinessKey();
            Useroffice useroffice = companyinfoDao.get(businessKey);
            useroffice.setTask(task);
            useroffice.setProcessInstance(processInstance);
            useroffice.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId((processInstance.getProcessDefinitionId())).singleResult());
            results.add(useroffice);
        }
        return results;
    }

    @Transactional(readOnly = false)
    public void delete(Useroffice Useroffice) {
        companyinfoDao.delete(Useroffice);
    }

    @Transactional(readOnly = false)
    public void update(Useroffice Useroffice) {
        Useroffice.preUpdate();
        companyinfoDao.update(Useroffice);
    }

    public List<Useroffice> findList(Useroffice Useroffice) {
        return super.findList(Useroffice);
    }

    public Page<Useroffice> findPage(Page<Useroffice> page, Useroffice Useroffice) {
        return super.findPage(page, Useroffice);
    }

    public Page<Useroffice> find(Page<Useroffice> page, Useroffice useroffice) {

        useroffice.getSqlMap().put("dsf", dataScopeFilter(useroffice.getCurrentUser(), "o", "u","", MenuStatusEnum.END.getValue()));
        useroffice.setPage(page);
        page.setList(companyinfoDao.findList(useroffice));

        /*for(Useroffice item : page.getList()) {
            String processInstanceId = item.getProcessInstanceId();
            //Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).active().singleResult();
            //item.setTask(task);
            if (StringUtils.isNotBlank(processInstanceId)) {
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                if (historicProcessInstance != null) {
                    item.setHistoricProcessInstance(historicProcessInstance);
                    item.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
                } else {
                    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
                    if (processInstance != null) {
                        item.setProcessInstance(processInstance);
                        item.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
                    }
                }
                ProcessInstance processInstance = actTaskService.getProcIns(item.getProcessInstanceId());
                if (processInstance != null) {
                    Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
                    if (taskInfok != null && StringUtils.isNotBlank(taskInfok.getTaskDefinitionKey()) && !taskInfok.getTaskDefinitionKey().equals("modifyApply")) {
                        item.setTask(taskInfok);
                    }
                }
            }
        }*/
        return page;
    }
    public Map getLeaveById(String id,String type) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Useroffice Useroffice = this.getById(id);
        Map<String,Object> map = Maps.newHashMap();
        String officeName = "";
        String officeId = "";
        if(Useroffice!=null){
            User user = userDao.get(Useroffice.getCreateBy());
            if(user!=null){
                map.put("userName", user.getName());
                map.put("photo",user.getPhoto());
                Office office = user.getOffice();
                if(office!=null && office.getName()!=null){
                    officeName = office.getName();
                    officeId = office.getId();
                }
            }
            map.put("createDate",Useroffice.getCreateDate()==null?"":sdf.format(Useroffice.getCreateDate()));
            map.put("companyId",Useroffice.getCompanyId());
            map.put("officeName",officeName);
            map.put("officeId",officeId);
            map.put("approvalId",id);
            List<Act> list = actTaskService.histoicFlowList(Useroffice.getProcessInstanceId(), "", "");
            List<Act> list2 = actTaskService.toMyStartedList(Useroffice.getProcessInstanceId());
            if (list2!=null && list2.size()!=0){
                Act act1 = list2.get(list2.size()-1);
                map.put("taskId", act1.getTaskId());
                map.put("taskName",act1.getTaskName());
                map.put("procInsId", act1.getProcInsId());
                map.put("procDefId", act1.getProcDefId());
                map.put("actStatus", act1.getStatus()==null?"todo":act1.getStatus());
                map.put("taskDefKey", act1.getTaskDefKey());
                map.put("procDefKey", "joincompany");
            }
            List list1 = new ArrayList();
            for (Act act:list){
                Map<String,Object> maps = new HashMap<String,Object>();
                if (type.equals("1") || type.equals("2")){
                    maps.put("activityName",act.getHistIns().getActivityName().equals("开始")?"发起申请":act.getHistIns().getActivityName());
                    maps.put("assigneeName", UserUtils.getUser().getName().equals(act.getAssigneeName())?"我":act.getAssigneeName());
                }else if(type.equals("3")){
                    maps.put("activityName",act.getHistIns().getActivityName().equals("开始")?"发起申请":act.getHistIns().getActivityName());
                    maps.put("assigneeName",act.getAssigneeName());
                }
                maps.put("startTime",act.getHistIns().getStartTime()==null?"":sdf.format(act.getHistIns().getStartTime()));
                maps.put("endTime", act.getHistIns().getEndTime()==null?"":sdf.format(act.getHistIns().getEndTime()));

                maps.put("durationTime",act.getDurationTime());
                list1.add(maps);
                /*System.out.println("startTime"+act.getHistIns().getStartTime());
                System.out.println("endTime"+act.getHistIns().getEndTime());
                System.out.println("执行环节:"+act.getHistIns().getActivityName());
                System.out.println("执行人:"+act.getAssigneeName());
                System.out.println("任务历时:" + act.getDurationTime());*/
            }
            map.put("process",list1);
        }
        return map;
    }

    /* * 审核审批保存
     * @param testAudit
     */
    @Transactional(readOnly = false)
    public void auditSave(Useroffice useroffice,String... extra) {
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = useroffice.getAct().getTaskDefKey();
        //业务逻辑对应的条件表达式
        String exp = "";
        // 审核环节
        if ("audit1".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit2".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit3".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit4".equals(taskDefKey)){
            exp = "pass";
        }else if ("audit5".equals(taskDefKey)){
            exp = "pass";
        }else if("apply_end".equals(taskDefKey)){
            exp = "pass";
        }else if("modifyApply".equals(taskDefKey)){
            return;
        }
        // 未知环节，直接返回
        else{
            return;
        }

        // 设置意见
        useroffice.getAct().setComment(("yes".equals(useroffice.getAct().getFlag())?"[同意] ":"[驳回] ")+useroffice.getAct().getComment());
        logger.info("Useroffice.getAct()="+useroffice.getAct());
//        Useroffice com = companyinfoDao.get(useroffice);

        // 提交流程任务
        Map<String, Object> vars = Maps.newHashMap();
        vars.put(exp, "yes".equals(useroffice.getAct().getFlag())? true : false);
        vars.put("passs", true);
        // 提交流程任务
        actTaskService.complete(useroffice.getAct().getTaskId(), useroffice.getAct().getProcInsId(), useroffice.getAct().getComment(), vars);
        if(extra.length > 0 && "yes".equals(useroffice.getAct().getFlag())){
            String joinUserId = extra[0];
            String companyId = extra[1];
            String roleId = extra[2];
            Role comRoles = new Role();
            String officeId = extra[3];
            if (StringUtils.isBlank(roleId)){
                comRoles = systemService.getRoleByEnname(companyId,useroffice.getOffice(),"yg");
            }else {
                comRoles = roleDao.get(roleId);
            }
            if (StringUtils.isBlank(roleId)){
                officeId = comRoles.getOffice().getId();
            }
            useroffice.setOfficeId(officeId);
            useroffice.setOfficeId(officeId);
            User user = UserUtils.get(joinUserId);
            user.setCompany(new Office(companyId));
            user.setOffice(new Office(officeId));
            systemService.saveUserInfo(user);
            User userToRole = null;
            if (comRoles != null && StringUtils.isNotBlank(comRoles.getId())) {
                User user1 = UserUtils.get(joinUserId);
                userToRole= systemService.assignUserToRole(comRoles, user1,0);
            }
            if (userToRole!=null){
                systemService.saveCurrentCompanyById(joinUserId,companyId,officeId);
            }

        }
        useroffice.setComment(("yes".equals(useroffice.getAct().getFlag())?"[同意] ":"[驳回] ")+useroffice.getAct().getComment());
        useroffice.preUpdate();
        String remarks = useroffice.getAct().getComment();
        String companyId = useroffice.getCompanyId();
        Office office = officeService.get(companyId);
        if ("yes".equals(useroffice.getAct().getFlag())){
            useroffice.setStatus("3");
            if(StringUtils.isNotBlank(office.getGroupId())) {
                layGroupService.saveUsers(office.getGroupId(), useroffice.getUserId());
            }
        }else {
            useroffice.setStatus("4");
        }
        this.update(useroffice);
        //一个管理员审批完成后，其他管理员不必再操作了
        String companyinfoId = useroffice.getId();
        String masterId = UserUtils.getUser().getId();
        companyinfoDao.updateMaster(companyinfoId, masterId);
        pushinfoService.updateStatusByPushId(companyinfoId, "1");
        Pushinfo pushinfo = new Pushinfo();
        Pushinfo selectPush = new Pushinfo();
        selectPush.setPushId(useroffice.getId());
        selectPush.setType("2003");
        List<Pushinfo> pushinfos = pushinfoService.findList(selectPush);
        if (pushinfos!=null && pushinfos.size()!=0){
            pushinfo = pushinfos.get(0);
        }
        String title = "团队申请";
        String content="您的团队申请已审批!";
        Map extras = new HashMap();

        pushinfo.setCurrentUser(UserUtils.getUser());
        String alias = useroffice.getUserId();
        if (remarks.length()>16){
            remarks = remarks.substring(0,16)+"...";
        }
        remarks = UserUtils.getUser().getName()+ "\n"
                +"已审批,公司名称"+office==null || office.getName()==null || office.getName().equals("")?"":office.getName()+ "\n"
                +"审批结果:"+("yes".equals(useroffice.getAct().getFlag())? "已通过" : "被驳回");
        pushinfo.setRemarks(remarks);
        pushinfo.setUserId(UserUtils.getUser().getId());
        pushinfo.setType("2003");
        pushinfo.setPushId(useroffice.getId());
        pushinfo.setTitle(title);
        pushinfo.setContent(content);
        pushinfo.setParentType("singleCompanyNews");
        pushinfo.setCompanyId(companyId);
        pushinfo.setMobile("ios,android");
        pushinfo.setStatus("1");
        pushinfo.setPushUserId(alias);
        pushinfoService.save(pushinfo);
        extras.put("type", "2003");
        extras.put("id", useroffice.getId());
        extras.put("userId",UserUtils.getUser().getId());
        extras.put("userName",UserUtils.getUser().getName());
        JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(useroffice.getId());
        workProjectNotifyService.readByNotifyId(notify);
        UserUtils.pushIm(useroffice.getUserId(),remarks);
    }





}