package com.yd.dal.service.practitioner.impl;

import com.yd.api.practitioner.vo.hiring.PractitionerHiringContractTerms;
import com.yd.dal.entity.agms.hiring.PractitionerHiringListInfo;
import com.yd.dal.entity.customer.*;
import com.yd.dal.entity.customer.practitioner.PractitionerInfo;
import com.yd.dal.entity.meta.MdPractitionerHiringApproveSteps;
import com.yd.dal.entity.practitioner.hiring.*;
import com.yd.dal.mapper.agms.AgmsHiringMapper;
import com.yd.dal.mapper.customer.AclPractitionerHiringBasicInfoMapper;
import com.yd.dal.mapper.customer.AclPractitionerHiringMembershipMapper;
import com.yd.dal.mapper.customer.AclPractitionerMapper;
import com.yd.dal.mapper.practitioner.PractitionerHiringMapper;
import com.yd.dal.service.customer.AclFileUploadDALService;
import com.yd.dal.service.customer.AclPractitionerDALService;
import com.yd.dal.service.customer.AclPractitionerSubordinateSystemDALService;
import com.yd.dal.service.meta.MdPractitionerHiringApproveStepsDALService;
import com.yd.dal.service.practitioner.PractitionerHiringDALService;
import com.yd.dal.service.user.AclUserDALService;
import com.yd.rmi.cache.SystemConfigService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author xxy
 */
@Service("practitionerHiringDALService")
public class PractitionerHiringDALServiceImpl implements PractitionerHiringDALService {

    @Resource
    private PractitionerHiringMapper practitionerHiringMapper;
    @Autowired
    private AclPractitionerDALService aclPractitionerDALService;
    @Autowired
    private AclFileUploadDALService aclFileUploadDALService;
    @Autowired
    private AclPractitionerHiringMembershipMapper membershipMapper;
    @Autowired
    private MdPractitionerHiringApproveStepsDALService mdPractitionerHiringApproveStepsDalService;
    @Autowired
    private AclPractitionerMapper aclPractitionerMapper;
    @Autowired
    private AgmsHiringMapper agmsHiringMapper;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private AclUserDALService aclUserDalService;
    @Autowired
    private AclPractitionerSubordinateSystemDALService aclPractitionerSubordinateSystemDALService;
    @Autowired
    private AclPractitionerHiringBasicInfoMapper basicInfoMapper;

    @Override
    public List<HiringListInfo> findHiringList(Long practitionerId, Long approvingStatus) {
        return practitionerHiringMapper.findHiringList(practitionerId, approvingStatus);
    }

    @Override
    public HiringBasicInfo findHiringBasicInfo(Long hiringBasicInfoId) {
        return practitionerHiringMapper.findHiringBasicInfo(hiringBasicInfoId);
    }

    @Override
    public HiringMemberShip findHiringMemberShip(Long hiringBasicInfoId) {
        return practitionerHiringMapper.findHiringMemberShip(hiringBasicInfoId);
    }

    @Override
    public List<HiringWorkingExperience> findHiringWorkingExperienceList(Long hiringBasicInfoId) {
        return practitionerHiringMapper.findHiringWorkingExperienceList(hiringBasicInfoId);
    }

    @Override
    public List<HiringPersonalStatements> findHiringPersonalStatementsList(Long hiringBasicInfoId) {
        return practitionerHiringMapper.findHiringPersonalStatementsList(hiringBasicInfoId);
    }

    @Override
    public List<HiringContractTermsConfirms> findHiringContractTermsConfirmsList(Long hiringBasicInfoId) {
        return practitionerHiringMapper.findHiringContractTermsConfirmsList(hiringBasicInfoId);
    }

    @Override
    public List<HiringApproveRecords> findHiringApproveRecordsList(Long hiringBasicInfoId) {

        // 当前审核状态
        AclPractitionerHiringBasicInfo basicInfo = basicInfoMapper.selectByPrimaryKey(hiringBasicInfoId);
        String approveStatus = basicInfo.getApproveStatus();

        List<HiringApproveRecords> records = practitionerHiringMapper.findHiringApproveRecordsList(hiringBasicInfoId);

        PractitionerInfo practitionerInfo;
        CustomerFileUpload fileUpload;
        String imagePath;
        String levelName;

        for (HiringApproveRecords item : records) {
            // 获取职级
            practitionerInfo = aclPractitionerDALService.findPractitionerInfoByPractitionerId(item.getApprovingPractitionerId());
            levelName = (practitionerInfo != null) ? practitionerInfo.getLevelName() : null;
            // 获取头像
            fileUpload = aclFileUploadDALService.findFilePathInfo(1, 1, item.getApprovingPractitionerId());
            imagePath = (fileUpload != null) ? fileUpload.getFilePath() : null;

            item.setHeadImagePath(imagePath);
            item.setLevelName(levelName);
        }

        // 如果已审核结束，则不需要手动创建未审批的流程
        if ("0".equals(approveStatus)) {
            return records;
        }

        // 声明最终返回的List
        List<HiringApproveRecords> resultList = new ArrayList<>(records);
        // 所有的审批流程
        List<MdPractitionerHiringApproveSteps> stepsList = systemConfigService.findHiringApproveStepsAll();
        // 当前经纪人的报聘职级
        AclPractitionerHiringMembership hiringMemberShip = membershipMapper.selectByHiringBasicInfoId(hiringBasicInfoId);
        String mdDropOptionName = hiringMemberShip.getMdDropOptionName();
        // 审批的体系负责人
        String subsystemOwnerName = "";
        if (hiringMemberShip.getApprovedBy() != null) {
            AclPractitioner approvedBy = aclPractitionerDALService.findPractitionerById(hiringMemberShip.getApprovedBy());
            subsystemOwnerName = (approvedBy != null) ? approvedBy.getName() : "";
        }

        for (MdPractitionerHiringApproveSteps step : stepsList) {
            // S2前2步不用审批
            if ((mdDropOptionName.indexOf("S2") >= 0 || mdDropOptionName.indexOf("S3") >= 0)
                    && (step.getStepSeq() == 1 || step.getStepSeq() == 2)
            ) {
                continue;
            }
            // 没有辅导人，前2步不用审批
            if ((hiringMemberShip.getMentorPractitionerId() == null || hiringMemberShip.getMentor() == null)
                    && (step.getStepSeq() == 1 || step.getStepSeq() == 2)
            ) {
                continue;
            }

            if(approveStatus == null){
            	approveStatus = "-2";
            }
            if (step.getStepSeq() > Integer.parseInt(approveStatus)) {
                HiringApproveRecords obj = new HiringApproveRecords();
                obj.setApproveStepId(step.getId());
                obj.setApproveStepName(step.getStepName());
                obj.setApprovingStatusId(Long.valueOf("2"));
                obj.setApprovingStatus("未审批");
                // 获取每一步审批人姓名
                if ("mentor".equals(step.getApproveRole())) {
                    obj.setApprovingPractitionerName(hiringMemberShip.getMentor());
                } else if ("subsystemOwner".equals(step.getApproveRole())) {
                    obj.setApprovingPractitionerName(subsystemOwnerName);
                } else {
                    String names = aclUserDalService.selectNamesByMobileNos(step.getAppointedApprovePractitioners());
                    obj.setApprovingPractitionerName(names);
                }
                resultList.add(obj);
            }
        }
        return resultList;
    }

    @Override
    public List<PractitionerHiringContractTerms> queryContractTerms() {
        return practitionerHiringMapper.queryContractTerms();
    }

    @Override
    public List<HiringListInfo> queryHandledList(Long practitionerId, int approvingStatus) {
        return practitionerHiringMapper.queryHandledList(practitionerId, approvingStatus);
    }

    /**
     * 需求需要AGMS用户也能在ydLife中审批，
     * 所以在响应报文一致的情况下，需要合并两个查询接口的结果集
     */
    @Override
    public List<HiringListInfo> queryUnhandledList(Long practitionerId) {

        List<HiringListInfo> resultList = new ArrayList<>();

        AclPractitioner practitioner = aclPractitionerMapper.selectByPrimaryKey(practitionerId);
        // AGMS接口查询逻辑的数据
        List<HiringListInfo> agmsDataList = this.queryAGMSHiringinfoList(practitioner.getMobileNo());
        System.out.println("------------------------------AGMS接口查询逻辑的数据--------------------------");
        System.out.println(agmsDataList);

        List<HiringListInfo> ydLifeDataList = this.queryYdLifeHiringinfoList(practitionerId);
        System.out.println("-----------------------------ydLife接口查询逻辑的数据-------------------------");
        System.out.println(ydLifeDataList);

        resultList.addAll(agmsDataList);
        resultList.addAll(ydLifeDataList);
        System.out.println("-----------------------------去重前的数据-----------------------------");
        System.out.println(resultList);

        resultList = this.unrepeatedObjList(resultList);
        System.out.println("-----------------------------去重后的数据-----------------------------");
        System.out.println(resultList);


        return resultList;
    }

    private List<HiringListInfo> unrepeatedObjList(List<HiringListInfo> list) {

        List<HiringListInfo> uniqueList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                // 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
                // 根据firstName去重
                () -> new TreeSet<>(Comparator.comparingLong(HiringListInfo::getHiringBasicInfoId))), ArrayList::new));

        return uniqueList;
    }

    private List<HiringListInfo> queryYdLifeHiringinfoList(Long practitionerId) {

        List<HiringListInfo> resultList = new ArrayList<>();

        List<HiringListInfo> list1 = practitionerHiringMapper.queryMentorUnhandledList(practitionerId);
        List<HiringListInfo> list2 = practitionerHiringMapper.querySystemOwnerUnhandledList(practitionerId);
        resultList.addAll(list1);
        resultList.addAll(list2);

        return resultList;
    }

    private List<HiringListInfo> queryAGMSHiringinfoList(String practitionerMobileNo) {
        // 结果集
        List<PractitionerHiringListInfo> dataList = new ArrayList<>();

        List<MdPractitionerHiringApproveSteps> ownSteps = mdPractitionerHiringApproveStepsDalService.findByAppointedApprovePractitioners(practitionerMobileNo);
        // 根据当前用户拥有的审批步骤查询每一步能够审批的数据
        String stepName;
        Integer stepSeq;
        String canAprroveGrade;
        for (MdPractitionerHiringApproveSteps step : ownSteps) {
            stepName = step.getStepName();
            stepSeq = step.getStepSeq();
            canAprroveGrade = step.getCanAprroveGrade();

            List<String> canAprroveGrades = new ArrayList<>();
            canAprroveGrades.addAll(Arrays.asList(canAprroveGrade.split(",")));

            String approveStatus = this.getApproveStatusByStepSeq(stepSeq);
            List<PractitionerHiringListInfo> resultList =
                    agmsHiringMapper.queryUnhandledList(approveStatus, canAprroveGrades,
                            null,
                            null,
                            null,
                            null
                    );
            if (CollectionUtils.isNotEmpty(resultList)) {
                dataList.addAll(resultList);
            }

            if (canAprroveGrades.contains("30")) {
                List<PractitionerHiringListInfo> s2List = agmsHiringMapper.queryS2List(approveStatus,null);
                dataList.addAll(s2List);
            }
        }
        List<HiringListInfo> list = new ArrayList<>();
        for (PractitionerHiringListInfo item : dataList) {
            HiringListInfo hiringInfo = new HiringListInfo();
            BeanUtils.copyProperties(item, hiringInfo);
            list.add(hiringInfo);
        }
        return list;
    }

    @Override
    public int queryApprovalIdentity(Long practitionerId) {
        // 审批身份 0.既是辅导人又是团队长  1.辅导人  2.团队长
        int isMentor = membershipMapper.isMentor(practitionerId);
        int isSystemOwner = membershipMapper.isSystemOwner(practitionerId);

        if (isMentor > 0 && isSystemOwner == 0 ) {
            return 1;
        }
        if (isMentor == 0 && isSystemOwner > 0 ) {
            return 2;
        }
        if (isMentor > 0 && isSystemOwner > 0 ) {
            return 0;
        }
        return 1;
    }

    @Override
    public String getApproveStatusByStepSeq(Integer stepSeq) {
        if (Integer.valueOf(1).equals(stepSeq)) {
            return "-2";
        } else if (Integer.valueOf(2).equals(stepSeq)) {
            return "1";
        } else if (Integer.valueOf(3).equals(stepSeq)) {
            return "2";
        } else if (Integer.valueOf(4).equals(stepSeq)) {
            return "3";
        } else if (Integer.valueOf(5).equals(stepSeq)) {
            return "4";
        } else if (Integer.valueOf(6).equals(stepSeq)) {
            return "5";
        } else {
            return null;
        }
    }

    @Override
    public Integer getNextStepSeqByApproveStatus(String approveStatus) {
        if ("-2".equals(approveStatus)) {
            return Integer.valueOf("1");
        } else if ("1".equals(approveStatus)) {
            return Integer.valueOf("2");
        } else if ("2".equals(approveStatus)) {
            return Integer.valueOf("3");
        } else if ("3".equals(approveStatus)) {
            return Integer.valueOf("4");
        } else if ("4".equals(approveStatus)) {
            return Integer.valueOf("5");
        } else if ("5".equals(approveStatus)) {
            return Integer.valueOf("6");
        } else {
            return null;
        }
    }

    @Override
    public List<Long> queryBasicInfoIdList(List<Long> list) {
        return practitionerHiringMapper.queryBasicInfoIdList(list);
    }

    @Override
    public AclPractitionerHiringMembership queryHiringMemberShip(Long hiringBasicInfoId) {
        AclPractitionerHiringMembership hiringMemberShip = membershipMapper.selectByHiringBasicInfoId(hiringBasicInfoId);
        if (hiringMemberShip.getMentorPractitionerId() == null) {
            return hiringMemberShip;
        }
        AclPractitioner mentor = aclPractitionerDALService.findPractitionerById(hiringMemberShip.getMentorPractitionerId());

        // 查询并显示“辅导人”所属的S1分部，分部负责人，S2体系，体系负责人，S3纵队，纵队负责人，没有的显示空
        List<AclPractitionerSubordinateSystem> subordinateSystemList = aclPractitionerSubordinateSystemDALService.findAll();
        Map<Long, AclPractitionerSubordinateSystem> subordinateSystemMap = new HashMap<>();
        subordinateSystemList.forEach(i -> subordinateSystemMap.put(i.getId(), i));

        Map<Long, AclPractitioner> aclPractitionerMap = aclPractitionerDALService.findAllMap();
        //所属体系
        AclPractitionerSubordinateSystem subordinateSystem = null;
        //体系团队长
        AclPractitioner systemOwner = null;

        if (mentor.getS1Id() != null) {
            subordinateSystem = subordinateSystemMap.get(mentor.getS1Id());
            if (subordinateSystem != null) {
                hiringMemberShip.setS1SubordinateSystemName(subordinateSystem.getName());

                systemOwner = aclPractitionerMap.get(subordinateSystem.getOwnerPractitionerId());
                hiringMemberShip.setS1TeamLeaderName(systemOwner != null ? systemOwner.getName() : null);
                hiringMemberShip.setS1TeamLeaderId(systemOwner != null ? systemOwner.getId() : null);
            }
        }

        if (null != mentor.getS2Id()) {
            subordinateSystem = subordinateSystemMap.get(mentor.getS2Id());
            if (subordinateSystem != null) {
                hiringMemberShip.setS2SubordinateSystemName(subordinateSystem != null ? subordinateSystem.getName() : null);

                systemOwner = aclPractitionerMap.get(subordinateSystem.getOwnerPractitionerId());
                hiringMemberShip.setS2TeamLeaderName(systemOwner != null ? systemOwner.getName() : null);
                hiringMemberShip.setS2TeamLeaderId(systemOwner != null ? systemOwner.getId() : null);
            }
        }
        if (null != mentor.getS3Id()) {
            subordinateSystem = subordinateSystemMap.get(mentor.getS3Id());
            if (subordinateSystem != null) {
                hiringMemberShip.setS3SubordinateSystemName(subordinateSystem != null ? subordinateSystem.getName() : null);

                systemOwner = aclPractitionerMap.get(subordinateSystem.getOwnerPractitionerId());
                hiringMemberShip.setS3TeamLeaderName(systemOwner != null ? systemOwner.getName() : null);
                hiringMemberShip.setS3TeamLeaderId(systemOwner != null ? systemOwner.getId() : null);
            }
        }
        return hiringMemberShip;
    }

    @Override
    public String getHiringOrganizationInfo(AclPractitionerHiringBasicInfo basicInfo, AclPractitionerHiringMembership hiringMemberShip) {
        StringBuilder orgInfo = new StringBuilder();
        String s3SubordinateSystemName = hiringMemberShip.getS3SubordinateSystemName();
        String s2SubordinateSystemName = hiringMemberShip.getS2SubordinateSystemName();
        String s1SubordinateSystemName = hiringMemberShip.getS1SubordinateSystemName();

        boolean flag = false;
        if (StringUtils.isNotEmpty(s3SubordinateSystemName)) {
            orgInfo.append(s3SubordinateSystemName);
            if (s3SubordinateSystemName.indexOf("纵队") < 0) {
                orgInfo.append("纵队");
            }
            flag = true;
        }
        if (StringUtils.isNotEmpty(s2SubordinateSystemName)) {
            orgInfo.append(s2SubordinateSystemName);
            if (s2SubordinateSystemName.indexOf("体系") < 0) {
                orgInfo.append("体系");
            }
            flag = true;
        }
        if (StringUtils.isNotEmpty(s1SubordinateSystemName)) {
            orgInfo.append(s1SubordinateSystemName);
            if (s1SubordinateSystemName.indexOf("分部") < 0) {
                orgInfo.append("分部");
            }
            flag = true;
        }
        if (flag) {
            orgInfo.append("的");
        }
        return orgInfo.append(basicInfo.getName()).toString();
    }
}
