package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.entity.SysUser;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.ISysRoleExtService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.ctop.entity.ProjectMember;
import org.jeecg.modules.ctop.mapper.ProjectMemberMapper;
import org.jeecg.modules.ctop.service.IProjectMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目成员
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-11-19
 */
@Service
public class ProjectMemberServiceImpl extends ServiceImpl<ProjectMemberMapper, ProjectMember> implements IProjectMemberService {

    @Autowired
    private ProjectMemberMapper memberMapper;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private UserAllocationMapper userAllocationMapper;

    private static final String[] PERMISSION_VIEW_PROJECT = {"admin", "saleDirector", "sale", "saleAssistant", "saleAm"};

    @Override
    public void addMember(SysUser sysUser, Project project) {
        Map<String, Object> map = new HashMap<>();
        map.put("project_id", project.getId());
        map.put("user_id", sysUser.getId());
        this.removeByMap(map);
        ProjectMember member = new ProjectMember();
        member.setProjectId(project.getId());
        member.setProjectName(project.getProjectName());
        member.setUserId(sysUser.getId());
        member.setUserName(sysUser.getRealname());
        String roleCode = sysRoleService.getRoleCodeByUserId(sysUser.getId());
        if (!Check.isNull(roleCode)) {
            member.setRoleCode(roleCode);
        }
        this.save(member);
    }


    /**
     * 查询所有项目
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> selectProjectsByUserId(String userId) {
        return memberMapper.selectProjectsByUserId(userId);
    }

    //视频报表
    @Override
    public List<ProjectMember> getProjects(List<Integer> mediaIds) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        String roleCode = memberMapper.getRoleCodeByUserId(userId);
        String companyId = memberMapper.getCompanyIdByUserId(userId);

        //角色权限判断
        List<ProjectMember> projectMemberList = null;
        if (roleCode.equals("plan") || roleCode.equals("clip") || roleCode.equals("shot") || roleCode.equals("plane") || roleCode.equals("planeLeader")) {
            projectMemberList = memberMapper.designProjects(userId, mediaIds);
        } else if (roleCode.equals("designTeamLeader")) {
            projectMemberList = memberMapper.designLeaderProjects(companyId, mediaIds);
        } else if (roleCode.equals("admin")) {
            projectMemberList = memberMapper.adminProjects(mediaIds);
        } else if (roleCode.equals("operator") || roleCode.equals("operationAssistant") || roleCode.equals("touTiaoOperationManager")) {
            projectMemberList = memberMapper.designProjects(userId, mediaIds);
        } else {
            //如果以上角色都不是的话直接查询此角色所属项目
            projectMemberList = memberMapper.designProjects(userId, mediaIds);
        }

        if (null == projectMemberList) {
            projectMemberList = new ArrayList<>();
        }

        return projectMemberList;
    }

    @Override
    public List<Map<String, Object>> getProjectAccountByUserId(String userId) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Integer> mediaList = new ArrayList<>();
        mediaList.add(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT);
        mediaList.add(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INSIDE_INT);
        //查询登录账号下的项目
        List<ProjectMember> projectMemberList = this.queryProjectMemberBy(userId, mediaList);
        if (projectMemberList.isEmpty()) {
            return result;
        }
        projectMemberList.forEach(ProjectMember -> {
            Map<String, Object> temp = this.queryAccountByProjectId(ProjectMember);
            if (temp != null) {
                result.add(temp);
            }
        });
        return result;
    }

    @Override
    public ProjectMember getProjectByParams(Long targetProject, String userId) {
        QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
        if (null != targetProject) {
            queryWrapper.eq("project_id", targetProject);
        }
        if (null != userId) {
            queryWrapper.eq("user_id", userId);
        }
        queryWrapper.last("limit 1");
        return null;
    }


    private Map<String, Object> queryAccountByProjectId(ProjectMember projectMember) {
        Map<String, Object> temp = new HashMap<>();
        temp.put("project", projectMember);
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectMember.getProjectId());
        queryWrapper.isNotNull("account_id");
        List<UserAllocation> userAllocations = userAllocationMapper.selectList(queryWrapper);
        if (userAllocations.isEmpty()) {
            temp = null;
        } else {
            temp.put("account", userAllocations);
        }
        return temp;
    }

    private List<ProjectMember> queryProjectMemberBy(String userId, List<Integer> mediaIds) {
        String roleCode = memberMapper.getRoleCodeByUserId(userId);
        if (ArrayUtils.contains(PERMISSION_VIEW_PROJECT, roleCode)) {
            return memberMapper.adminProjects(mediaIds);
        }
        return memberMapper.queryProjectMemberByUserId(userId, mediaIds);
    }


    //查看销售所在平台项目
    @Override
    public List<ProjectMember> getSaleOwnProjects(List<Integer> mediaIds) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        String roleCode = memberMapper.getRoleCodeByUserId(userId);

        //角色权限判断
        List<ProjectMember> projectMemberList = null;
        if (roleCode.equals("admin")) {
            projectMemberList = memberMapper.adminProjects(mediaIds);
        } else {
            //如果以上角色都不是的话直接查询此角色所属项目
            projectMemberList = memberMapper.getSaleProjects(userId, mediaIds);
        }

        if (null == projectMemberList) {
            projectMemberList = new ArrayList<>();
        }

        return projectMemberList;
    }

    @Override
    public List<Long> getProjectByMap(String userId) {
        return memberMapper.getProjectByMap(userId);
    }

    //视频报表
    @Override
    public List<ProjectMember> getOwnProjects(List<Integer> mediaIds) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        String roleCode = memberMapper.getRoleCodeByUserId(userId);

        //角色权限判断
        List<ProjectMember> projectMemberList = null;
        if (roleCode.equals("admin")) {
            projectMemberList = memberMapper.adminProjects(mediaIds);
        } else {
            //如果以上角色都不是的话直接查询此角色所属项目
            projectMemberList = memberMapper.designProjects(userId, mediaIds);
        }

        if (null == projectMemberList) {
            projectMemberList = new ArrayList<>();
        }

        return projectMemberList;
    }


}
