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.BackUserAccountDao;
import com.mmc.iuav.user.dao.CompanyDao;
import com.mmc.iuav.user.dao.UserServiceDao;
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.CompanyInfoVO;
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.List;
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;

    @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);
        if (companyInfoDO != null) {
            CompanyInfoVO companyInfoVO = companyInfoDO.buildCompanyInfoVO();
            // 设置手机号
            CompanyBackUserDO companyBackUserDO = companyDao.getCompanyBackUserByCompanyId(id);
            if (companyBackUserDO != null) {
                BackUserAccountDO backUserAccountDO = backUserAccountDao.getBackUserAccountDO(companyBackUserDO.getBackUserAccountId());
                if (backUserAccountDO != null) {
                    companyInfoVO.setPhoneNum(backUserAccountDO.getPhoneNum());
                    companyInfoVO.setBackUserId(companyBackUserDO.getBackUserAccountId());
                }
            }
            return ResultBody.success(companyInfoVO);
        }
        return ResultBody.success();
    }

    @Override
    public ResultBody<CompanyInfoVO> listCompanyPage(CompanyInfoQO param, LoginSuccessDTO loginSuccessDTO) {
        CompanyInfoDO companyInfoDO = companyDao.getCompanyInfoByBackUserAccountId(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 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) {
        // 查看该成员是否已被绑定
        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(0);
        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);
        }
        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));
        }
        pageNo = (pageNo - 1) * pageSize;
        List<UserAccountDO> userAccountDOS = companyDao.listCompanyMembersPage(companyInfoId, pageNo, 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();
    }


}
