package cn.com.ty.lift.business.project.service;

import cn.com.ty.lift.business.framework.util.MessageUtils;
import cn.com.ty.lift.business.project.dao.entity.ProjectUser;
import cn.com.ty.lift.business.project.dao.entity.model.request.ProjectRequest;
import cn.com.ty.lift.business.project.dao.entity.model.response.ProjectRelevanceResponse;
import cn.com.ty.lift.business.project.dao.entity.model.response.ProjectUserResponse;
import cn.com.ty.lift.business.project.dao.mapper.ProjectUserMapper;
import cn.com.ty.lift.common.constants.CommonEnum;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

/**
 * @author bieao
 * @date 2019/12/31
 * @description 项目组成员业务层
 */
@Service
public class ProjectUserService extends ServiceImpl<ProjectUserMapper, ProjectUser> {

    public List<ProjectUserResponse> getUserList(Long projectId, Long mtCompanyId) {
        return baseMapper.findUserListById(projectId, mtCompanyId);
    }

    /**
     * @param projectId 项目ID
     * @param mtCompanyId 公司ID
     * @return List<ProjectUser> userList项目组成员列表
     * @description 查询项目组成员
     * @date 2019/12/13 2:40 PM
     */
    public List<ProjectUserResponse> userList(Long projectId, Long mtCompanyId, Long userId, String currentRoleCode) {
        List<ProjectUserResponse> userList = getUserList(projectId, mtCompanyId);
        List<ProjectUserResponse> workerList = new ArrayList<>();
        if (CommonEnum.DefaultRole.MTWORK.getCode().equals(currentRoleCode)) {
            userList.forEach(entry -> {
                if (Objects.equals(userId, entry.getUserId())) {
                    workerList.add(entry);
                }
            });
            return workerList;
        } else {
            return userList.stream().filter(
                    entry -> (CommonEnum.DefaultRole.MTWORK.getCode().equals(entry.getUserRole())
                            || CommonEnum.DefaultRole.REGION_DIRECTOR.getCode().equals(entry.getUserRole())))
                    .collect(Collectors.toList());
        }
    }

    /**
     * @param request 批量新增项目组成员
     * @return Integer 成功1或失败0
     * @description 批量新增项目组成员
     * @date 2019/12/4 4:41 PM
     */
    public boolean add(ProjectRequest request) {
        List<ProjectUser> userList = request.getUserList();
        userList.forEach(entry -> {
            entry.setProjectId(request.getProjectId());
            entry.setMtCompanyId(request.getMtCompanyId());
            entry.setUserRole(CommonEnum.DefaultRole.MTWORK.getCode());
        });
        return saveBatch(userList);
    }

    /**
     * @param request 修改项目组成员
     * @return Integer 成功1或失败0
     * @description 修改项目组成员
     * @date 2020/1/11 10:43 上午
     */
    @Transactional(rollbackFor = Exception.class)
    public RestResponse modify(ProjectRequest request){
        QueryWrapper<ProjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", request.getUserId());
        queryWrapper.eq("project_id", request.getProjectId());
        queryWrapper.eq("user_role", CommonEnum.DefaultRole.MTWORK.getCode());
        ProjectUser entry = getOne(queryWrapper);
        if (ObjectUtil.isEmpty(entry))
            return RestResponse.success(null, MessageUtils.get("msg.user.not.exist"));
        //如果该成员是维保工，升级成维保班长，若该项目组成员还有其他维保班长，则该维保班长设置为维保工
        if (Objects.equals("0", entry.getIsMonitor())) {
            //设置为维保班长
            entry.setIsMonitor("1");
            boolean result = update(entry, queryWrapper);
            if (!result)
                return RestResponse.fail(MessageUtils.get("msg.modify.fail"));
            QueryWrapper<ProjectUser> wrapper = new QueryWrapper<>();
            wrapper.eq("mt_company_id", request.getMtCompanyId());
            wrapper.eq("project_id", request.getProjectId());
            wrapper.eq("user_role", CommonEnum.DefaultRole.MTWORK.getCode());
            List<ProjectUser> userList = list(wrapper);
            Optional<ProjectUser> first = userList.stream().filter(user ->
                    !user.getUserId().equals(entry.getUserId()) && Objects.equals("1", user.getIsMonitor())).findFirst();
            if (first.isPresent()) {
                ProjectUser user = first.get();
                //设置另外的维保班长为维保工
                user.setIsMonitor("0");
                boolean ret = update(user, new QueryWrapper<ProjectUser>() {{
                    eq("user_id", user.getUserId());
                    eq("project_id", user.getProjectId());
                    eq("user_role", CommonEnum.DefaultRole.MTWORK.getCode());
                }});
                if (ret) return RestResponse.success(null, MessageUtils.get("msg.modify.success"));
                else TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return RestResponse.success(null, MessageUtils.get("msg.modify.success"));
        } else {
            //设置为维保工
            entry.setIsMonitor("0");
            update(entry, queryWrapper);
            return RestResponse.success(null, MessageUtils.get("msg.modify.success"));
        }
    }

    /**
     * @param id          项目id
     * @param mtCompanyId 公司id
     * @return 是否成功
     * @description 批量删除项目组成员
     * @date 2020/5/26 5:33 下午
     */
    public boolean removeByMap(Long id, Long mtCompanyId) {
        Map<String, Object> columnMap = new HashMap<>(2);
        columnMap.put("mt_company_id", mtCompanyId);
        columnMap.put("project_id", id);
        return removeByMap(columnMap);
    }

    /**
     * @param request 批量删除项目组成员
     * @return Integer 成功1或失败0
     * @description 批量删除项目组成员
     * @date 2020/1/11 10:43 上午
     */
    public int remove(ProjectRequest request) {
        List<ProjectUser> userList = request.getUserList();
        userList.forEach(entry -> {
            entry.setProjectId(request.getProjectId());
            entry.setMtCompanyId(request.getMtCompanyId());
            entry.setUserRole(CommonEnum.DefaultRole.MTWORK.getCode());
        });
        return baseMapper.batchRemoveWithParams(request);
    }

    public RestResponse relevanceProject(ProjectRequest request) {
        IPage<ProjectRelevanceResponse> relevancePage = baseMapper.findProjectListByUserId(request.getPage(), request);
        return RestResponse.success(relevancePage);
    }
}
