package com.sifang.modules.taskdispatch.service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.form.AddReportReq;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.taskdispatch.constant.ReviewDispatchConst;
import com.sifang.modules.taskdispatch.dao.CrmPriorReviewSettingDao;
import com.sifang.modules.taskdispatch.dao.CrmPriorReviewSettingMemberDao;
import com.sifang.modules.taskdispatch.dao.CrmReviewDispatchDao;
import com.sifang.modules.taskdispatch.dao.CrmReviewGroupMemberDao;
import com.sifang.modules.taskdispatch.entity.CrmPriorReviewSetting;
import com.sifang.modules.taskdispatch.entity.CrmPriorReviewSettingMember;
import com.sifang.modules.taskdispatch.entity.CrmReviewDispatch;
import com.sifang.modules.taskdispatch.entity.CrmReviewGroupMember;
import com.sifang.modules.taskdispatch.util.BatchItem;
import com.sifang.modules.taskdispatch.util.BatchItemPriority;
import com.sifang.modules.taskdispatch.vo.PriorReviewSettingVo;
import com.sifang.modules.taskdispatch.vo.ReviewSettingMemberVo;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CrmPriorReviewSettingService extends BaseService {

    @Autowired
    private CrmPriorReviewSettingDao priorReviewSettingDao;

    @Autowired
    private CrmPriorReviewSettingMemberDao priorReviewSettingMemberDao;

    @Autowired
    private CrmPlatformEmpDao crmPlatformEmpDao;

    @Autowired
    CrmReviewGroupMemberDao reviewGroupMemberDao;

    @Autowired
    private CrmReviewGroupMemberService crmReviewGroupMemberService;

    @Autowired
    UserDao userDao;

    @Autowired
    private CrmReviewDispatchDao crmReviewDispatchDao;

    @Autowired
    ItemManageDao itemManageDao;

    @Autowired
    private CrmReviewGroupMemberDao groupMemberDao;

    @Autowired
    private TraderDao traderDao;

    public void getPriorReviewSettingList(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> list = priorReviewSettingDao.getPriorReviewSettingList(page, map);
        page.setData(list);
        page.setCount(priorReviewSettingDao.countPriorReviewSetting(map));
    }

    @Transactional(rollbackFor = Exception.class)
    public Result addPriorReviewSetting(PriorReviewSettingVo setting, Operator operator) {
        Result result = new Result();
        CrmPriorReviewSetting reviewSetting = priorReviewSettingDao.findReviewSettingByTraderId(setting.getTraderId());
        if(reviewSetting != null){
            result.setErrMsg("代理商可不重复选择！");
            result.setCode("501");
            return result;
        }
        CrmPriorReviewSetting priorReviewSetting = new CrmPriorReviewSetting();
        priorReviewSetting.setTraderId(setting.getTraderId());
        priorReviewSetting.setStatus("0");
        priorReviewSetting.setCreateBy(operator.getUserId());
        priorReviewSetting.setCreator(operator.getUserName());
        priorReviewSetting.setCreateTime(new Date());
        priorReviewSettingDao.save(priorReviewSetting);
        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>();
        Set<String> set3 = new HashSet<>();
        Set<String> set4 = new HashSet<>();
        for(ReviewSettingMemberVo memberVo : setting.getMemberList()){
            if("设计审核".equals(memberVo.getGroupName())){
                if(!set1.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            if("档案审核".equals(memberVo.getGroupName())){
                if(!set2.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            if("安装审核".equals(memberVo.getGroupName())){
                if(!set3.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            if("并网审核".equals(memberVo.getGroupName())){
                if(!set4.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            CrmPriorReviewSettingMember priorReviewSettingMember = new CrmPriorReviewSettingMember();
            priorReviewSettingMember.setReviewSettingId(priorReviewSetting.getId());
            priorReviewSettingMember.setEmployeeId(memberVo.getEmployeeId());
            CrmPlatformEmployee crmPlatformEmployee = crmPlatformEmpDao.get(memberVo.getEmployeeId());
            priorReviewSettingMember.setUserId(crmPlatformEmployee.getUserId());
            priorReviewSettingMember.setFlag(memberVo.getFlag());
            priorReviewSettingMember.setGroupName(memberVo.getGroupName());
            priorReviewSettingMemberDao.save(priorReviewSettingMember);
        }
        result.setCode("200");
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result editPriorReviewSetting(PriorReviewSettingVo setting) {
        Result result = new Result();
        CrmPriorReviewSetting reviewSetting = priorReviewSettingDao.findReviewSettingByTraderId(setting.getTraderId());
        if(reviewSetting != null && !reviewSetting.getId().equals(setting.getId())){
            result.setErrMsg("代理商可不重复选择！");
            result.setCode("501");
            return result;
        }
        CrmPriorReviewSetting priorReviewSetting = priorReviewSettingDao.get(setting.getId());
        priorReviewSetting.setTraderId(setting.getTraderId());
        priorReviewSetting.setFinallyUpdateTime(new Date());
        priorReviewSettingDao.save(priorReviewSetting);
        //删除
        priorReviewSettingMemberDao.deleteMemberByReviewSettingId(setting.getId());
        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>();
        Set<String> set3 = new HashSet<>();
        Set<String> set4 = new HashSet<>();
        for(ReviewSettingMemberVo memberVo : setting.getMemberList()){
            if("设计审核".equals(memberVo.getGroupName())){
                if(!set1.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            if("档案审核".equals(memberVo.getGroupName())){
                if(!set2.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            if("安装审核".equals(memberVo.getGroupName())){
                if(!set3.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            if("并网审核".equals(memberVo.getGroupName())){
                if(!set4.add(memberVo.getEmployeeId())){
                    result.setErrMsg(memberVo.getGroupName()+"审核人员重复");
                    result.setCode("501");
                    return result;
                }
            }
            CrmPriorReviewSettingMember priorReviewSettingMember = new CrmPriorReviewSettingMember();
            priorReviewSettingMember.setReviewSettingId(priorReviewSetting.getId());
            priorReviewSettingMember.setEmployeeId(memberVo.getEmployeeId());
            CrmPlatformEmployee crmPlatformEmployee = crmPlatformEmpDao.get(memberVo.getEmployeeId());
            priorReviewSettingMember.setUserId(crmPlatformEmployee.getUserId());
            priorReviewSettingMember.setFlag(memberVo.getFlag());
            priorReviewSettingMember.setGroupName(memberVo.getGroupName());
            priorReviewSettingMemberDao.save(priorReviewSettingMember);
        }
        result.setCode("200");
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result deletePriorReviewSetting(String id) {
        Result result = new Result();
        priorReviewSettingDao.deleteById(id);
        priorReviewSettingMemberDao.deleteMemberByReviewSettingId(id);
        result.setCode("200");
        return result;
    }

    public Result changeStatus(String id, String status, String traderId) {
        Result result = new Result();
        //禁用时查看当前代理商是否有优先审核的单据
        if("1".equals(status)){
            Map<String, String> map = new HashMap<>();
            User user= UserUtils.getUser();
            if(User.USER_TYPE_WXG.equals(user.getUserType())){
                EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
            }
            map.put("traderId",traderId);
            map.put("isPriority","1");
            List<Record> list = itemManageDao.getExamineLogList(map);
            if(list.size()>0){
                result.setErrMsg("该代理商有优先审核的单据，不可删除！");
                result.setCode("501");
                return result;
            }
        }
        CrmPriorReviewSetting priorReviewSetting = priorReviewSettingDao.get(id);
        priorReviewSetting.setStatus(status);
        priorReviewSettingDao.save(priorReviewSetting);
        result.setCode("200");
        return result;
    }

    public CrmPriorReviewSetting findReviewSettingById(String id) {
        return priorReviewSettingDao.findReviewSettingById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void traderPriorityReview(String traderId, String itemId, String groupName) {
        //获取一级二级代理商信息
        CrmTrader crmTrader = traderDao.get(traderId);
        String parentId = crmTrader.getParentId();
        CrmPriorReviewSetting reviewSetting = priorReviewSettingDao.findReviewSettingByTraderIdStatus(parentId);
        //判断该代理商是否为优先审核
        if(reviewSetting != null){
            List<CrmPriorReviewSettingMember> memberList = priorReviewSettingMemberDao.findReviewSettingMemberByGroupName(reviewSetting.getId(),groupName);
            Map<String,List<CrmPriorReviewSettingMember>> map = memberList.stream().collect(Collectors.groupingBy(CrmPriorReviewSettingMember::getFlag));
            Set ketSet = map.keySet();
            //获取审核组人员信息
            CrmPriorReviewSettingMember settingMember1 = new CrmPriorReviewSettingMember();
            CrmPriorReviewSettingMember settingMember2 = new CrmPriorReviewSettingMember();
            CrmPriorReviewSettingMember settingMember3 = new CrmPriorReviewSettingMember();
            String employeeId = "";
            String userId = "";
            for (Object key:ketSet){
                if("1".equals(key)){
                    settingMember1 = map.get(key).get(0);
                }
                if("2".equals(key)){
                    settingMember2 = map.get(key).get(0);
                }
                if(ketSet.size() > 2){
                    if("3".equals(key)){
                        settingMember3 = map.get(key).get(0);
                    }
                }
            }
            //判断审核人员是否在线
            List<Record> mainMemberList = reviewGroupMemberDao.findByEmployeeId(settingMember1.getEmployeeId());
            if(mainMemberList.size() > 0){
                Record mainMember = getSigninMember(mainMemberList);
                if (mainMember != null) {
                    employeeId = settingMember1.getEmployeeId();
                    userId = settingMember1.getUserId();
                }else{
                    List<Record> spareMemberList1 = reviewGroupMemberDao.findByEmployeeId(settingMember2.getEmployeeId());
                    if(spareMemberList1.size()>0){
                        Record sparemMember1 = getSigninMember(spareMemberList1);
                        if (sparemMember1 != null) {
                            employeeId = settingMember2.getEmployeeId();
                            userId = settingMember2.getUserId();
                        }else{
                            if(ketSet.size() > 2) {
                                List<Record> spareMemberList2 = reviewGroupMemberDao.findByEmployeeId(settingMember3.getEmployeeId());
                                if (spareMemberList2.size() > 0) {
                                    Record spareMember2 = getSigninMember(spareMemberList2);
                                    if (spareMember2 != null) {
                                        employeeId = settingMember3.getEmployeeId();
                                        userId = settingMember3.getUserId();
                                    } else {
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
                //派单
                if (StringUtils.isBlank(itemId)) {
                    throw new BusinessException(ReviewDispatchConst.ERR_CODE_ITEM_REQUIRED, "待办事项不能为空！");
                }
                if(StringUtil.isNotBlank(userId)){
                    User assigneeUser = userDao.getById(userId);
                    List<String> itemIds = new ArrayList<>();
                    itemIds.add(itemId);
                    Date dispatchTime = new Date();
                    List<CrmReviewDispatch> dispatches = new ArrayList<>();
                    CrmReviewDispatch dispatch = createReviewDispatch(itemId, dispatchTime, employeeId, userId);
                    dispatches.add(dispatch);

                    //自动分配审核人员
                    Long count = itemManageDao.priorityTaskCount(userId,"1");
                    //优先审单单据不可超出5条
                    if(count < 5){
                        ItemManage itemManage = itemManageDao.get(itemId);
                        if(itemManage.getAssignAuditUserId() == null || itemManage.getAssignAuditUserId() == "" && itemManage.getEndTime() == null){
                            itemManage.setAssignAuditUserId(userId);
                            itemManage.setAssignee(CrmUtils.getUserXM(assigneeUser));
                            itemManage.setLatestDispatchId(dispatch.getId());
                            itemManage.setAssignTime(dispatchTime);
                            itemManage.setIsPriority("1");
                            itemManageDao.save(itemManage);
                        }
                        crmReviewDispatchDao.save(dispatches);
                    }
                }
            }
        }
    }

    private Record getSigninMember(List<Record> members) {
        for (Record member : members) {
            Date signinTime = member.getDate("signin_time");
            Date signoutTime = member.getDate("signout_time");
            if (signinTime != null && signoutTime == null) {
                return member;
            }
        }
        return null;
    }

    @NotNull
    private static CrmReviewDispatch createReviewDispatch(String itemId, Date reDispatchTime, String employeeId, String userId) {
        CrmReviewDispatch dispatch = new CrmReviewDispatch();
        dispatch.setId(IdGen.uuid());
        dispatch.setStatus(ReviewDispatchConst.STATUS_ONGOING);
        dispatch.setDispatchType(ReviewDispatchConst.DISPATCH_TYPE_MANUAL);
        dispatch.setCreateBy("1");
        dispatch.setCreator("system");
        dispatch.setCreateTime(reDispatchTime);
        dispatch.setRedispatchTime(null);
        dispatch.setFinishTime(null);
        dispatch.setEmployeeId(employeeId);
        dispatch.setAssignUserId(userId);
        dispatch.setItemId(itemId);
        return dispatch;
    }

}
