package com.cool.store.service.impl;

import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.LineInfoDAO;
import com.cool.store.entity.*;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.ExperienceStatusEnum;
import com.cool.store.enums.WorkflowSubStageEnum;
import com.cool.store.enums.WorkflowSubStageStatusEnum;
import com.cool.store.enums.*;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.*;
import com.cool.store.request.TrainingExperienceDistributionRequest;
import com.cool.store.service.TrainingExperienceService;
import com.cool.store.utils.poi.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.annotation.Tainted;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.cool.store.enums.ErrorCodeEnum.INTERVIEW_LINE_ID_IS_NULL;

@Service
@Slf4j
public class TrainingExperienceServiceImpl extends LineFlowService implements TrainingExperienceService {

    @Resource
    TrainingExperienceMapper trainingExperienceMapper;

    @Resource
    LineInfoMapper lineInfoMapper;

    @Resource
    LineInfoDAO lineInfoDAO;

    @Resource
    SysRoleMapper sysRoleMapper;

    @Resource
    EnterpriseUserMapper enterpriseUserMapper;

    @Resource
    EnterpriseUserRoleMapper enterpriseUserRoleMapper;

    @Resource
    UserAuthMappingMapper userAuthMappingMapper;


    @Resource
    private CommonService commonService;

    @Resource
    RegionMapper regionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean distribution(TrainingExperienceDistributionRequest request) {
//        if (Objects.isNull(request)) {
//            return Boolean.FALSE;
//        }
//        if (Objects.isNull(request.getLineId())) {
//            throw new ServiceException(ErrorCodeEnum.INTERVIEW_LINE_ID_IS_NULL);
//        }
//        LeaseBaseInfoDO leaseBaseInfoDO = request.toLeaseBaseInfoDO();
//        Date currentDate = new Date();
//        LineInfoDO lineInfoDO = new LineInfoDO();
//        if (request.getExperienceStartTime().compareTo(request.getExperienceEndTime()) >= 0) {
//            throw new ServiceException(ErrorCodeEnum.TIME_FALSE);
//        }
//        if (currentDate.before(request.getExperienceStartTime())) {
//            leaseBaseInfoDO.setExperienceStatus(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_85.getCode());
//            lineInfoDO.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_85.getCode());
//            LineInfoDO msgLineInfo = lineInfoMapper.getByLineId(request.getLineId());
//            Map<String, String> templateParam = new HashMap<>();
//            templateParam.put("shopName", request.getStoreName());
//            templateParam.put("experienceTime", String.format("%s 到 %s", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, request.getExperienceStartTime()),
//                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, request.getExperienceEndTime())));
//            commonService.sendSms(msgLineInfo.getMobile(), SMSMsgEnum.SHOP_EXPERIENCE,templateParam);
//        } else if (currentDate.after(request.getExperienceStartTime()) || currentDate.before(request.getExperienceEndTime())) {
//            leaseBaseInfoDO.setExperienceStatus(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_90.getCode());
//            lineInfoDO.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_90.getCode());
//        } else {
//            throw new ServiceException("时间");
//        }
//        trainingExperienceMapper.insert(leaseBaseInfoDO);
//        lineInfoDO.setWorkflowSubStage(WorkflowSubStageEnum.STORE_EXPERIENCE.getCode());
//        lineInfoDO.setId(request.getLineId());
//        lineInfoMapper.updateByPrimaryKeySelective(lineInfoDO);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void experienceStatusChange(Long lineId, Integer status, String abandonCause) {
//        trainingExperienceMapper.updateStatus(lineId, status, abandonCause);
//        LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(lineId);
//        if (ExperienceStatusEnum.DONE.getExperienceStatus().equals(status)) {
//            if (Objects.isNull(lineInfoDO)) {
//                throw new ServiceException(ErrorCodeEnum.INTERVIEW_PARTNER_NOT_EXIST);
//            }
//            lineInfoDO.setWorkflowSubStage(WorkflowSubStageEnum.SECOND_INTERVIEWS.getCode());
//            lineInfoDO.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.SECOND_INTERVIEWS_100.getCode());
//            lineInfoMapper.updateByPrimaryKeySelective(lineInfoDO);
//            commonService.sendSms(lineInfoDO.getMobile(),SMSMsgEnum.SECOND_INTERVIEW_APPOINTMENT);
//        } else {
//            lineInfoDO.setWorkflowSubStage(WorkflowSubStageEnum.STORE_EXPERIENCE.getCode());
//            lineInfoDO.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_95.getCode());
//            lineInfoMapper.updateByPrimaryKeySelective(lineInfoDO);
//
//            Map<String, String> requestMap = new HashMap<>();
//            requestMap.put("partnerUsername",lineInfoDO.getUsername());
//            requestMap.put("partnerMobile",lineInfoDO.getMobile());
//            requestMap.put("lineId",String.valueOf(lineInfoDO.getId()));
//            commonService.sendMessage(Collections.singletonList(lineInfoDO.getInvestmentManager()),
//                    MessageEnum.MESSAGE_33,
//                    requestMap);
//        }

    }

    @Override
    public LeaseBaseInfoDO getTrainingExperience(Long lineId) {
        List<String> roleNames = new ArrayList<>();
        roleNames.add("加盟店店长");
        roleNames.add("加盟店储备店长");
        roleNames.add("店长");

        LeaseBaseInfoDO leaseBaseInfoDO = trainingExperienceMapper.selectByLineId(lineId);
//        if (Objects.isNull(leaseBaseInfoDO)) {
//            leaseBaseInfoDO = new LeaseBaseInfoDO();
//            LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(lineId);
//            if (Objects.nonNull(lineInfoDO)
//                    && lineInfoDO.getWorkflowSubStage().equals(WorkflowSubStageEnum.STORE_EXPERIENCE.getCode())
//                    && lineInfoDO.getWorkflowSubStageStatus().equals(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_85.getCode())) {
//                leaseBaseInfoDO.setExperienceStatus(WorkflowSubStageStatusEnum.STORE_EXPERIENCE_85.getCode());
//                return leaseBaseInfoDO;
//            }
//            return null;
//        }
        List<SysRoleDO> xfStoreManager = sysRoleMapper.getXFStoreManager(roleNames);
        List<Long> roleIds = xfStoreManager.stream().map(SysRoleDO::getId).collect(Collectors.toList());
        //店长角色的用户id
        List<String> userIdsByRoleIdList = enterpriseUserRoleMapper.getUserIdsByRoleIdList(roleIds);
        //当前门店
        RegionDO storeRegion = regionMapper.getRegionByStoreId(leaseBaseInfoDO.getStoreId());
        //权限
        List<String> userIdsByMappingIds = userAuthMappingMapper.getUserIdsByMappingIds(Collections.singletonList(storeRegion.getRegionId()));
        //过滤
        userIdsByMappingIds.retainAll(userIdsByRoleIdList);
        //用户
        if (CollectionUtils.isEmpty(userIdsByMappingIds)){
            leaseBaseInfoDO.setStoreManager("");
            return leaseBaseInfoDO;
        }
        List<EnterpriseUserDO> userInfoByUserIds = enterpriseUserMapper.getUserInfoByUserIds(userIdsByMappingIds);
        if (CollectionUtils.isNotEmpty(userInfoByUserIds)){
            String nameList = userInfoByUserIds.stream().map(EnterpriseUserDO::getName).collect(Collectors.joining(CommonConstants.COMMA));
            leaseBaseInfoDO.setStoreManager(nameList);
        }
        return leaseBaseInfoDO;
    }

    @Override
    protected Boolean auditPass(Long auditId, LineInfoDO lineInfo, String userId) {
        WorkflowSubStageEnum workflowSubStageEnum = WorkflowSubStageEnum.getWorkflowSubStageEnum(lineInfo.getWorkflowSubStage());
        WorkflowSubStageEnum nextStage = workflowSubStageEnum.getNextStage();
        //更新线索阶段
        lineInfoDAO.updateWorkflowStage(lineInfo.getId(), nextStage, nextStage.getInitStatus(), userId);
        return Boolean.TRUE;
    }

    @Override
    protected Boolean auditReject(Long auditId, LineInfoDO lineInfo, String userId) {
        return Boolean.TRUE;
    }


}
