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.AclPractitioner;
import com.yd.dal.entity.customer.AclPractitionerHiringMembership;
import com.yd.dal.entity.customer.CustomerFileUpload;
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.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.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.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;

    @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) {
        List<HiringApproveRecords> records = practitionerHiringMapper.findHiringApproveRecordsList(hiringBasicInfoId);
        PractitionerInfo practitionerInfo;
        CustomerFileUpload fileUpload;
        String imagePath;
        String levelName;

        // 创建一个Map
        Map<Long, HiringApproveRecords> map = new HashMap<>();
        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);

            map.put(item.getApproveStepId(), item);
        }

        // 声明最终返回的List
        List<HiringApproveRecords> resultList = new ArrayList<>();
        // 所有的审批流程
        List<MdPractitionerHiringApproveSteps> stepsList = systemConfigService.findHiringApproveStepsAll();
        // 当前经纪人的报聘职级
        AclPractitionerHiringMembership hiringMemberShip = membershipMapper.selectByHiringBasicInfoId(hiringBasicInfoId);

        HiringApproveRecords record;
        for (MdPractitionerHiringApproveSteps step : stepsList) {
            // S2前2步不用审批
            if (Long.valueOf("30").equals(hiringMemberShip.getMdDropOptionId())
                    && (step.getStepSeq() == 1 || step.getStepSeq() == 2)
            ) {
                continue;
            }
            // 没有辅导人，前2步不用审批
            if ((hiringMemberShip.getMentorPractitionerId() == null || hiringMemberShip.getMentor() == null)
                    && (step.getStepSeq() == 1 || step.getStepSeq() == 2)
            ) {
                continue;
            }
            record = map.get(step.getId());
            if (record != null) {
                resultList.add(record);
            } else {
                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(hiringMemberShip.getSubsystemOwner());
                } 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);
                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) {
        switch (stepSeq) {
            case 1 :
                return "-2";
            case 2 :
                return "1";
            case 3 :
                return "2";
            case 4 :
                return "3";
            case 5 :
                return "4";
            case 6 :
                return "5";
        }
        return null;
    }

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

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