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

import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.entity.UserCompany;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.IProductService;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.service.ISysRoleExtService;
import cn.com.ctop.common.module.service.ISysUserService;
import cn.com.ctop.common.module.service.IUserCompanyService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
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.jeecg.modules.ctop.entity.ProjectMember;
import org.jeecg.modules.ctop.mapper.ProjectMemberMapper;
import org.jeecg.modules.ctop.service.IAdvertiserService;
import org.jeecg.modules.ctop.service.IProjectMemberService;
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 {
    @Autowired
    private ProjectMemberMapper memberMapper;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private UserAllocationMapper userAllocationMapper;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IAdvertiserService advertiserService;
    @Autowired
    private IProductService productService;
    @Resource
    private IUserCompanyService userCompanyService;

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

    @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);
    }

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


    //视频报表
    @Override
    public List<ProjectMember> getProjects(List<Integer> mediaIds, String userId) {
//        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, null);
        } 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<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, null);
        } 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);
        } else if (mediaType.equals(CtopAdConstant.PLATFORM_TYPE_TENCENT)
                || mediaType.equals(CtopAdConstant.PLATFORM_TYPE_TENCENT_PY)) {
            mediaList.add(CtopAdConstant.PLATFORM_TYPE_TENCENT_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);
        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) {
//        UserCompany userCompany = userCompanyService.getByUserId(userId);
//        if (Check.isNull(userCompany)) {
//            return null;
//        }
//        String companyId = userCompany.getCompanyId();
        String roleCode = memberMapper.getRoleCodeByUserId(userId);
        if ("admin".equals(roleCode)) {
            return memberMapper.adminProjects(mediaIds, null);
        } else if (ArrayUtils.contains(PERMISSION_VIEW_PROJECT, roleCode)) {
            return memberMapper.adminProjects(mediaIds, null);
        }
        return memberMapper.queryProjectMemberByUserId(userId, mediaIds, null);
    }


    //查看销售所在平台项目
    @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, null);
        } 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, null);
        } 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, null);
        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<ProjectMember> getMapsByProjectList(List<ProjectMember> projectMembers) {
        if (Check.isNull(projectMembers)) {
            return projectMembers;
        }
        JSONArray projectIdArray = new JSONArray();
        if (!Check.isNull(projectMembers)) {
            for (ProjectMember member : projectMembers) {
                projectIdArray.add(member.getProjectId());
            }
        }
        List<JSONObject> projectList = projectService.getProjectListByIds(projectIdArray);
        if (Check.isNull(projectList)) {
            return projectMembers;
        }
        Map<Long, JSONObject> projectMap = new HashMap<>();
        for (int i = 0; i < projectList.size(); i++) {
            JSONObject projectJson = projectList.get(i);
            projectMap.put(projectJson.getLong("projectId"), projectJson);
        }
        Map<String, String> userIdMap = new HashMap<>();
        Map<String, String> advertiserIdMap = new HashMap<>();
        Map<Long, Long> productIdMap = new HashMap<>();
        for (int i = 0; i < projectList.size(); i++) {
            JSONObject projectJson = projectList.get(i);
            if (!Check.isNull(projectJson.getString("responsibleId"))) {
                userIdMap.put(projectJson.getString("responsibleId"), projectJson.getString("responsibleId"));
            }
            if (!Check.isNull(projectJson.getString("designResponsibleId"))) {
                userIdMap.put(projectJson.getString("designResponsibleId"), projectJson.getString("designResponsibleId"));
            }
            if (!Check.isNull(projectJson.getString("advertiserId"))) {
                advertiserIdMap.put(projectJson.getString("advertiserId"), projectJson.getString("advertiserId"));
            }
            if (!Check.isNull(projectJson.getLong("productId"))) {
                productIdMap.put(projectJson.getLong("productId"), projectJson.getLong("productId"));
            }
        }
        Map<String, String> userMap = new HashMap<>();
        if (!Check.isNullMap(userIdMap)) {
            userMap = userService.getUserMapByMap(userIdMap);
        }

        Map<String, String> advertiserMap = new HashMap<>();
        if (!Check.isNullMap(advertiserIdMap)) {
            List<JSONObject> advertiserList = advertiserService.getAdvertiserByMap(advertiserIdMap);
            if (!Check.isNull(advertiserList)) {
                for (int i = 0; i < advertiserList.size(); i++) {
                    JSONObject advertiserJson = advertiserList.get(i);
                    advertiserMap.put(advertiserJson.getString("id"), advertiserJson.getString("name"));
                }
            }
        }
        Map<Long, String> productMap = new HashMap<>();
        if (!Check.isNullMap(productIdMap)) {
            List<JSONObject> productList = productService.getProductByMap(productIdMap);
            if (!Check.isNull(productList)) {
                for (int i = 0; i < productList.size(); i++) {
                    JSONObject productJson = productList.get(i);
                    productMap.put(productJson.getLong("id"), productJson.getString("productName"));
                }
            }
        }
        for (ProjectMember member : projectMembers) {
            Long projectId = member.getProjectId();
            JSONObject projectJson = projectMap.get(projectId);
            if (Check.isNull(projectJson)) {
                continue;
            }
            member.setMediaId(projectJson.getString("mediaId"));
            member.setMaxBid(projectJson.getLong("maxBid"));
            member.setBidType(projectJson.getString("bidType"));
            member.setOcpxActionType(projectJson.getString("ocpxActionType"));
            member.setDeepConversionType(projectJson.getString("deepConversionType"));
            String advertiserId = projectJson.getString("advertiserId");
            member.setAdvertiserId(advertiserId);
            if (!Check.isNullMap(advertiserMap)) {
                member.setAdvertiserName(advertiserMap.get(advertiserId));
            }
            String responsibleId = projectJson.getString("responsibleId");
            String designResponsibleId = projectJson.getString("designResponsibleId");
            if (!Check.isNullMap(userMap)) {
                member.setResponsibleName(userMap.get(responsibleId));
                member.setDesignResponsibleName(userMap.get(designResponsibleId));
            }
            Long productId = projectJson.getLong("productId");
            member.setProductId(productId);
            if (!Check.isNullMap(productMap)) {
                member.setProductName(productMap.get(productId));
            }
        }
        return projectMembers;
    }

    @Override
    public List<ProjectMember> getOwnProducts(List<Integer> mediaList, Long productId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();
        String roleCode = memberMapper.getRoleCodeByUserId(userId);

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


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

        return projectMemberList;
    }

    @Override
    public List<Long> getProjectIdsByProductId(Long productId, String userId, String companyId, String mediaId) {
        return memberMapper.getProjectIdsByProductId(productId, userId, companyId, mediaId);
    }

}


