package com.jpsoft.shinestar.modules.workflow.service.impl;

import java.util.*;
import javax.annotation.Resource;

import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.entity.PersonRoleInfo;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.base.service.PersonRoleInfoService;
import com.jpsoft.shinestar.modules.business.dto.ExaminePersonDTO;
import com.jpsoft.shinestar.modules.business.entity.RequestForLeaveInfo;
import com.jpsoft.shinestar.modules.business.service.RequestForLeaveInfoService;
import com.jpsoft.shinestar.modules.workflow.entity.*;
import com.jpsoft.shinestar.modules.workflow.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.jpsoft.shinestar.modules.workflow.dao.ProcessSetDAO;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.github.pagehelper.PageHelper;

@Transactional(rollbackFor = Exception.class)
@Component(value = "processSetService")
public class ProcessSetServiceImpl implements ProcessSetService {
    @Resource(name = "processSetDAO")
    private ProcessSetDAO processSetDAO;


    @Autowired
    private ProcessActivityService processActivityService;

    @Autowired
    private RequestForLeaveInfoService requestForLeaveInfoService;

    @Autowired
    private ProcinstService procinstService;

    @Autowired
    private ProcessActUserService processActUserService;

    @Autowired
    private ProcinstActUserService procinstActUserService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @Override
    public ProcessSet get(String id) {
        // TODO Auto-generated method stub
        return processSetDAO.get(id);
    }

    @Override
    public int insert(ProcessSet model) {
        // TODO Auto-generated method stub
        //model.setId(UUID.randomUUID().toString());

        return processSetDAO.insert(model);
    }

    @Override
    public int update(ProcessSet model) {
        // TODO Auto-generated method stub
        return processSetDAO.update(model);
    }

    @Override
    public int delete(String id) {
        // TODO Auto-generated method stub
        return processSetDAO.delete(id);
    }

    @Override
    public boolean exist(String id) {
        // TODO Auto-generated method stub
        int count = processSetDAO.exist(id);

        return count > 0 ? true : false;
    }

    @Override
    public List<ProcessSet> list() {
        // TODO Auto-generated method stub
        return processSetDAO.list();
    }

    @Override
    public Page<ProcessSet> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize, boolean count, List<Sort> sortList) {
        Page<ProcessSet> page = PageHelper.startPage(pageNumber, pageSize, count).doSelectPage(() -> {
            processSetDAO.search(searchParams, sortList);
        });

        return page;
    }

    @Override
    public ExaminePersonDTO getExaminePerson(String procInstId, String processTemplateId, PersonPopedom personPopedom, Integer activityOrder,Map<String,Object> conditions) throws Exception {

        ExaminePersonDTO examinePersonDTO = new ExaminePersonDTO();
        List<ProcessActivity> processActivityList = processActivityService.findByActivityOrderProcessTemplateId(personPopedom.getPersonRoleId(), activityOrder, processTemplateId);
        if (processActivityList.size() == 0) {
            throw new Exception("模板没有相应步骤配置");
        }

        ProcessActivity processActivity = null;

        if (conditions==null || conditions.size()==0){
            processActivity = processActivityList.get(0);
        }else {
            for (ProcessActivity processActivity1 : processActivityList){
                if (StringUtils.isNotBlank(processActivity1.getCondition())){
                    ExpressionParser parser = new SpelExpressionParser();
                    //Double day = Double.parseDouble(days);
                    EvaluationContext ctx = new StandardEvaluationContext();

                    if (conditions!=null) {
                        for (String key : conditions.keySet()) {
                            ctx.setVariable(key, conditions.get(key));
                        }
                    }

                    //#day <7 && #day>2
                    Boolean value = (Boolean) parser.parseExpression(processActivity1.getCondition()).getValue(ctx);

                    if (value){
                        processActivity = processActivity1;
                        break;
                    }
                }
            }
        }

        if (processActivity ==null){
            throw new Exception("模板相应步骤配置错误");
        }


        String name = "";
        String personIds = "";

        //审核人
        List<ProcessActUser> processActUserList = processActUserService.findByActivityIdAndUserType(processActivity.getId(), "1");
        if (processActUserList.size() == 0) {
            throw new Exception("对应步骤未配置相应操作人");
        }
        for (ProcessActUser processActUser : processActUserList) {
            if ("1".equals(processActUser.getSource())) {
                PersonInfo personInfo = personInfoService.get(Long.parseLong(processActUser.getPersonId()));
                if (personInfo != null) {

                    if (StringUtils.isBlank(name)) {
                        name = personInfo.getName();
                        personIds = personInfo.getId().toString();
                    } else {
                        name = name + "," + personInfo.getName();
                        personIds = personIds + "," + personInfo.getId();
                    }
                }

            }
            if ("2".equals(processActUser.getSource())) {
                List<String> roleIdsList = new ArrayList<>();
                roleIdsList.add(processActUser.getPersonRoleId());
                List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIdList(processActUser.getDepartmentId(), roleIdsList);
                if (personPopedomList.size() > 0) {
                    for (PersonPopedom personPopedom1 : personPopedomList) {
                        PersonInfo personInfo = personInfoService.get(personPopedom1.getPersonId());
                        if (personInfo != null) {

                            if (StringUtils.isBlank(name)) {
                                name = personInfo.getName();
                                personIds = personInfo.getId().toString();
                            } else {
                                name = name + "," + personInfo.getName();
                                personIds = personIds + "," + personInfo.getId();
                            }
                        }
                    }
                }
            }
            if ("3".equals(processActUser.getSource())) {

                //   if (activityOrder == 1) {
                //申请者的角色
                PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom.getPersonRoleId());
                if (StringUtils.isNotBlank(personRoleInfo.getParentId())) {
                    //直属上级角色
                    PersonRoleInfo personRoleInfo1 = personRoleInfoService.get(personRoleInfo.getParentId());
                    if (personRoleInfo1 != null) {
                        List<String> roleIdsList = new ArrayList<>();
                        roleIdsList.add(personRoleInfo1.getId());
                        List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIdList(personPopedom.getCompanyId(), roleIdsList);
                        if (personPopedomList.size() > 0) {
                            for (PersonPopedom personPopedom1 : personPopedomList) {
                                PersonInfo personInfo = personInfoService.get(personPopedom1.getPersonId());
                                if (personInfo != null) {
                                    if (StringUtils.isBlank(name)) {
                                        name = personInfo.getName();
                                        personIds = personInfo.getId().toString();
                                    } else {
                                        name = name + "," + personInfo.getName();
                                        personIds = personIds + "," + personInfo.getId();
                                    }
                                }
                            }
                        }
                    }
                }

            }


        }
        String ccName = "";
        String ccPersonIds = "";

        //抄送人
        List<ProcessActUser> processActUserList1 = processActUserService.findByActivityIdAndUserType(processActivity.getId(), "2");
        if (processActUserList1.size() > 0) {
            for (ProcessActUser processActUser : processActUserList1) {
                if ("1".equals(processActUser.getSource())) {
                    PersonInfo personInfo = personInfoService.get(Long.parseLong(processActUser.getPersonId()));
                    if (personInfo != null) {
                        if (StringUtils.isBlank(ccName)) {
                            ccName = personInfo.getName();
                            ccPersonIds = personInfo.getId().toString();
                        } else {
                            ccName = ccName + "," + personInfo.getName();
                            ccPersonIds = ccPersonIds + "," + personInfo.getId();
                        }
                    }


                }
                if ("2".equals(processActUser.getSource())) {
                    List<String> roleIdsList = new ArrayList<>();
                    roleIdsList.add(processActUser.getPersonRoleId());
                    List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIdList(processActUser.getDepartmentId(), roleIdsList);
                    if (personPopedomList.size() > 0) {
                        for (PersonPopedom personPopedom1 : personPopedomList) {
                            PersonInfo personInfo = personInfoService.get(personPopedom1.getPersonId());
                            if (personInfo != null) {
                                if (StringUtils.isBlank(ccName)) {
                                    ccName = personInfo.getName();
                                    ccPersonIds = personInfo.getId().toString();
                                } else {
                                    ccName = ccName + "," + personInfo.getName();
                                    ccPersonIds = ccPersonIds + "," + personInfo.getId();
                                }
                            }

                        }
                    }
                }
                if ("3".equals(processActUser.getSource())) {
                    //申请者的角色
                    PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom.getPersonRoleId());
                    if (StringUtils.isNotBlank(personRoleInfo.getParentId())) {
                        //直属上级角色
                        PersonRoleInfo personRoleInfo1 = personRoleInfoService.get(personRoleInfo.getParentId());
                        if (personRoleInfo1 != null) {
                            List<String> roleIdsList = new ArrayList<>();
                            roleIdsList.add(personRoleInfo1.getId());
                            List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIdList(processActUser.getDepartmentId(), roleIdsList);
                            if (personPopedomList.size() > 0) {
                                for (PersonPopedom personPopedom1 : personPopedomList) {
                                    PersonInfo personInfo = personInfoService.get(personPopedom1.getPersonId());
                                    if (personInfo != null) {
                                        if (StringUtils.isBlank(name)) {
                                            ccName = personInfo.getName();
                                            ccPersonIds = personInfo.getId().toString();
                                        } else {
                                            ccName = ccName + "," + personInfo.getName();
                                            ccPersonIds = ccPersonIds + "," + personInfo.getId();
                                        }
                                    }

                                }
                            }
                        }
                    }

                }
            }
        }

        examinePersonDTO.setOperation(processActivity.getOperation());
        examinePersonDTO.setPersonNames(name);
        examinePersonDTO.setPersonIds(personIds);
        examinePersonDTO.setCcPersonNames(ccName);
        examinePersonDTO.setCcPersonIds(ccPersonIds);
        examinePersonDTO.setProcessTemplateId(processActivity.getProcessTemplateId());
        examinePersonDTO.setActivityId(processActivity.getId());
        return examinePersonDTO;

    }
}