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

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yd.api.agms.vo.hiring.PractitionerHiringListRequestVO;
import com.yd.dal.entity.agms.hiring.*;
import com.yd.dal.entity.customer.AclPractitioner;
import com.yd.dal.entity.customer.AclPractitionerHiringMembership;
import com.yd.dal.entity.customer.AclPractitionerSubordinateSystem;
import com.yd.dal.entity.customer.practitioner.PractitionerSubordinateInfo;
import com.yd.dal.entity.meta.MdPractitionerHiringApproveSteps;
import com.yd.dal.entity.user.AclUser;
import com.yd.dal.mapper.agms.AgmsHiringMapper;
import com.yd.dal.mapper.customer.AclPractitionerHiringMembershipMapper;
import com.yd.dal.service.agms.AgmsHiringDALService;
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.util.page.PageInfoUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author xxy
 */
@Service("agmsHiringDALService")
public class AgmsHiringDALServiceImpl implements AgmsHiringDALService {

    private AgmsHiringMapper agmsHiringMapper;
    @Autowired
    private AclUserDALService aclUserDalService;
    @Autowired
    private MdPractitionerHiringApproveStepsDALService mdPractitionerHiringApproveStepsDalService;
    @Autowired
    private PractitionerHiringDALService practitionerHiringDalService;
    @Autowired
    private AclPractitionerSubordinateSystemDALService aclPractitionerSubordinateSystemDalService;
    @Autowired
    private AclPractitionerHiringMembershipMapper membershipMapper;
    @Autowired
    private AclPractitionerDALService aclPractitionerDALService;

    @Autowired
    public void setAgmsHiringMapper(AgmsHiringMapper agmsHiringMapper){
        this.agmsHiringMapper = agmsHiringMapper;
    }

    @Override
    public PractitionerHiringBasicInfo findPractitionerHiringBasicInfo(Long hiringBasicInfoId) {
        return agmsHiringMapper.findPractitionerHiringBasicInfo(hiringBasicInfoId);
    }

    @Override
    public PractitionerHiringMemberShip findPractitionerHiringMemberShip(Long hiringBasicInfoId) {
        PractitionerHiringMemberShip practitionerHiringMemberShip = agmsHiringMapper.findPractitionerHiringMemberShip(hiringBasicInfoId);
        AclPractitionerHiringMembership hiringMemberShip = this.queryHiringMemberShip(hiringBasicInfoId);

        practitionerHiringMemberShip.setS1TeamLeaderId(hiringMemberShip.getS1TeamLeaderId());
        practitionerHiringMemberShip.setS2TeamLeaderId(hiringMemberShip.getS2TeamLeaderId());
        practitionerHiringMemberShip.setS3TeamLeaderId(hiringMemberShip.getS3TeamLeaderId());

        practitionerHiringMemberShip.setS1TeamLeaderName(hiringMemberShip.getS1TeamLeaderName());
        practitionerHiringMemberShip.setS2TeamLeaderName(hiringMemberShip.getS2TeamLeaderName());
        practitionerHiringMemberShip.setS3TeamLeaderName(hiringMemberShip.getS3TeamLeaderName());

        practitionerHiringMemberShip.setS1SubordinateSystemName(hiringMemberShip.getS1SubordinateSystemName());
        practitionerHiringMemberShip.setS2SubordinateSystemName(hiringMemberShip.getS2SubordinateSystemName());
        practitionerHiringMemberShip.setS3SubordinateSystemName(hiringMemberShip.getS3SubordinateSystemName());

        return practitionerHiringMemberShip;
    }

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

        // 查询并显示“辅导人”所属的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 List<PractitionerHiringWorkingExperience> findPractitionerHiringWorkingExperienceList(Long hiringBasicInfoId) {
        return agmsHiringMapper.findPractitionerHiringWorkingExperienceList(hiringBasicInfoId);
    }

    @Override
    public List<PractitionerHiringPersonalStatements> findPractitionerHiringPersonalStatementsList(Long hiringBasicInfoId) {
        return agmsHiringMapper.findPractitionerHiringPersonalStatementsList(hiringBasicInfoId);
    }

    @Override
    public List<PractitionerHiringContractTermsConfirms> findPractitionerHiringContractTermsConfirmsList(Long hiringBasicInfoId) {
        return agmsHiringMapper.findPractitionerHiringContractTermsConfirmsList(hiringBasicInfoId);
    }

    @Override
    public List<PractitionerHiringApproveRecords> findPractitionerHiringApproveRecordsList(Long hiringBasicInfoId) {
        return agmsHiringMapper.findPractitionerHiringApproveRecordsList(hiringBasicInfoId);
    }

    @Override
    public Long findPractitionerIdByLoginId(Long loginId) {
        return agmsHiringMapper.findPractitionerIdByLoginId(loginId);
    }

    @Override
    public PageInfo<PractitionerHiringListInfo> practitionerHiringList(PractitionerHiringListRequestVO requestVO) {
        String orderBy = "hiringBasicInfoId desc";
        PageInfo<PractitionerHiringListInfo> pageInfo = requestVO.getPageInfo();
        PageHelper.startPage(pageInfo.getPageNum(),pageInfo.getPageSize(),orderBy);
        Page<PractitionerHiringListInfo> destList = agmsHiringMapper.practitionerHiringList(requestVO);
        pageInfo = new PageInfo<>(destList);
        return pageInfo;
    }

    @Override
    public PageInfo<PractitionerHiringListInfo> queryHandledList(Long loginPractitionerId, String status, PractitionerHiringListRequestVO requestVO) {
        //体系查询调整，如果体系为S3，则需要查询它下面的所有子集
        PractitionerSubordinateInfo practitionerSubordinateInfo = new PractitionerSubordinateInfo();
        BeanUtils.copyProperties(requestVO,practitionerSubordinateInfo);
        practitionerSubordinateInfo.setInsurerBranchId(requestVO.getBranchId());
        List<Long> subsystemIdList = aclPractitionerSubordinateSystemDalService.getLongs(practitionerSubordinateInfo);

        List<PractitionerHiringListInfo> destList =
                agmsHiringMapper.queryHandledList(loginPractitionerId, status, requestVO.getBranchId(),
                        requestVO.getDeptId(),
                        subsystemIdList,
                        requestVO.getName());

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

        // 去重后的list分页
        PageInfo<PractitionerHiringListInfo> pageInfo = requestVO.getPageInfo();
        int pageNum = pageInfo.getPageNum();
        int pageSize = pageInfo.getPageSize();
        PageInfo<PractitionerHiringListInfo> page = PageInfoUtils.list2PageInfo(uniqueList, pageNum, pageSize);

        return page;
    }

    @Override
    public List<PractitionerHiringListInfo> queryUnhandledList(PractitionerHiringListRequestVO requestVO) {
        // 结果集
        List<PractitionerHiringListInfo> dataList = new ArrayList<>();

        AclUser user = aclUserDalService.selectByPrimaryKey(requestVO.getLoginId());
        String loginMobileNo = user.getMobileNo();
        // 查询该号码具有的审批步骤
        List<MdPractitionerHiringApproveSteps> ownSteps = mdPractitionerHiringApproveStepsDalService.findByAppointedApprovePractitioners(loginMobileNo);
        if (CollectionUtils.isEmpty(ownSteps)) {
            return dataList;
        }

        // 根据当前用户拥有的审批步骤查询每一步能够审批的数据
        String stepName;
        Integer stepSeq;
        String canAprroveGrade;

        //体系查询调整，如果体系为S3，则需要查询它下面的所有子集
        PractitionerSubordinateInfo practitionerSubordinateInfo = new PractitionerSubordinateInfo();
        BeanUtils.copyProperties(requestVO,practitionerSubordinateInfo);
        practitionerSubordinateInfo.setInsurerBranchId(requestVO.getBranchId());
        List<Long> subsystemIdList = aclPractitionerSubordinateSystemDalService.getLongs(practitionerSubordinateInfo);

        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 = practitionerHiringDalService.getApproveStatusByStepSeq(stepSeq);
            List<PractitionerHiringListInfo> resultList =
                    agmsHiringMapper.queryUnhandledList(approveStatus, canAprroveGrades,
                            requestVO.getBranchId(),
                            requestVO.getDeptId(),
                            subsystemIdList,
                            requestVO.getName()
                    );
            if (CollectionUtils.isNotEmpty(resultList)) {
                dataList.addAll(resultList);
            }

            if (canAprroveGrades.contains("30")) {
                List<PractitionerHiringListInfo> s2List = agmsHiringMapper.queryS2List(approveStatus);
                dataList.addAll(s2List);
            }

        }
        // 每个审核步骤可能查询出重复数据， 需去重
        List<PractitionerHiringListInfo> uniqueList = dataList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                // 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
                // 根据hiringBasicInfoId去重
                () -> new TreeSet<>(Comparator.comparingLong(PractitionerHiringListInfo::getHiringBasicInfoId))), ArrayList::new));

        return uniqueList;
    }
}
