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

import cn.com.ctop.alarm.modules.entity.RuleAccountTemplate;
import cn.com.ctop.alarm.modules.mapper.RuleAccountTemplateMapper;
import cn.com.ctop.common.module.entity.SysLog;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.SysLogMapper;
import cn.com.ctop.common.module.mapper.SysRoleMapper;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
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.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.ctop.entity.ProjectMember;
import org.jeecg.modules.ctop.mapper.ProjectMemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 用户分配
 * @Author: jeecg-boot
 * @Date: 2019-08-08
 * @Version: V1.0
 */
@Service
public class UserAllocationServiceImpl extends ServiceImpl<UserAllocationMapper, UserAllocation> implements IUserAllocationService {

    @Autowired
    UserAllocationMapper userAllocationMapper;

    @Override
    public UserAllocation getByAccountId(Long accountId) {
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId + "").orderByDesc("id").last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public List<UserAllocation> getByParams(Long projectId, String systemType, Integer accountStatus) {
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        if (null != projectId && projectId != 0) {
            queryWrapper.eq("project_id", projectId);
        }
        if (null != systemType && !"".equals(systemType.trim())) {
            queryWrapper.eq("system_type", systemType);
        }
        if (null != accountStatus) {
            queryWrapper.eq("account_status", accountStatus);
        }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

    @Override
    public Map<String, Object> getPangolinAccountListByParams(String userId, JSONObject data) {
        Map<String, Object> result = new HashMap<>();
        Long projectId = data.getLong("project_id");
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_id", CtopAdConstant.PLATFORM_TYPE_PANGOLIN);
        if (null != userId && !"".equals(userId.trim())) {
            queryWrapper.eq("user_id", userId);
        }
        if (null != projectId && projectId != 0) {
            queryWrapper.eq("project_id", projectId);
        }
        List<UserAllocation> allocations = this.list(queryWrapper);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        result.put("data", allocations);
        return result;
    }

    @Override
    public Map<String, Object> getPangolinProjectListByParams(String userId) {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("distinct project_id,project_name");
        queryWrapper.eq("media_id", CtopAdConstant.PLATFORM_TYPE_PANGOLIN);
        if (null != userId && !"".equals(userId.trim())) {
            queryWrapper.eq("user_id", userId);
        }
        List<UserAllocation> allocations = this.list(queryWrapper);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        result.put("data", allocations);
        return result;
    }

    @Override
    public List<UserAllocation> getByMediaId(String mediaId) {
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        if ("".equals(mediaId)) {
            queryWrapper.eq("media_id", mediaId);
        }
        return this.list(queryWrapper);
    }

    @Override
    public List<UserAllocation> listByMediaId(String mediaId, int accountStatus) {
        return userAllocationMapper.listByMediaId(mediaId, accountStatus);
    }

    @Override
    public String getAdvertiserIdByAccountId(Long accountId) {
        return userAllocationMapper.queryAdvertiserId(accountId);
    }

    @Override
    public List<JSONObject> getAccountListByProject(Long projectId) {
        return userAllocationMapper.getAccountListByProject(projectId);
    }

    /**
     * 获取项目下的所有userId
     *
     * @param projectId
     * @return
     */
    @Override
    public List<JSONObject> getUserIdListByProjectId(Long projectId) {
        return userAllocationMapper.getUserIdListByProjectId(projectId);
    }

    @Override
    public List<JSONObject> getAccountIdListByUserId(String userId) {
        return userAllocationMapper.getAccountIdListByUserId(userId);
    }

    @Override
    public List<JSONObject> getAccountIdsByUserId(String userId) {
        List<JSONObject> result = new ArrayList<>();
        if ("e9ca23d68d884d4ebb19d07889727dae".equals(userId)) {
            result = userAllocationMapper.getAllAccountIdsByMediaId("2");
        } else {
            result = userAllocationMapper.getAccountIdsByUserId(userId);

        }
        return result;
    }

    @Override
    public List<UserAllocation> getUserAllocations(String mediaId, int switchType) {
        QueryWrapper<UserAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("media_id", mediaId);
        queryWrapper.eq("account_status", 0);
        queryWrapper.eq("monitoring_link", 0);
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public JSONObject getSwitchStatusByAccount(Long accountId) {
        return userAllocationMapper.getSwitchStatusByAccount(accountId);
    }

    @Override
    public List<Long> getAccountsByDeleteComment() {
        return userAllocationMapper.queryAccountsByDeleteComment();
    }

    @Override
    public List<UserAllocation> getAccountListByUserIdAndProductId(String userId, Long projectId, Long productId) {
        return userAllocationMapper.getAccountListByUserIdAndProductId(userId, projectId, productId);
    }

    @Override
    public Map<Long, List<JSONObject>> getAccountListByProjectList(List<JSONObject> projectList) {
        Map<Long, List<JSONObject>> map = new HashMap<>();
        List list = new ArrayList();
        for (int i = 0; i < projectList.size(); i++) {
            JSONObject jsonObject = projectList.get(i);
            if (!Check.isNull(jsonObject)) {
                list.add(jsonObject.getLong("projectId"));
                map.put(jsonObject.getLong("projectId"), new ArrayList<>());
            }
        }
        List<JSONObject> jsonList = userAllocationMapper.getAccountListByProjectList(list);
        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject jsonObject = jsonList.get(i);
            if (!Check.isNull(jsonObject)) {
                Long projectId = jsonObject.getLong("projectId");
                List<JSONObject> jsonObjects = map.get(projectId);
                jsonObjects.add(jsonObject);
            }
        }
        return map;
    }

    @Override
    public Map<Long, List<JSONObject>> getAccountListByProjectListV2(List<JSONObject> projectList) {
        Map<Long, List<JSONObject>> map = new HashMap<>();
        List list = new ArrayList();
        for (int i = 0; i < projectList.size(); i++) {
            JSONObject jsonObject = projectList.get(i);
            if (!Check.isNull(jsonObject)) {
                list.add(jsonObject.getLong("projectId"));
                map.put(jsonObject.getLong("projectId"), new ArrayList<>());
            }
        }
        List<JSONObject> jsonList = userAllocationMapper.getAccountListByProjectListV2(list);
        for (int i = 0; i < jsonList.size(); i++) {
            JSONObject jsonObject = jsonList.get(i);
            if (!Check.isNull(jsonObject)) {
                Long projectId = jsonObject.getLong("projectId");
                List<JSONObject> jsonObjects = map.get(projectId);
                jsonObjects.add(jsonObject);
            }
        }
        return map;
    }

    @Override
    public List<JSONObject> getAccountListByProjectAndUserId(Long projectId, String userId) {
        return userAllocationMapper.getAccountListByProjectAndUserId(projectId, userId);
    }

    @Override
    public List<JSONObject> getUserIdListByProductId(Long productId, String userId) {
        return userAllocationMapper.getUserIdListByProductId(productId, userId);
    }

    @Override
    public List<Long> getValidProjectIds(Integer mediaId) {
        return userAllocationMapper.getValidProjectIds(mediaId);
    }

    @Override
    public List<JSONObject> getByAccountIds(JSONArray accountIds) {
        return userAllocationMapper.getByAccountIds(accountIds);
    }

    @Override
    public List<Long> getKuaiShouUserIdListByProjectId(Long projectId) {
        return userAllocationMapper.getKuaiShouUserIdListByProjectId(projectId);
    }

    @Override
    public List<JSONObject> selectAccountsByKuaishouUserId(Long userId) {
        return userAllocationMapper.selectAccountsByKuaishouUserId(userId);
    }

    @Override
    public boolean updateProjectStrategyStatus(Long accountId, Integer projectStrategy) {
        int num = userAllocationMapper.updateProjectStrategyStatus(accountId, projectStrategy);
        return num > 0;
    }

    @Override
    public List<Long> queryAutomaticAccounts(Long projectId) {
        return userAllocationMapper.queryAutomaticAccounts(projectId);
    }

    @Autowired
    RuleAccountTemplateMapper ruleAccountTemplateMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    ProjectMemberMapper projectMemberMapper;

    @Autowired
    ProjectMemberMapper memberMapper;

    @Autowired
    SysLogMapper sysLogMapper;

    @Override
    public Result<UserAllocation> editUserAlloCation(UserAllocation userAllocation) {
        Result<UserAllocation> result = new Result<>();
        UserAllocation userAllocationEntity = userAllocationMapper.selectById(userAllocation.getId());
        if (userAllocationEntity == null) {
            result.error500("未找到对应实体");
        } else {
            int ok = userAllocationMapper.updateById(userAllocation);
            Integer accountStatus = userAllocation.getAccountStatus();
            if (!Check.isNull(accountStatus)) {
                if (accountStatus == 1) {
                    QueryWrapper<RuleAccountTemplate> ruleAccountTemplateQueryWrapper = new QueryWrapper<>();
                    ruleAccountTemplateQueryWrapper.eq("account_id", userAllocationEntity.getAccountId());
                    RuleAccountTemplate updateRuleAccountTemplate = new RuleAccountTemplate();
                    updateRuleAccountTemplate.setTemplateStatus(1);
                    ruleAccountTemplateMapper.update(updateRuleAccountTemplate, ruleAccountTemplateQueryWrapper);
                }
            }

            UserAllocation update = userAllocationMapper.selectById(userAllocation.getId());
            QueryWrapper<ProjectMember> memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.eq("user_id", update.getUserId());
            memberQueryWrapper.eq("project_id", update.getProjectId());
            memberQueryWrapper.last("limit 1");
            ProjectMember member = memberMapper.selectOne(memberQueryWrapper);
            if (Check.isNull(member)) {
                ProjectMember addMember = new ProjectMember();
                addMember.setProjectId(userAllocationEntity.getProjectId());
                addMember.setUserId(userAllocationEntity.getUserId());
                addMember.setUserName(userAllocationEntity.getUserName());
                String roleCode = sysRoleMapper.getRoleCodeByUserId(userAllocationEntity.getUserId());
                if (!Check.isNull(roleCode)) {
                    addMember.setRoleCode(roleCode);
                }
                projectMemberMapper.insert(addMember);
            }

            if (ok == 1) {
                result.success("修改成功!");
            }

            //同步 财务结算 状态
            Map<String, Object> cwjs = userAllocationMapper.getCwjsSettlementByAccountId(String.valueOf(userAllocationEntity.getAccountId()));
            if (!Check.isNull(cwjs)) {
                userAllocationMapper.updCwjsSettlementStatus(cwjs.get("id").toString(), accountStatus);
            }
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            SysLog sysLog = new SysLog();
            sysLog.setLogType(2);
            sysLog.setLogContent(String.valueOf(accountStatus));
            sysLog.setRequestParam(userAllocationEntity.getAccountId().toString());
            sysLog.setOperateType(10001);
            sysLog.setUserid(user.getId());
            sysLog.setCreateBy(user.getRealname());
            sysLog.setCreateTime(new Date());
            sysLogMapper.insert(sysLog);

        }

        return result;
    }

    @Override
    public List<Long> getAccountListByProjectId(Long projectId) {
        return userAllocationMapper.getAccountListByProjectId(projectId);
    }


}
