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

import com.google.common.base.Strings;
import com.yd.api.practitioner.service.PractitionerService;
import com.yd.api.practitioner.vo.payscale.PayScaleInfo;
import com.yd.api.practitioner.vo.subordinate.TeamMemberDetail;
import com.yd.dal.entity.customer.AclCustomer;
import com.yd.dal.entity.customer.AclPractitionerSubordinateSystem;
import com.yd.dal.entity.practitioner.opportunity.PlayerSalesActivityInfo;
import com.yd.dal.entity.practitioner.opportunity.OwnOpportunityInfo;
import com.yd.dal.entity.customer.AclPractitioner;
import com.yd.dal.entity.customer.practitioner.PractitionerBasicInfo;
import com.yd.dal.entity.customer.practitioner.PractitionerInfo;
import com.yd.dal.entity.customer.practitioner.PractitionerRankInfo;
import com.yd.dal.entity.practitioner.payscale.PayScaleBasicInfo;
import com.yd.dal.mapper.customer.AclCustomerMapper;
import com.yd.dal.mapper.customer.AclPractitionerMapper;
import com.yd.dal.service.customer.AclPractitionerDALService;
import com.yd.dal.service.customer.AclPractitionerSubordinateSystemDALService;
import com.yd.util.CommonUtil;
import com.yd.util.auth.setting.AudienceSetting;
import com.yd.util.auth.setting.JwtTokenUtil;
import com.yd.util.deshandler.DESTypeHandler;
import com.yd.util.intercept.annotation.TargetDataSource;
import com.yd.util.intercept.commons.DataSourceKey;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@Service("aclPractitionerDALService")
public class AclPractitionerDALServiceImpl implements AclPractitionerDALService {
    private static final Logger LOG = Logger.getLogger(AclPractitionerDALServiceImpl.class);
    @Resource
    private AclPractitionerMapper aclPractitionerMapper;
    @Autowired
    private AudienceSetting audienceSetting;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AclCustomerMapper aclCustomerMapper;
    @Autowired
    PractitionerService practitionerService;
    @Autowired
    private AclPractitionerDALService aclPractitionerDALService;
    @Autowired
    private AclPractitionerSubordinateSystemDALService aclPractitionerSubordinateSystemDalService;
    @Override
    public AclPractitioner findByCustomerIdIsActive(Long customerId, int isActive) {
        return aclPractitionerMapper.findByCustomerIdIsActive(customerId,isActive);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public PractitionerBasicInfo getPractitionerBasicInfoForOffline(String mobileNo) {
        if(!Strings.isNullOrEmpty(mobileNo)){
            return aclPractitionerMapper.getPractitionerInfoByMobileNoForOffline(mobileNo);
        }else{
            LOG.error("mobileNo is null！");
        }
        return null;
    }

    @Override
    public PractitionerBasicInfo getPractitionerBasicInfoForOnline(String mobileNo) {
        if(!Strings.isNullOrEmpty(mobileNo)){
            return aclPractitionerMapper.getPractitionerInfoByMobileNoForOnline(mobileNo);
        }else{
            LOG.error("mobileNo is null！");
        }
        return null;
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public List<PractitionerRankInfo> getPractitionerRankInfoForOffline(Integer time) {
        return aclPractitionerMapper.getPractitionerRankInfoForOffline(time);
    }

    @Override
    public List<PractitionerRankInfo> getPractitionerRankInfoForOnline(Integer time,Long practitionerTypeId) {
        return aclPractitionerMapper.getPractitionerRankInfoForOnline(time,practitionerTypeId);
    }

    @Override
    public List<PractitionerRankInfo> getPractitionerRankInfoForSpecials(List<String> mobileSpecials,Integer time) {
        return aclPractitionerMapper.getPractitionerRankInfoForSpecials(mobileSpecials,time);
    }

    @Override
    public PractitionerInfo findPractitionerInfoByLogin(String mobileNo) {
        return aclPractitionerMapper.findPractitionerInfoByLogin(mobileNo);
    }

    @Override
    public List<PractitionerInfo> findPractitionerInfoByPractitionerCode(List<String> paramList) {
        return aclPractitionerMapper.findPractitionerInfoByPractitionerCode(paramList);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_MASTER)
    public AclPractitioner findPractitionerById(Long practitionerId) {
        return aclPractitionerMapper.selectByPrimaryKey(practitionerId);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_MASTER)
    public void updatePractitioner(AclPractitioner practitioner) {
        aclPractitionerMapper.updateByPrimaryKeySelective(practitioner);
    }

    @Override
    public List<OwnOpportunityInfo> ownOpportunityQuery(Long practitionerId) {
        return aclPractitionerMapper.ownOpportunityQuery(practitionerId);
    }
    @Override
    public List<AclPractitioner> findByIds(List<Long> practitionerIdList) {
        return aclPractitionerMapper.findByIds(practitionerIdList);
    }

    @Override
    public List<AclPractitioner> findForSubordinateIdByPractitionerId(Long practitionerId) {
        return aclPractitionerMapper.findForSubordinateIdByPractitionerId(practitionerId) ;
    }

    @Override
    public List<PlayerSalesActivityInfo> playerSalesActivityQuery(Long practitionerId, Long optionsId) {
        return aclPractitionerMapper.playerSalesActivityQuery(practitionerId, optionsId);
    }
    @Override
    public List<AclPractitioner> findBySubordinateSystemId(Long subordinateSystemId,String systemType) {
        return aclPractitionerMapper.findBySubordinateSystemId(subordinateSystemId,systemType);
    }

    @Override
    public String findMobileNoByPractitionerId(Long practitionerId) {
        String mobileNo =  aclPractitionerMapper.findMobileNoByPractitionerId(practitionerId);
        if(!Strings.isNullOrEmpty(mobileNo)){
            DESTypeHandler jpaCryptoConverter = new DESTypeHandler();
            mobileNo = jpaCryptoConverter.decode(mobileNo);
        }
        return mobileNo;
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public PractitionerBasicInfo findByMobileNoE(String mobileNo) {
        return aclPractitionerMapper.findByMobileNoE(mobileNo);
    }

    @Override
    public AclPractitioner findById(Long practitionerId) {
        return aclPractitionerMapper.selectByPrimaryKey(practitionerId);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public PractitionerRankInfo getPractitionerRankInfoByPractitionerIdEG(String practitionerIdEG, Integer time) {
        return aclPractitionerMapper.getPractitionerRankInfoByPractitionerIdEG(practitionerIdEG,time);
    }

    @Override
    public PractitionerRankInfo getPractitionerRankInfoByPractitionerIdYD(Long practitionerId, Integer time) {
        return aclPractitionerMapper.getPractitionerRankInfoByPractitionerIdYD(practitionerId,time);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public List<PayScaleInfo> findPayScaleByPractitionerEG(String practitionerIdEG) {
        return aclPractitionerMapper.findPayScaleByPractitionerEG(practitionerIdEG);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public PayScaleBasicInfo findFilePathByMonShId(Integer monShId) {
        return aclPractitionerMapper.findFilePathByMonShId(monShId);
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public PractitionerBasicInfo findByIdEG(String practitionerIdEG) {
        return aclPractitionerMapper.findByIdEG(practitionerIdEG);
    }

    @Override
    public AclPractitioner findPractitionerByLeadsAssignedId(Long leadsAssignedId) {
        return aclPractitionerMapper.findPractitionerByLeadsAssignedId(leadsAssignedId);
    }

    @Override
    public List<AclPractitioner> findAll() {
        return aclPractitionerMapper.findAll();
    }

    @Override
    public int isTeamLeader(Long practitionerId) {
        return aclPractitionerMapper.isTeamLeader(practitionerId);
    }

    @Override
    public List<Long> queryTeamAllPractitionerId(Long practitionerId,Integer isActive) {
        return aclPractitionerMapper.queryTeamAllPractitionerId(practitionerId, isActive);
    }

    @Override
    public List<Long> queryMentoredByPractitionerId(Long practitionerId) {
        return aclPractitionerMapper.queryMentoredByPractitionerId(practitionerId);
    }

    @Override
    public void save(AclPractitioner practitioner) {
        aclPractitionerMapper.insert(practitioner);
    }

    @Override
    public PractitionerInfo findPractitionerInfoByPractitionerId(Long practitionerId) {
        return aclPractitionerMapper.findPractitionerInfoByPractitionerId(practitionerId);
    }

    @Override
    public List<TeamMemberDetail> queryTeamMemberDetailList(List<Long> practitionerIdList) {
        return aclPractitionerMapper.queryTeamMemberDetailList(practitionerIdList);
    }

    @Override
    public List<String> findLeaveOfficeByPractitionerId(Long practitionerId) {
        DESTypeHandler jpaCryptoConverter = new DESTypeHandler();
        List<String> mobileNos = aclPractitionerMapper.findLeaveOfficeByPractitionerId(practitionerId);
        List<String> mobileNoList = new ArrayList<>(mobileNos.size());
        mobileNos.forEach(m -> mobileNoList.add(jpaCryptoConverter.decode(m)));
        return mobileNoList;
    }

    @Override
    public List<AclPractitioner> queryAllLifePractitioner() {
        return aclPractitionerMapper.queryAllLifePractitioner();
    }

    @Override
    public List<PractitionerInfo> findPractitionerInfoByNameList(List<String> nameList) {
        return aclPractitionerMapper.findPractitionerInfoByNameList(nameList);
    }

    @Override
    public List<PractitionerInfo> findPractitionerInfoByMobileList(List<String> mobileList) {
        return aclPractitionerMapper.findPractitionerInfoByMobileList(mobileList);
    }

    @Override
    public List<PayScaleInfo> queryEGHistorySalaryPDFByPractitionerId(Long practitionerId) {
        return aclPractitionerMapper.queryEGHistorySalaryPDFByPractitionerId(practitionerId);
    }

    @Override
    public List<AclCustomer> getAclCustomers(Long practitionerId,Long flag) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String userId = "";
        int issuerLength = audienceSetting.issuer.length();
        String token = request.getHeader(audienceSetting.header);
        if(!CommonUtil.isNullOrBlank(token) && token.length() > issuerLength){
            String headStr = token.substring(0, issuerLength).toLowerCase();
            if (headStr.compareTo(audienceSetting.issuer) == 0){
                token = token.substring(issuerLength, token.length());
                //token格式合法并且没有失效
                if (jwtTokenUtil.validateToken(token) && !jwtTokenUtil.isTokenExpired(token)){
                    userId = jwtTokenUtil.getUserIdToken(token);
                }
            }
        }
        LOG.info("等保调整，token中的userId: "+userId);
        if(CommonUtil.isNullOrBlank(userId)){
            return null;
        }
        AclPractitioner practitioner = aclPractitionerMapper.selectByPrimaryKey(practitionerId);
        if(null != practitioner){
            Long customerId = null;
            //我的团队，特殊处理
            if(null != flag){
                AclPractitioner practitioner1 = aclPractitionerMapper.selectByMobileNo(userId);
                //育成人 特殊处理
                List<AclPractitioner> practitionerList = aclPractitionerDALService.findByIds(practitionerService.getPractitionerIdList(practitioner1.getId(),null));
                if(null != practitioner.getRaiseId()){
                    practitionerList.add(practitioner);
                }
                AclPractitionerSubordinateSystem aclPractitionerSubordinateSystem =aclPractitionerSubordinateSystemDalService.findById(practitioner.getSubordinateSystemId());
                if(null != aclPractitionerSubordinateSystem && aclPractitionerSubordinateSystem.getOwnerPractitionerId() != null){
                    practitionerList.add(practitioner);
                }
                if(null != practitionerList && practitionerList.size() > 0){
                    for(AclPractitioner acl:practitionerList){
                        if(practitioner.getCustomerId().equals(acl.getCustomerId())){
                            customerId = acl.getCustomerId();
                            userId = practitioner.getMobileNo();
                            break;
                        }
                    }
                }
            }
            if(null == customerId || null == flag){
                customerId=practitioner.getCustomerId();
            }
            AclCustomer aclCustomer = new AclCustomer();
            aclCustomer.setId(customerId);
            aclCustomer.setMobileNo(userId);
            List<AclCustomer> findByObjSortable = aclCustomerMapper.findByObj(aclCustomer);
            if(findByObjSortable == null || findByObjSortable.size() == 0){
                return null;
            }
            return findByObjSortable;
        }
        return null;
    }

    @Override
    public List<TeamMemberDetail> queryTeamMemberDetailRaiseList(List<Long> practitionerIdList) {
        return aclPractitionerMapper.queryTeamMemberDetailRaiseList(practitionerIdList);
    }

    @Override
    public AclPractitioner findPractitionerByRaise(Long practitionerId) {
        return aclPractitionerMapper.findPractitionerByRaise(practitionerId);
    }
}
