package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.entity.Advertiser;
import cn.com.ctop.common.module.entity.Product;
import cn.com.ctop.common.module.entity.Project;
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.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.common.system.query.QueryGenerator;
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.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 项目成员
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-11-19
 */
@Slf4j
@Api(tags = "项目成员")
@RestController
@RequestMapping("/ctop/projectMember")
public class ProjectMemberController {
    @Autowired
    private IProjectMemberService projectMemberService;
    @Resource
    private ProjectMemberMapper projectMemberMapper;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IAdvertiserService advertiserService;
    @Autowired
    private IUserAllocationService userAllocationService;


    /**
     * 查看项目成员
     *
     * @param projectId
     * @return
     */
    @GetMapping(value = "/getMemberList")
    public Map<String, Object> getMemberList(String projectId) {
        Map<String, Object> map = new HashMap<>();
        try {
            QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("project_id", projectId);
            queryWrapper.orderByDesc("create_time");
            List<ProjectMember> projectMemberList = projectMemberMapper.selectList(queryWrapper);
            map.put("code", 0);
            map.put("success", true);
            map.put("result", projectMemberList);
        } catch (Exception e) {
            map.put("success", false);
            map.put("code", -1);
        }

        return map;
    }


    /**
     * 我参与项目
     * @param userId
     * @return
     */
    @Autowired
    private IProductService productService;

    @GetMapping(value = "/participateList")
    public Map<String, Object> participateList(String userId) {
        Map<String, Object> map = new HashMap<>();
        try {
            QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            if (!"admin".equals(roleCode) && !"sale".contains(roleCode) && !"meidaManager".equals(roleCode)) {
                queryWrapper.eq("user_id", userId);
            }
            queryWrapper.groupBy("project_id");
            queryWrapper.orderByDesc("create_time");
            List<ProjectMember> projectMembers = projectMemberMapper.selectList(queryWrapper);
            List<ProjectMember> projectMemberList = new ArrayList<>();
            if (!Check.isNull(projectMembers)) {
                for (ProjectMember projectMember : projectMembers) {
                    if (Check.isNull(projectMember)) {
                        continue;
                    }
                    Project project = projectService.getById(projectMember.getProjectId());
                    if (!Check.isNull(project)) {
                        SysUser responsible = sysUserService.getById(project.getResponsibleId());

                        if (!Check.isNull(responsible)) {
                            projectMember.setResponsibleName(responsible.getRealname());
                        }

                        SysUser designResponsible = sysUserService.getById(project.getDesignResponsibleId());
                        if (!Check.isNull(designResponsible)) {
                            projectMember.setDesignResponsibleName(designResponsible.getRealname());
                        }

                        projectMember.setProjectName(project.getProjectName());
                        Product product = productService.getById(project.getProductId());
                        if (!Check.isNull(product)) {
                            projectMember.setProductId(product.getId());
                            projectMember.setProductName(product.getProductName());
                        }
                        Advertiser advertiser = advertiserService.getById(project.getAdvertiserId());
                        if (!Check.isNull(advertiser)) {
                            projectMember.setAdvertiserName(advertiser.getName());
                        }
                        projectMember.setAdvertiserId(project.getAdvertiserId());
                        projectMember.setMediaId(project.getMediaId());
                        projectMember.setMaxBid(project.getMaxBid());
                        projectMemberList.add(projectMember);
                    }
                }
            }
            map.put("code", 0);
            map.put("success", true);
            map.put("result", projectMemberList);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("code", -1);
        }
        return map;
    }

    /**
     * 获取项目以及账户信息
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/getProductProjectAndAccountList")
    public Result<List<JSONObject>> getProductProjectAndAccountList(@RequestBody JSONObject requestJson) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            String userId = requestJson.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("请选择userId");
            }
            List<Integer> mediaIds = new ArrayList<>();
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            //角色为 管理员 || 销售 || 媒介 查询全部
            List<String> userIds = new ArrayList<>();
            if ("CompanyManager".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("bytedanceDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("kuaishouDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else  if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
                userIds = null;
            }else {
                userIds.add(userId);
            }
            //查询项目信息以及广告主
            List<JSONObject> projectList = projectMemberService.getProjectByUserIdAndMediaIds(userIds, mediaIds);
            List<JSONObject> haveList = new ArrayList<>();
            List<JSONObject> list = new ArrayList<>();
            if (!Check.isNull(projectList)) {
                list = projectService.queryProductInfo(projectList);
                if (Check.isNull(list)) {
                    result.setSuccess(false);
                    result.setMessage("该用户没有可用的产品");
                    return result;
                }
                //项目id 查询账户人员信息
                Map<Long, List<JSONObject>> accountMap = userAllocationService.getAccountListByProjectList(projectList);
                for (int i = 0; i < projectList.size(); i++) {
                    JSONObject project = projectList.get(i);
                    if (!Check.isNull(project)) {
                        List<JSONObject> accountList = accountMap.get(project.getLong("projectId"));
                        if (!Check.isNull(accountList)) {
                            project.put("accountList", accountList);
                            haveList.add(project);
                        }
                    }
                }

                for (JSONObject object : list) {
                    List<JSONObject> proList = new ArrayList<>();
                    for (JSONObject have : haveList) {
                        if (Check.isNull(have)) {
                            continue;
                        }
                        if (Check.isNull(have.getLong("productId"))) {
                            continue;
                        }
                        if (object.getLong("productId") - have.getLong("productId") == 0) {
                            proList.add(have);
                        }
                    }
                    object.put("projectList", proList);
                }
            }
            result.setSuccess(true);
            result.setResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 获取项目以及账户信息
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/getProductProjectList")
    public Result<List<JSONObject>> getProductProjectList(@RequestBody JSONObject requestJson) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            String userId = requestJson.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("请选择userId");
            }
            List<Integer> mediaIds = new ArrayList<>();
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            //角色为 管理员 || 销售 || 媒介 查询全部
            List<String> userIds = new ArrayList<>();
            if ("CompanyManager".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("bytedanceDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("kuaishouDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("admin".equals(roleCode) || "sale".contains(roleCode) || "meidaManager".equals(roleCode)) {
                userIds = null;
            }else {
                userIds.add(userId);
            }
            //查询项目信息以及广告主
            List<JSONObject> projectList = projectMemberService.getProjectByUserIdAndMediaIds(userIds, mediaIds);
            List<JSONObject> list = new ArrayList<>();
            if (!Check.isNull(projectList)) {
                list = projectService.queryProductInfo(projectList);
                if (Check.isNull(list)) {
                    result.setSuccess(false);
                    result.setMessage("该用户没有可用的产品");
                    return result;
                }
                for (JSONObject object : list) {
                    List<JSONObject> proList = new ArrayList<>();
                    for (JSONObject have : projectList) {
                        if (Check.isNull(have)) {
                            continue;
                        }
                        if (Check.isNull(have.getLong("productId"))) {
                            continue;
                        }
                        if (object.getLong("productId") - have.getLong("productId") == 0) {
                            proList.add(have);
                        }
                    }
                    object.put("projectList", proList);
                }
            }
            result.setSuccess(true);
            result.setResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 获取项目以及账户信息
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/participateListByMediaId")
    public Result<List<JSONObject>> participateListByMediaId(@RequestBody JSONObject requestJson) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            String userId = requestJson.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("请选择userId");
            }
            List<Integer> mediaIds = new ArrayList<>();
            String type = requestJson.getString("type");
            if (!Check.isNull(type)) {
                if ("kuaishou".equals(type)) {
                    mediaIds.add(2);
                    mediaIds.add(4);
                } else if ("bytedance".equals(type)) {
                    mediaIds.add(1);
                    mediaIds.add(3);
                }
            }
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            //角色为 管理员 || 销售 || 媒介 查询全部
            List<String> userIds = new ArrayList<>();
            if ("CompanyManager".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("bytedanceDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("kuaishouDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
                userIds = null;
            }else{
                userIds.add(userId);
            }

            //查询项目信息以及广告主
            List<JSONObject> projectList = projectMemberService.getProjectByUserIdAndMediaIds(userIds, mediaIds);
            List<JSONObject> haveList = new ArrayList<>();
            if (!Check.isNull(projectList)) {
                //项目id 查询账户人员信息
                Map<Long, List<JSONObject>> accountMap = userAllocationService.getAccountListByProjectList(projectList);
                for (int i = 0; i < projectList.size(); i++) {
                    JSONObject project = projectList.get(i);
                    if (!Check.isNull(project)) {
                        List<JSONObject> accountList = accountMap.get(project.getLong("projectId"));
                        if (!Check.isNull(accountList)) {
                            project.put("accountList", accountList);
                            haveList.add(project);
                        }
                    }
                }
            }
            result.setSuccess(true);
            result.setResult(haveList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 获取项目以及账户信息
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/participateListByMediaIdV2")
    public Result<List<JSONObject>> participateListByMediaIdV2(@RequestBody JSONObject requestJson) {
        Result<List<JSONObject>> result = new Result<>();
        try {
            String userId = requestJson.getString("userId");
            if (Check.isNull(userId)) {
                throw new Exception("请选择userId");
            }
            List<Integer> mediaIds = new ArrayList<>();
            String type = requestJson.getString("type");
            if (!Check.isNull(type)) {
                if ("kuaishou".equals(type)) {
                    mediaIds.add(2);
                    mediaIds.add(4);
                } else if ("bytedance".equals(type)) {
                    mediaIds.add(1);
                    mediaIds.add(3);
                }
            }
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            //角色为 管理员 || 销售 || 媒介 查询全部
            List<String> userIds = new ArrayList<>();
            if ("CompanyManager".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("bytedanceDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("kuaishouDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
                userIds = null;
            }else {
                userIds.add(userId);
            }
            //查询项目信息以及广告主
            List<JSONObject> projectList = projectMemberService.getProjectByUserIdAndMediaIds(userIds, mediaIds);
            List<JSONObject> haveList = new ArrayList<>();
            if (!Check.isNull(projectList)) {
                //项目id 查询账户人员信息
                Map<Long, List<JSONObject>> accountMap = userAllocationService.getAccountListByProjectListV2(projectList);
                for (int i = 0; i < projectList.size(); i++) {
                    JSONObject project = projectList.get(i);
                    if (!Check.isNull(project)) {
                        List<JSONObject> accountList = accountMap.get(project.getLong("projectId"));
                        if (!Check.isNull(accountList)) {
                            project.put("accountList", accountList);
                            haveList.add(project);
                        }
                    }
                }
            }
            result.setSuccess(true);
            result.setResult(haveList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    @GetMapping("/projectList")
    public Map<String, Object> projectList(String userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            if ("admin".equals(roleCode) || "sale".contains(roleCode) || "meidaManager".equals(roleCode)) {
                List<Project> projects = projectService.list();
                result.put("data", projects);
                ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
                return result;
            }
            List<Project> projects = projectMemberService.selectListByUserId(userId);
            result.put("data", projects);
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
    }

    @GetMapping(value = "/participateListV2")
    public Result<IPage<ProjectMember>> participateListV2(ProjectMember projectMember,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        Result<IPage<ProjectMember>> result = new Result<>();

        String userId = projectMember.getUserId();
        if (Check.isNull(userId)) {
            result.setSuccess(false);
            result.setMessage("未获取到用户信息");
            return result;
        }
        String projectName = projectMember.getProjectName();
        Long productId = projectMember.getProductId();
        projectMember.setUserId(null);
        projectMember.setProjectName(null);
        projectMember.setProductId(null);
        QueryWrapper<ProjectMember> queryWrapper = QueryGenerator.initQueryWrapper(projectMember, req.getParameterMap());
        String roleCode = sysRoleService.getRoleCodeByUserId(userId);
        List<String> userIds = null;
        if ("CompanyManager".equals(roleCode)) {
            userIds = roleService.getCompanyUsers(roleCode, userId);
        } else if ("bytedanceDirector".equals(roleCode)) {
            userIds = roleService.getCompanyUsers(roleCode, userId);
        } else if ("kuaishouDirector".equals(roleCode)) {
            userIds = roleService.getCompanyUsers(roleCode, userId);
        } else if (!"admin".equals(roleCode) && !roleCode.contains("sale") && !"meidaManager".equals(roleCode)) {
            queryWrapper.eq("user_id", userId);
        }
        if (!Check.isNull(userIds)) {
            queryWrapper.in("user_id", userIds);
        }

        if (!Check.isNull(projectName)) {
            queryWrapper.like("project_name", projectName);
        }
        if (!Check.isNull(productId)) {
            List<Long> projectIds = projectService.getProjectIdsByProductId(productId);
            if (Check.isNull(projectIds)) {
                result.setSuccess(false);
                result.setMessage("该产品下暂无关联项目");
                return result;
            }
            queryWrapper.in("project_id", projectIds);
        }
        queryWrapper.groupBy("project_id");
        queryWrapper.orderByDesc("create_time");
        Page<ProjectMember> page = new Page<>(pageNo, pageSize);
        IPage<ProjectMember> pageList = projectMemberService.page(page, queryWrapper);
        List<ProjectMember> projectMembers = pageList.getRecords();
        projectMembers = projectMemberService.getMapsByProjectList(projectMembers);
        pageList.setRecords(projectMembers);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    @GetMapping(value = "/participateListV3")
    public Result participateListV3(ProjectMember projectMember,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {

        Result<IPage<ProjectMember>> result = this.participateListV2(projectMember, 1, 10000, req);
        List<ProjectMember> resultList = new ArrayList<>();
        if (result.isSuccess()) {
            List<ProjectMember> listProject = result.getResult().getRecords();
            if (!Check.isNull(listProject)) {
                Map<String, List<ProjectMember>> groupByMedia = listProject.stream().filter(p -> (!Check.isNull(p.getMediaId()))).collect(Collectors.groupingBy(ProjectMember::getMediaId));
                resultList = groupByMedia.get(projectMember.getMediaId());
                if (!Check.isNull(resultList)) {
                    resultList.stream().filter(p -> (!Check.isNull(p.getAdvertiserName()))).collect(Collectors.toList());
                    resultList = resultList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ProjectMember::getAdvertiserId))), ArrayList::new));
                }
            }
        }
        return Result.successMsg("成功。", resultList);
    }


    /**
     * 分页列表查询
     *
     * @param projectMember
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<ProjectMember>> queryPageList(ProjectMember projectMember,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        Result<IPage<ProjectMember>> result = new Result<>();
        QueryWrapper<ProjectMember> queryWrapper = QueryGenerator.initQueryWrapper(projectMember, req.getParameterMap());
        Page<ProjectMember> page = new Page<>(pageNo, pageSize);
        IPage<ProjectMember> pageList = projectMemberService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 批量添加
     *
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/batchAdd")
    public Result<ProjectMember> batchAdd(@RequestBody JSONObject jsonObject) {
        Result<ProjectMember> result = new Result<>();
        try {
            if (Check.isNull(jsonObject)) {
                throw new Exception("入参不能为空");
            }
            Long projectId = jsonObject.getLong("projectId");
            if (Check.isNull(projectId)) {
                throw new Exception("请选择项目");
            }
            Project project = projectService.getById(projectId);
            if (Check.isNull(project)) {
                throw new Exception("项目不存在");
            }
            JSONArray memberArr = jsonObject.getJSONArray("memberArr");
            if (Check.isNull(memberArr)) {
                throw new Exception("请选择项目成员");
            }
            for (int i = 0; i < memberArr.size(); i++) {
                String userId = memberArr.getString(i);
                if (!Check.isNull(userId)) {
                    QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("user_id", userId);
                    queryWrapper.eq("project_id", projectId);
                    ProjectMember selectMember = projectMemberService.getOne(queryWrapper);
                    if (!Check.isNull(selectMember)) {
                        continue;
                    }
                    ProjectMember member = new ProjectMember();
                    String roleCode = sysRoleService.getRoleCodeByUserId(userId);
                    if (!Check.isNull(roleCode)) {
                        member.setRoleCode(roleCode);
                    }
                    member.setProjectId(projectId);
                    member.setProjectName(project.getProjectName());
                    member.setUserId(userId);
                    SysUser sysUser = sysUserService.getById(userId);
                    if (!Check.isNull(sysUser)) {
                        member.setUserName(sysUser.getRealname());
                    }

                    projectMemberService.save(member);
                }
            }
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 添加
     *
     * @param projectMember
     * @return
     */
   /* @PostMapping(value = "/add")
    public Result<ProjectMember> add(@RequestBody ProjectMember projectMember) {
        Result<ProjectMember> result = new Result<>();
        try {
            projectMemberService.save(projectMember);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }*/

    /**
     * 编辑
     *
     * @param projectMember
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<ProjectMember> edit(@RequestBody ProjectMember projectMember) {
        Result<ProjectMember> result = new Result<>();
        ProjectMember projectMemberEntity = projectMemberService.getById(projectMember.getId());
        if (projectMemberEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = projectMemberService.updateById(projectMember);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<Object> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            projectMemberService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<ProjectMember> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ProjectMember> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.projectMemberService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<ProjectMember> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ProjectMember> result = new Result<>();
        ProjectMember projectMember = projectMemberService.getById(id);
        if (projectMember == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(projectMember);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 我参与项目
     *
     * @return
     */
    @GetMapping(value = "/bytedanceProjectParticipateInList")
    public Result<List<ProjectMember>> bytedanceProjectParticipateInList(@RequestParam(required = false) String userId) {
        Result<List<ProjectMember>> result = new Result<>();
        List<Integer> mediaIds = new ArrayList<>();
        mediaIds.add(1);
        mediaIds.add(2);
        mediaIds.add(3);
        mediaIds.add(4);
        List<ProjectMember> projectMemberList = projectMemberService.getProjects(mediaIds, userId);
        if (projectMemberList == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(projectMemberList);
            result.setSuccess(true);
        }
        return result;

    }

    /**
     * 查询当前账户下的快手头条传不同的mediaType
     *
     * @return
     */
    @GetMapping("/getProjectAccountByUserId")
    public Result<List<Map<String, Object>>> getProjectAccountBy(String mediaType, String userId) {
        Result<List<Map<String, Object>>> resultBody = new Result<>();
        try {
            List<Integer> mediaIds = new ArrayList<>();
            if ("1".equals(mediaType)) {
                mediaIds.add(1);
                mediaIds.add(3);
            } else if ("2".equals(mediaType)) {
                mediaIds.add(2);
                mediaIds.add(4);
            } else if ("16".equals(mediaType) || "tencent".equals(mediaType)) {
                mediaIds.add(16);
            }

            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            List<String> userIds = new ArrayList<>();
            if ("CompanyManager".equals(roleCode) || "bytedanceDirector".equals(roleCode) || "kuaishouDirector".equals(roleCode)) {
                userIds = roleService.getCompanyUsers(roleCode, userId);
            } else if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
                userIds = null;
            } else {
                userIds.add(userId);
            }

            List<Map<String, Object>> result = new ArrayList<>();
            List<JSONObject> projectList = projectMemberService.getProjectByUserIdAndMediaIds(userIds, mediaIds);
            if (!Check.isNull(projectList)) {
                Map<Long, List<JSONObject>> accountMap = userAllocationService.getAccountListByProjectList(projectList);
                for (JSONObject project : projectList) {
                    if (Check.isNull(project)) {
                        continue;
                    }
                    List<JSONObject> accountList = accountMap.get(project.getLong("projectId"));
                    if (Check.isNull(accountList)) {
                        continue;
                    }
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("project", project);
                    temp.put("account", accountList);
                    result.add(temp);
                }
            }
            resultBody.setSuccess(true);
            resultBody.setResult(result);
        } catch (Exception e) {
            log.error("getProjectAccountByUserId error, userId={}, mediaType={}", userId, mediaType, e);
            resultBody.setSuccess(false);
            resultBody.setMessage("查询失败");
        }
        return resultBody;
    }

    /**
     * 查询当前账户下的快手头条传不同的mediaType
     *
     * @return
     */
    @GetMapping("/getAllProjectAccount")
    public Result<List<Map<String, Object>>> getAllProjectAccount(String mediaType) {
        Result<List<Map<String, Object>>> resultBody = new Result<>();
        try {
            List<Map<String, Object>> result = projectMemberService.getAllProjectAccount(mediaType);
            resultBody.setSuccess(true);
            resultBody.setResult(result);
        } catch (Exception e) {
            resultBody.setSuccess(false);
            resultBody.success("查询失败");
        }
        return resultBody;
    }


    /**
     * 销售的项目
     *
     * @return
     */
    @PostMapping(value = "/getSaleOwnProjects")
    public Result<List<ProjectMember>> getSaleOwnProjects(@RequestBody JSONObject data) {
        Result<List<ProjectMember>> result = new Result<>();

        JSONArray ids = data.getJSONArray("mediaIds");
        List<Integer> mediaIds = new ArrayList<>();
        if (null != ids && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                mediaIds.add(ids.getIntValue(i));
            }
        }
        List<ProjectMember> projectMemberList = projectMemberService.getSaleOwnProjects(mediaIds);
        if (projectMemberList == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(projectMemberList);
            result.setSuccess(true);
        }
        return result;

    }

    /**
     * 自己所在的项目
     *
     * @return
     */
    @PostMapping("/getOwnProjects")
    public Result<List<ProjectMember>> getOwnProjects(@RequestBody JSONObject data) {
        Result<List<ProjectMember>> result = new Result<>();
        JSONArray ids = data.getJSONArray("mediaIds");
        List<Integer> mediaIds = new ArrayList<>();
        if (null != ids && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                mediaIds.add(ids.getIntValue(i));
            }
        }
        List<ProjectMember> projectMemberList = projectMemberService.getOwnProjects(mediaIds);
        if (projectMemberList == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(projectMemberList);
            result.setSuccess(true);
        }
        return result;
    }
}
