package com.mmc.iuav.user.service.impl;

import com.mmc.iuav.page.PageResult;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.client.PmsClient;
import com.mmc.iuav.user.dao.*;
import com.mmc.iuav.user.entity.*;
import com.mmc.iuav.user.model.dto.LoginSuccessDTO;
import com.mmc.iuav.user.model.qo.CompanyInfoQO;
import com.mmc.iuav.user.model.vo.AliasAndImgVo;
import com.mmc.iuav.user.model.vo.CompanyInfoVO;
import com.mmc.iuav.user.model.vo.CompanyMemberVO;
import com.mmc.iuav.user.model.vo.UserAccountVO;
import com.mmc.iuav.user.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: zj
 * @Date: 2023/7/3 15:39
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private PmsClient pmsClient;

    @Autowired
    private BackUserAccountDao backUserAccountDao;

    @Autowired
    private UserServiceDao userServiceDao;

    @Autowired
    private CooperationDao cooperationDao;

    @Autowired
    private MessageDao messageDao;

    @Override
    public ResultBody addCompanyInfo(CompanyInfoVO companyInfo) {
        int count = companyDao.countCompanyNames(companyInfo.getId(), companyInfo.getCompanyName());
        if (count > 0) {
            return ResultBody.error(ResultEnum.COMPANY_NAME_EXIST_ERROR);
        }
        CompanyInfoDO companyInfoDO = new CompanyInfoDO(companyInfo);
        companyDao.addCompanyInfo(companyInfoDO);
        return ResultBody.success();
    }

    @Override
    public ResultBody removeCompanyInfo(Integer id, String token) {
        // 查询绑定账号数量是否大于0
        int backAccountCount = companyDao.countCompanyBackUser(id);
        if (backAccountCount > 0) {
            return ResultBody.error(ResultEnum.REMOVE_COMPANY_BINDING_ERROR);
        }
        // 查询绑定服务数量是否大于0
        Integer taskCount = pmsClient.countCompanyTasks(id, token);
        if (taskCount == null || taskCount > 0) {
            return ResultBody.error(ResultEnum.REMOVE_COMPANY_TASK_ERROR);
        }
        // 有绑定小程序用户则不能删除
        List<CompanyMemberDO> memberDOS = companyDao.listCompanyMembers(id);
        if (!CollectionUtils.isEmpty(memberDOS)) {
            return ResultBody.error(ResultEnum.REMOVE_COMPANY_BINDING_APP_ERROR);
        }
        companyDao.removeCompanyInfo(id);
        return ResultBody.success();
    }

    @Override
    public ResultBody updateCompanyInfo(CompanyInfoVO companyInfo) {
        int count = companyDao.countCompanyNames(companyInfo.getId(), companyInfo.getCompanyName());
        if (count > 0) {
            return ResultBody.error(ResultEnum.COMPANY_NAME_EXIST_ERROR);
        }
        CompanyInfoDO companyInfoDO = new CompanyInfoDO(companyInfo);
        companyDao.updateCompanyInfo(companyInfoDO);
        return ResultBody.success();
    }

    @Override
    public ResultBody<CompanyInfoVO> getCompanyInfoById(Integer id) {
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoById(id);
        //根据公司id查找到当前加盟公司的标签
        Integer companyTagId = companyDao.getCompanyTagId(id);
        if (companyInfoDO != null) {
            CompanyInfoVO companyInfoVO = companyInfoDO.buildCompanyInfoVO();
            // 设置手机号
            CompanyBackUserDO companyBackUserDO = companyDao.getCompanyBackUserByCompanyId(id);
            if (companyBackUserDO != null) {
                Integer backUserAccountId = companyBackUserDO.getBackUserAccountId();
                BackUserAccountDO backUserAccountDO = backUserAccountDao.getBackUserAccountDO(backUserAccountId);
                if (backUserAccountDO != null) {
                    companyInfoVO.setPhoneNum(backUserAccountDO.getPhoneNum());
                    companyInfoVO.setBackUserAccountId(backUserAccountId);
                    companyInfoVO.setBackUserId(backUserAccountId);
                }
            }
            companyInfoVO.setCooperationTagId(companyTagId);
            return ResultBody.success(companyInfoVO);
        }
        return ResultBody.success();
    }

    @Override
    public ResultBody<CompanyInfoVO> listCompanyPage(CompanyInfoQO param, LoginSuccessDTO loginSuccessDTO) {
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoByAppLoginUserId(loginSuccessDTO.getUserAccountId());
        if (companyInfoDO != null && !companyInfoDO.getCompanyType().equals(0)) {
            param.setCompanyInfoId(companyInfoDO.getId());
        }
        int count = companyDao.countListCompanyPage(param);
        if (count == 0) {
            return ResultBody.success(PageResult.buildPage(param.getPageNo(), param.getPageSize(), count));
        }
        Integer pageNo = param.getPageNo();
        param.buildCurrentPage();
        List<CompanyInfoDO> companyInfoDOS = companyDao.listCompanyPage(param);
        List<CompanyInfoVO> companyInfoVOList = companyInfoDOS.stream().map(CompanyInfoDO::buildCompanyInfoVO).collect(Collectors.toList());
        return ResultBody.success(PageResult.buildPage(pageNo, param.getPageSize(), count, companyInfoVOList));
    }

    @Override
    public CompanyInfoVO getCompanyInfoByBackUserAccountId(Integer backUserAccountId) {
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoByBackUserAccountId(backUserAccountId);
        if (companyInfoDO != null) {
            return companyInfoDO.buildCompanyInfoVO();
        }
        return null;
    }

    @Override
    public CompanyInfoVO getCompanyInfoByAppLoginUserId(Integer backUserAccountId) {
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoByAppLoginUserId(backUserAccountId);
        if (companyInfoDO != null) {
            CompanyInfoVO companyInfoVO = companyInfoDO.buildCompanyInfoVO();
            companyInfoVO.setBackUserId(backUserAccountId);
            return companyInfoVO;
        }
        return null;
    }

    @Override
    public void addCompanyBackUser(CompanyBackUserDO companyBackUserDO) {
        companyDao.addCompanyBackUser(companyBackUserDO);
    }

    @Override
    public void updateCompanyBackUser(CompanyBackUserDO companyBackUserDO) {
        companyDao.updateCompanyBackUser(companyBackUserDO);
    }

    @Override
    public List<CompanyInfoVO> listCompanyPageBack(CompanyInfoQO param) {
        Integer pageNo = param.getPageNo();
        param.buildCurrentPage();
        List<CompanyInfoDO> companyInfoDOS = companyDao.listCompanyPage(param);
        List<CompanyInfoVO> companyInfoVOList = companyInfoDOS.stream().map(CompanyInfoDO::buildCompanyInfoVO).collect(Collectors.toList());
        return companyInfoVOList;
    }

    @Override
    public List<CompanyInfoDO> listCompanyInfoByUID(List<Integer> backUserIds) {
        List<CompanyInfoDO> companyInfoDOList = companyDao.listCompanyInfoByUID(backUserIds);
        return companyInfoDOList;
    }

    @Override
    public ResultBody bindingCompanyMember(LoginSuccessDTO loginSuccessDTO, Integer userAccountId, Integer companyInfoId, Integer leader) {
        // 查看该成员是否已被绑定
        int count = companyDao.countBingingCompanyInfoByUID(userAccountId);
        if (count > 0) {
            return ResultBody.error(ResultEnum.REBINDING_COMPANY_ERROR);
        }
        CompanyMemberDO companyMemberDO = new CompanyMemberDO();
        companyMemberDO.setUserAccountId(userAccountId);
        companyMemberDO.setCompanyInfoId(companyInfoId);
        companyMemberDO.setLeader(leader);
        companyDao.addCompanyMember(companyMemberDO);
        return ResultBody.success();
    }

    @Override
    public CompanyInfoVO getAppCompanyInfoUId(Integer userAccountId) {
        CompanyInfoDO companyInfoDO = companyDao.getAppCompanyInfoUId(userAccountId);
        if (companyInfoDO != null) {
            return companyInfoDO.buildCompanyInfoVO();
        }
        return null;
    }

    @Override
    public CompanyBackUserDO getCompanyBackUserByCompanyId(Integer id) {
        CompanyBackUserDO companyBackUserDO = companyDao.getCompanyBackUserByCompanyId(id);
        return companyBackUserDO;
    }

    @Override
    public ResultBody unbindCompanyMember(LoginSuccessDTO userLoginInfoFromRedis, Integer userAccountId, Integer companyInfoId) {
        CompanyMemberDO companyMemberDO = companyDao.getCompanyMember(userAccountId, companyInfoId);
        if (companyMemberDO != null) {
            if (companyMemberDO.getLeader().equals(1)) {
                return ResultBody.error(ResultEnum.UNBIND_COMPANY_MEMBER_ERROR);
            }
        }
        companyDao.unbindCompanyMember(userAccountId, companyInfoId);
        return ResultBody.success();
    }

    @Override
    @Transactional
    public ResultBody transferLeader(LoginSuccessDTO loginSuccessDTO, Integer fromUserAccountId, Integer toUserAccountId, Integer companyInfoId) {
        CompanyMemberDO companyMemberDO = companyDao.getCompanyMember(fromUserAccountId, companyInfoId);
        if (companyMemberDO != null) {
            if (!companyMemberDO.getLeader().equals(1)) {
                return ResultBody.error(ResultEnum.TRANFER_COMPANY_MEMBER_LEADER_ERROR);
            }
        }
        companyDao.updateCompanyMember(fromUserAccountId, 0, companyInfoId);
        companyDao.updateCompanyMember(toUserAccountId, 1, companyInfoId);
        // 后台账号电话应该为现在管理员的电话
        UserAccountDO accountDO = userServiceDao.getUserAccountById(toUserAccountId);
        CompanyBackUserDO companyBackUserDO = companyDao.getCompanyBackUserByCompanyId(companyInfoId);
        if (accountDO != null && companyBackUserDO != null) {
            BackUserAccountDO backUserAccountDO = new BackUserAccountDO();
            backUserAccountDO.setId(companyBackUserDO.getBackUserAccountId());
            backUserAccountDO.setPhoneNum(accountDO.getPhoneNum());
            backUserAccountDao.updateBackUserAccount(backUserAccountDO);
        } else {
            return ResultBody.error(ResultEnum.LOGIN_ACCOUNT_NOT_EXIT_ERROR);
        }
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoById(companyInfoId);
        if (companyInfoDO != null) {
            companyInfoDO.setPhoneNum(accountDO.getPhoneNum());
            companyDao.updateCompanyInfo(companyInfoDO);
        }
        //加盟入住的标签也要换绑定 user_tag , user_apply_tag
        UserApplyTagDO userApplyTagDO = cooperationDao.selectTageByUserId(fromUserAccountId);
        if(userApplyTagDO != null) {
            userApplyTagDO.setUserAccountId(toUserAccountId);
            cooperationDao.updateUserApplyTag(userApplyTagDO);
        }
        return ResultBody.success();
    }

    @Override
    public ResultBody listCompanyMembers(Integer companyInfoId, LoginSuccessDTO loginSuccessDTO, Integer pageNo, Integer pageSize) {
        int count = companyDao.countCompanyMembers(companyInfoId);
        if (count == 0) {
            return ResultBody.success(PageResult.buildPage(pageNo, pageSize, count));
        }
        Integer pageNoTemp = (pageNo - 1) * pageSize;
        List<UserAccountDO> userAccountDOS = companyDao.listCompanyMembersPage(companyInfoId, pageNoTemp, pageSize);
        List<UserAccountVO> userAccountVOS = userAccountDOS.stream().map(UserAccountDO::buildUserAccountVO).collect(Collectors.toList());
        return ResultBody.success(PageResult.buildPage(pageNo, pageSize, count, userAccountVOS));
    }

    @Override
    public ResultBody<CompanyInfoVO> getCompanyInfoByBUId(Integer backUserAccountId) {
        // 获取公司id
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoByBackUserAccountId(backUserAccountId);
        if (companyInfoDO != null) {
            companyInfoDO.setLicenseImg(null);
            return ResultBody.success(companyInfoDO.buildCompanyInfoVO());
        }
        return ResultBody.success();
    }

    @Override
    public Integer countCompanyBackUser(Integer id) {
        int countCompanyBackUser = companyDao.countCompanyBackUser(id);
        return countCompanyBackUser;
    }

    @Transactional
    @Override
    public void unbindingAllUsers(Integer id) {
        // 解绑小程序成员
        companyDao.unbindingAllAppUsers(id);
        // 解绑后台账号
        companyDao.unbindingAllPcUsers(id);
    }

    @Override
    public List<CompanyInfoVO> listCompanyInfoByIds(List<Integer> ids) {
        List<CompanyInfoDO> companyInfoDOS = companyDao.listCompanyInfoByIds(ids);
        List<CompanyInfoVO> companyInfoVOS = companyInfoDOS.stream().map(CompanyInfoDO::buildCompanyInfoVO).collect(Collectors.toList());
        return companyInfoVOS;
    }

    @Override
    public List<CompanyInfoVO> listCompanyInfoByBUIds(List<Integer> backUserAccountIds) {
        List<CompanyInfoDO> companyInfoDOS = this.listCompanyInfoByUID(backUserAccountIds);
        List<CompanyInfoVO> companyInfoVOS = companyInfoDOS.stream().map(CompanyInfoDO::buildCompanyInfoVO).collect(Collectors.toList());
        return companyInfoVOS;
    }

    @Override
    public void deleteCompanyInfoById(Integer id) {
        companyDao.deleteCompanyInfoById(id);
    }

    @Override
    public ResultBody getManagerIdByBackUserId(Integer backUserAccountId) {
        CompanyBackUserDO companyBackUserDO = companyDao.getCompanyBackUserByBackUserId(backUserAccountId);
        CompanyMemberDO companyMemberDO = companyDao.getManagerByCompanyId(companyBackUserDO.getCompanyInfoId());
        if (companyMemberDO == null) {
            return ResultBody.error("无管理员");
        }
        return ResultBody.success(companyMemberDO.getUserAccountId());
    }

    @Override
    public ResultBody insertUserRcd(Integer rUserId, List<Integer> userIds) {
        for (Integer userId : userIds) {
            Integer integer = companyDao.selectUserByUserRcd(userId);
            if(integer != 0){
                continue;
            }
            companyDao.insertUserRcd(userId,rUserId);
        }
        return ResultBody.success();
    }

    @Override
    public ResultBody listUserAndRoleByCompanyId(Integer companyInfoId) {
        List<CompanyMemberDO> companyMemberDOS = companyDao.selectUserAndRoleList(companyInfoId);
        List<CompanyMemberVO> companyMemberVOS = new ArrayList<>();
        // 遍历 companyMemberDOS 中的 userAccountId
        for (CompanyMemberDO companyMemberDO : companyMemberDOS) {
            Integer userAccountId = companyMemberDO.getUserAccountId();
            UserAccountDO userAccount = userServiceDao.getUserAccountById(userAccountId);
            UserAccountVO userAccountVO = userAccount.buildUserAccountVO();
            CompanyMemberVO companyMemberVO = CompanyMemberVO.builder()
                    .userAccountId(companyMemberDO.getUserAccountId())
                    .roleId(companyMemberDO.getLeader())
                    .roleName(companyMemberDO.getRoleName())
                    .userAccountVO(userAccountVO)
                    .serviceAlias(companyMemberDO.getServiceAlias())
                    .serviceImg(companyMemberDO.getServiceImg())
                    .build();
            companyMemberVOS.add(companyMemberVO);
        }
        return ResultBody.success(companyMemberVOS);
    }

    @Override
    public Integer getCompanyBindUserId(Integer userId1, Integer userId2,Integer backUserId) {
        //获取这个公司绑定的所有用户
        List<Integer> listUserIds = companyDao.getBindCompanyUserIdList(backUserId);
        if(listUserIds == null) {
            return null;
        }
        if(listUserIds.contains(userId1)) {
            //如果发送消息的用户是一家公司的不可以
            if(listUserIds.contains(userId2)) {
                return null;
            }else {
                return userId1;
            }
        }else {
            return userId2;
        }
    }

    @Override
    public ResultBody updateAliasImgByUid(AliasAndImgVo aliasAndImgVo) {
        Integer userAccountId = aliasAndImgVo.getUserAccountId();
        String serviceAlias = aliasAndImgVo.getServiceAlias();
        String serviceImg = aliasAndImgVo.getServiceImg();
        companyDao.updateAliasImgByUid(userAccountId, serviceAlias, serviceImg);
        return ResultBody.success();
    }

    @Override
    public ResultBody consultUserMessageNum(Integer companyInfoId) {
        int count = 0;
        List<CompanyMemberDO> companyMemberDOS = companyDao.selectUserAndRoleList(companyInfoId);
        if (companyMemberDOS == null || companyMemberDOS.isEmpty()) {
            return ResultBody.error("无管理员");
        }
        //查询公司单位 客服id集合
        Set<Integer> userAccountIds = companyMemberDOS.stream().map(CompanyMemberDO::getUserAccountId).collect(Collectors.toSet());
        List<UserMessageDO> userMessageDOS = messageDao.selectMessageByCompanyInfoId(companyInfoId);
        if (userMessageDOS == null || userMessageDOS.isEmpty()) {
            return ResultBody.error("本单位近七天无用户与客服聊天记录");
        }
        for (UserMessageDO message : userMessageDOS) {
            if (userAccountIds.contains(message.getReceiverUserId())) {
                count++;
            }
        }
        return ResultBody.success(count);
    }

}
