package com.qmth.sop.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.sop.business.bean.dto.DataPermissionDto;
import com.qmth.sop.business.bean.dto.UserArchivesAllocationDto;
import com.qmth.sop.business.bean.result.ProjectMonitorCardResult;
import com.qmth.sop.business.bean.result.ProjectMonitorResult;
import com.qmth.sop.business.bean.result.ProjectMonitorUserResult;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBSopInfo;
import com.qmth.sop.business.entity.TBUserArchives;
import com.qmth.sop.business.mapper.TBSopInfoMapper;
import com.qmth.sop.business.service.*;
import com.qmth.sop.common.enums.CrmProcessEnum;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.SopRoleTypeEnum;
import com.qmth.sop.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ProjectMonitorServiceImpl extends ServiceImpl<TBSopInfoMapper, TBSopInfo> implements ProjectMonitorService {

    @Resource
    SysUserService sysUserService;

    @Resource
    TBUserArchivesAllocationService tbUserArchivesAllocationService;

    @Resource
    TBUserArchivesService tbUserArchivesService;

    @Resource
    BasicAttachmentService basicAttachmentService;

    @Override
    public IPage<ProjectMonitorResult> pageProjectMonitor(Page<ProjectMonitorResult> page, Long serviceUnitId, Long customerId, CrmProcessEnum process) {
        SysUser user = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(user.getId());
        List<String> processList = new ArrayList<>();
        if (process != null) {
            processList = getProcessList(process);
        }

        IPage<ProjectMonitorResult> pageProjectMonitor = baseMapper.pageProjectMonitor(new Page<>(page.getCurrent(), page.getSize()),
                serviceUnitId, customerId, process, processList, dpr);
        List<ProjectMonitorResult> monitorResultList = pageProjectMonitor.getRecords();
        for (ProjectMonitorResult monitorResult : monitorResultList) {
            monitorResult.setProcess(CrmProcessEnum.findCrmProcessByDesc(monitorResult.getTaskName()));
            List<UserArchivesAllocationDto> allocationDtoList = tbUserArchivesAllocationService.listUserArchivesAllocation(
                    monitorResult.getCrmDetailId());
            List<ProjectMonitorUserResult> coordinatorList = filterUserArchivesAllocation(allocationDtoList, SopRoleTypeEnum.REGION_COORDINATOR);
            monitorResult.setRegionCoordinator(!coordinatorList.isEmpty() ? coordinatorList.get(0) : null);
            List<ProjectMonitorUserResult> managerList = filterUserArchivesAllocation(allocationDtoList, SopRoleTypeEnum.PROJECT_MANAGER);
            monitorResult.setProjectManager(!managerList.isEmpty() ? managerList.get(0) : null);
            monitorResult.setEngineerList(filterUserArchivesAllocation(allocationDtoList, SopRoleTypeEnum.ENGINEER));
        }

        return pageProjectMonitor;
    }

    @Override
    public ProjectMonitorCardResult getUserCard(Long userId) {
        TBUserArchives userArchives = tbUserArchivesService.findByUserId(userId);
        if (Objects.isNull(userArchives)) {
            throw ExceptionResultEnum.ERROR.exception("人员不存在");
        }

        ProjectMonitorCardResult userCard = new ProjectMonitorCardResult();
        userCard.setName(userArchives.getName());
        userCard.setCode(userArchives.getCode());
        userCard.setMobileNumber(userArchives.getMobileNumber());
        try {
            if (StringUtils.isNotBlank(userArchives.getBasePhotoPath())) {
                userCard.setPhotoPath(basicAttachmentService.filePreviewPath(userArchives.getBasePhotoPath()));
            }
        } catch (Exception e) {
            log.error("[项目监控-工作证]照片预览出错:" + e.getMessage());
            userCard.setPhotoPath(null);
        }
        //项目经验
        if (StringUtils.isNotBlank(userArchives.getProjectExperience())) {
            List<String> resultList = JSONObject.parseArray(userArchives.getProjectExperience(),String.class);
            userCard.setProjectExperience(resultList);
        }
        return userCard;
    }


    private List<ProjectMonitorUserResult> filterUserArchivesAllocation(List<UserArchivesAllocationDto> allocationDtoList, SopRoleTypeEnum roleType) {
        List<ProjectMonitorUserResult> monitorResultList = new ArrayList<>();
        List<UserArchivesAllocationDto> filterUserList = allocationDtoList.stream().filter(user -> user.getSopRoleType().equals(roleType)).collect(
                Collectors.toList());
        for (UserArchivesAllocationDto dto : filterUserList) {
            ProjectMonitorUserResult userResult = new ProjectMonitorUserResult();
            BeanUtils.copyProperties(dto, userResult);
            monitorResultList.add(userResult);
        }
        return monitorResultList;
    }

    private List<String> getProcessList(CrmProcessEnum process) {
        List<String> processList = new ArrayList<>();
        if (process == CrmProcessEnum.FINISH) {
            return processList;
        }
        String[] descArr = process.getDesc().split(",");
        return Arrays.asList(descArr);
    }

}
