package cn.com.ctop.common.service.impl;


import cn.com.ctop.common.constant.CtopAdConstant;
import cn.com.ctop.common.entity.Project;
import cn.com.ctop.common.entity.ProjectMember;
import cn.com.ctop.common.entity.UserAllocation;
import cn.com.ctop.common.mapper.ProjectMemberMapper;
import cn.com.ctop.common.mapper.UserAllocationMapper;
import cn.com.ctop.common.service.IProjectMemberService;
import cn.com.ctop.common.service.ISysUserService;
import cn.com.ctop.common.utils.Check;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.entity.SysUser;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
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 {
    @Resource
    private ProjectMemberMapper memberMapper;
    @Resource
    private UserAllocationMapper userAllocationMapper;

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


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

    /**
     * 查询所有产品
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> selectProductsByUserId(String userId) {
        return memberMapper.selectProductsByUserId(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 ("plan".equals(roleCode) || "clip".equals(roleCode) || "shot".equals(roleCode) || "plane".equals(roleCode) || "planeLeader".equals(roleCode)) {
            projectMemberList = memberMapper.designProjects(userId, mediaIds);
        } else if ("designTeamLeader".equals(roleCode)) {
            projectMemberList = memberMapper.designLeaderProjects(companyId, mediaIds);
        } else if ("admin".equals(roleCode)) {
            projectMemberList = memberMapper.adminProjects(mediaIds);
        } else if ("operator".equals(roleCode) || "operationAssistant".equals(roleCode) || "touTiaoOperationManager".equals(roleCode)) {
            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, String mediaType) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Integer> mediaList = new ArrayList<>();
        if (mediaType.equals(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE)) {
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT);
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INSIDE_INT);
        } else if (mediaType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INSIDE_INT);
        }
        //查询登录账号下的项目
        List<ProjectMember> projectMemberList = this.queryProjectMemberBy(userId, mediaList);
        if (projectMemberList.isEmpty()) {
            return result;
        }
        Map<Long, List<JSONObject>> accountMap = this.getAccountListByProjectMemberList(projectMemberList);
        for (ProjectMember member : projectMemberList) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("project", member);
            List<JSONObject> jsonObjects = accountMap.get(member.getProjectId());
            if (Check.isNull(jsonObjects)) {
                continue;
            }
            temp.put("account", jsonObjects);
            result.add(temp);
        }

        return result;
    }

    private Map<Long, List<JSONObject>> getAccountListByProjectMemberList(List<ProjectMember> projectMemberList) {
        Map<Long, List<JSONObject>> map = new HashMap<>();
        List list = new ArrayList();
        for (ProjectMember member : projectMemberList) {
            list.add(member.getProjectId());
            map.put(member.getProjectId(), new ArrayList<>());
        }

        List<JSONObject> jsonList = userAllocationMapper.getAccountListByProjectList(list,null);
        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject jsonObject = jsonList.get(i);
            Long projectId = jsonObject.getLong("projectId");
            List<JSONObject> jsonObjects = map.get(projectId);
            jsonObjects.add(jsonObject);
        }
        return map;


    }

    @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 ("admin".equals(roleCode)) {
            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<Project> selectListByUserId(String userId) {
        return memberMapper.getProjectByUserId(userId);
    }

    @Override
    public List<Long> getProjectByAccountIds(JSONArray accountIds) {
        return memberMapper.getProjectByAccountIds(accountIds);
    }

    @Override
    public List<Long> getProductByAccountIds(JSONArray accountIds) {
        return memberMapper.getProductByAccountIds(accountIds);
    }

    //视频报表
    @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 ("admin".equals(roleCode)) {
            projectMemberList = memberMapper.adminProjects(mediaIds);
        } else {
            //如果以上角色都不是的话直接查询此角色所属项目
            projectMemberList = memberMapper.designProjects(userId, mediaIds);
        }

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

        return projectMemberList;
    }

    @Override
    public List<JSONObject> getProjectByUserIdAndMediaIds(List<String> userIds, List<Integer> mediaIds) {
        return memberMapper.getProjectByUserIdAndMediaIds(userIds, mediaIds);
    }

    @Override
    public List<Map<String, Object>> getAllProjectAccount(String mediaType) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Integer> mediaList = new ArrayList<>();
        if (mediaType.equals(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE)) {
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT);
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INSIDE_INT);
        } else if (mediaType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INSIDE_INT);
        }

        //查询登录账号下的项目
        List<ProjectMember> projectMemberList = this.memberMapper.adminProjects(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 List<Long> getProjectIdsByProductId(Long productId, String userId) {
        return memberMapper.getProjectIdsByProductId(productId, userId);
    }

}



