package com.ruixuan.jinniu.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.PageUtils;
import com.ruixuan.common.utils.Result;
import com.ruixuan.jinniu.entity.KuaishouAccount;
import com.ruixuan.jinniu.entity.KuaishouProject;
import com.ruixuan.jinniu.mapper.KuaishouProjectMapper;
import com.ruixuan.jinniu.service.IKuaishouAccountService;
import com.ruixuan.jinniu.service.IKuaishouProjectMemberService;
import com.ruixuan.jinniu.service.IKuaishouProjectService;
import com.ruixuan.system.service.ISysDeptService;
import com.ruixuan.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 项目信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-14
 */
@Service
public class KuaishouProjectServiceImpl implements IKuaishouProjectService {
    @Autowired
    private KuaishouProjectMapper projectMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IKuaishouAccountService kuaishouAccountService;
    @Autowired
    private IKuaishouProjectMemberService kuaishouProjectMemberService;

    /**
     * 查询项目信息
     *
     * @param id 项目信息主键
     * @return 项目信息
     */
    @Override
    public KuaishouProject selectKuaishouProjectById(Long id) {
        return projectMapper.selectKuaishouProjectById(id);
    }

    /**
     * 查询项目信息列表
     * 权限：admin 查所有
     */
    @Override
    public List<KuaishouProject> selectKuaishouProjectList(KuaishouProject kuaishouProject) {
        Long userId = kuaishouProject.getUserId();
        String roleKey = sysUserService.getRoleKeyByUserId(userId);
        List<Long> userList;
        if ("admin".equals(roleKey) || "directorOperations".equals(roleKey)) {
            //查看所有
            userList = null;
        } else if ("electricPin".equals(roleKey) || "facePin".equals(roleKey)) {
            //电销 面销
            kuaishouProject.setSaleIdList(Arrays.asList(userId));
        } else if ("eBayAmazon".equals(roleKey) || "salesDirector".equals(roleKey)) {
            //销售组长、销售总监
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
            kuaishouProject.setSaleIdList(userList);
        } else if ("operations".equals(roleKey) || "operator".equals(roleKey)) {
            //运营 运营专员
            kuaishouProject.setOperatorIdList(Arrays.asList(userId));
        } else if ("operationsManager".equals(roleKey)) {
            //运营经理、运营总监
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
            kuaishouProject.setOperatorIdList(userList);
        } else if ("design".equals(roleKey)) {
            //设计
            kuaishouProject.setDesignIdList(Arrays.asList(userId));
        } else if ("designLeader".equals(roleKey)) {
            //设计负责人
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
            kuaishouProject.setDesignIdList(userList);
        } else {
            //非销售、运营、设计角色，无权查看账户
            return Collections.emptyList();
        }
        PageUtils.startPage();
        return projectMapper.selectKuaishouProjectList(kuaishouProject);
    }

    /**
     * 新增项目信息
     *
     * @param kuaishouProject 项目信息
     * @return 结果
     */
    @Override
    public int insertKuaishouProject(KuaishouProject kuaishouProject) {
        int i = projectMapper.insertKuaishouProject(kuaishouProject);
        JSONObject mem = new JSONObject();
        mem.put("projectId", kuaishouProject.getId());
        mem.put("projectName", kuaishouProject.getProjectName());
        Set<Long> ses = new HashSet<>();
        if (Check.isNotNull(kuaishouProject.getSaleId())) {
            ses.add(kuaishouProject.getSaleId());
        }
        if (Check.isNotNull(kuaishouProject.getOperatorId())) {
            ses.add(kuaishouProject.getOperatorId());
        }
        if (Check.isNotNull(kuaishouProject.getDesignResponsibleId())) {
            ses.add(kuaishouProject.getDesignResponsibleId());
        }
        mem.put("userIds", ses);
        kuaishouProjectMemberService.addProjectUsers(mem);
        return i;
    }

    /**
     * 修改项目信息
     *
     * @param kuaishouProject 项目信息
     * @return 结果
     */
    @Override
    public int updateKuaishouProject(KuaishouProject kuaishouProject) {
        int i = 0;
        KuaishouProject project = projectMapper.selectKuaishouProjectById(kuaishouProject.getId());
        if (Check.isNotNull(project)) {
            i = projectMapper.updateKuaishouProject(kuaishouProject);
            if (i > 0 && Check.isNotNull(kuaishouProject.getProjectName()) && !project.getProjectName().equals(kuaishouProject.getProjectName())) {
                //修改项目名称的时候，同步到关联的账户中；
                List<KuaishouAccount> accounts = kuaishouAccountService.getAccountByProjectId(kuaishouProject.getId());
                for (KuaishouAccount account : accounts) {
                    account.setProjectName(kuaishouProject.getProjectName());
                    kuaishouAccountService.updateKuaishouAccount(account);
                }
            }
        }
        return i;
    }

    /**
     * 删除项目信息信息
     *
     * @param id 项目信息主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouProjectById(Long id) {
        projectMapper.deleteKuaishouProjectById(id);
        return kuaishouAccountService.deleteKuaishouAccountByProjectId(id);

    }

    @Override
    public Result<Object> getOcpxActionType() {
        List<JSONObject> list = projectMapper.getOcpxActionType();
        return Result.success(list);
    }

    @Override
    public List<KuaishouProject> getMyProjects(KuaishouProject kuaishouProject) {
        String roleKey = sysUserService.getRoleKeyByUserId(kuaishouProject.getUserId());
        if ("admin".equals(roleKey) || "directorOperations".equals(roleKey)) {

        } else if ("operationsManager".equals(roleKey)) {
            //运营经理 可以看自己部门所有人的（自己和下属的）
            Long deptId = deptService.getDeptIdByUserId(kuaishouProject.getUserId());
            kuaishouProject.setOperatorIdList(deptService.getDeptUserListByDeptId(deptId));
        } else {
            kuaishouProject.setOperatorIdList(Arrays.asList(kuaishouProject.getUserId()));
        }
        PageUtils.startPage();
        return projectMapper.getMyProjects(kuaishouProject);
    }

    @Override
    public Result<Object> getProjectAndAccountByUserId(Long userId, String mediaCode) {
        String roleKey = sysUserService.getRoleKeyByUserId(userId);
        List<Long> userList;
        if ("admin".equals(roleKey) || "directorOperations".equals(roleKey)) {
            userList = null;
            if ("admin".equals(roleKey)) {
                mediaCode = null;
            }
        } else if ("operationsManager".equals(roleKey)) {
            //运营经理 可以看自己部门所有人的（自己和下属的）
            Long deptId = deptService.getDeptIdByUserId(userId);
            userList = deptService.getDeptUserListByDeptId(deptId);
        } else {
            userList = Arrays.asList(userId);
        }
        //查询项目
        List<JSONObject> projectList = projectMapper.getProjectsByMedia(userList, mediaCode);
        for (JSONObject object : projectList) {
            Long projectId = object.getLong("projectId");
            object.put("accountList", kuaishouAccountService.getAccountNameByProjectId(projectId));
        }
        return Result.success(projectList);
    }

}