package com.seer.teach.mp.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.RoleEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mp.app.controller.req.AppAgentEmployeeRelationQueryReq;
import com.seer.teach.mp.app.controller.req.AppAgentEmployeeRelationReq;
import com.seer.teach.mp.app.controller.resp.AppAgentEmployeeRelationResp;
import com.seer.teach.mp.app.service.IAppAgentEmployeeRelationService;
import com.seer.teach.mp.entity.MpAgentEmployeeRelationEntity;
import com.seer.teach.mp.service.IMpAgentEmployeeRelationService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.UserRelationServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import com.seer.teach.user.api.dto.UserRelationDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * App端代理商员工关系服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2025-12-30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppAgentEmployeeRelationServiceImpl implements IAppAgentEmployeeRelationService {

    private final IMpAgentEmployeeRelationService mpAgentEmployeeRelationService;
    private final UserInfoServiceApi userInfoServiceApi;

    @Override
    public PageListBean<AppAgentEmployeeRelationResp> pageList(AppAgentEmployeeRelationQueryReq query) {
        log.info("查询参数：{}", query);
        IPage<MpAgentEmployeeRelationEntity> page = new Page<>(query.getPageNo(), query.getPageSize());
        var pageResult = mpAgentEmployeeRelationService.page(page, new LambdaQueryWrapper<>(MpAgentEmployeeRelationEntity.class)
                .eq(MpAgentEmployeeRelationEntity::getAgentId, query.getAgentId())
                .like(StringUtils.isNotBlank(query.getPosition()), MpAgentEmployeeRelationEntity::getPosition, query.getPosition())
                .eq(query.getStatus() != null, MpAgentEmployeeRelationEntity::getStatus, query.getStatus()));

        if (CollectionUtil.isEmpty(pageResult.getRecords())) {
            log.info("查询结果为空");
        }
        log.info("查询代理商员工数量：{}", pageResult.getTotal());

        return PageConverterUtils.convertPageListBean(pageResult, this::convertToRespList);
    }

    @Override
    public boolean addEmployee(AppAgentEmployeeRelationReq request) {
        LambdaQueryWrapper<MpAgentEmployeeRelationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MpAgentEmployeeRelationEntity::getAgentId, request.getAgentId())
               .eq(MpAgentEmployeeRelationEntity::getContactPhone, request.getContactPhone());

        MpAgentEmployeeRelationEntity existing = mpAgentEmployeeRelationService.getOne(wrapper);
        if (existing != null) {
            throw new CommonException(ResultCodeEnum.DATA_REPEAT_ERROR, "该员工已属于当前代理商");
        }
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUserName(request.getEmployeeName());
        userInfoDTO.setMobile(request.getContactPhone());
        userInfoDTO.setPassword(request.getPassword());
        userInfoDTO.setRoleCode(RoleEnum.AGENT);
        Integer userId = userInfoServiceApi.addUserInfoAndAssignRole(userInfoDTO);

        MpAgentEmployeeRelationEntity entity = new MpAgentEmployeeRelationEntity();
        entity.setAgentId(request.getAgentId());
        entity.setEmployeeUserId(userId);
        entity.setPosition(request.getPosition());
        entity.setStatus(request.getStatus());

        boolean result = mpAgentEmployeeRelationService.save(entity);
        log.info("新增员工结果：{}", result);
        return result;
    }

    @Override
    public boolean updateEmployee(AppAgentEmployeeRelationReq request) {
        // 验证员工是否属于当前代理商（通过ID查询并验证）
        MpAgentEmployeeRelationEntity existing = mpAgentEmployeeRelationService.getById(request.getId());
        AssertUtils.notNull(existing, ResultCodeEnum.DATA_NOT_EXIST);

        if (!existing.getAgentId().equals(request.getAgentId())) {
            throw new CommonException(ResultCodeEnum.PERMISSION_DENIED, "无权限操作此员工");
        }

        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUserName(request.getEmployeeName());
        userInfoDTO.setMobile(request.getContactPhone());
        userInfoDTO.setPassword(request.getPassword());
        boolean updateUserResult = userInfoServiceApi.updateUserInfo(userInfoDTO);
        log.info("更新员工结果：{}", updateUserResult);

        MpAgentEmployeeRelationEntity updateEntity = new MpAgentEmployeeRelationEntity();
        updateEntity.setId(request.getId());
        updateEntity.setPosition(request.getPosition());
        updateEntity.setStatus(request.getStatus());
        updateEntity.setEmployeeName(request.getEmployeeName());
        existing.setContactPhone(request.getContactPhone());
        boolean result = mpAgentEmployeeRelationService.updateById(existing);
        log.info("更新员工结果：{}", result);
        return result;
    }

    @Override
    public boolean deleteEmployee(Integer id) {
        MpAgentEmployeeRelationEntity existing = mpAgentEmployeeRelationService.getById(id);
        AssertUtils.notNull(existing, ResultCodeEnum.DATA_NOT_EXIST);
        boolean result = mpAgentEmployeeRelationService.removeById(id);
        log.info("删除员工结果：{}", result);
        return result;
    }

    @Override
    public AppAgentEmployeeRelationResp getById(Integer id) {
        MpAgentEmployeeRelationEntity entity = mpAgentEmployeeRelationService.getById(id);
        if (entity == null) {
            return null;
        }
        return convertToResp(entity);
    }

    @Override
    public List<AppAgentEmployeeRelationResp> getAllEmployeesByAgentId(Integer agentId) {
        List<MpAgentEmployeeRelationEntity> entities = mpAgentEmployeeRelationService.list(
            new LambdaQueryWrapper<MpAgentEmployeeRelationEntity>()
                .eq(MpAgentEmployeeRelationEntity::getAgentId, agentId)
        );

        if (CollectionUtil.isEmpty(entities)) {
            return List.of();
        }
        return entities.stream()
                .map(this::convertToResp)
                .collect(Collectors.toList());
    }

    @Override
    public boolean isEmployeeBelongsToAgent(Integer relationId, Integer agentId) {
        MpAgentEmployeeRelationEntity entity = mpAgentEmployeeRelationService.getById(relationId);
        if (entity == null) {
            return false;
        }
        return entity.getAgentId().equals(agentId);
    }

    /**
     * 将实体转换为响应对象
     */
    private AppAgentEmployeeRelationResp convertToResp(MpAgentEmployeeRelationEntity entity) {
        AppAgentEmployeeRelationResp resp = new AppAgentEmployeeRelationResp();
        resp.setId(entity.getId());
        resp.setAgentId(entity.getAgentId());
        resp.setPosition(entity.getPosition());
        resp.setStatus(entity.getStatus());
        resp.setCreateTime(entity.getCreateTime());
        resp.setUpdateTime(entity.getUpdateTime());

        // 通过用户服务获取员工的详细信息
        if (entity.getEmployeeUserId() != null) {
            UserInfoDTO userInfo = userInfoServiceApi.getByUserId(entity.getEmployeeUserId());
            resp.setEmployeeUserInfo(userInfo);
        }

        return resp;
    }

    /**
     * 批量转换实体为响应对象
     */
    private List<AppAgentEmployeeRelationResp> convertToRespList(List<MpAgentEmployeeRelationEntity> entities) {
        if (CollectionUtil.isEmpty(entities)) {
            return List.of();
        }
        return entities.stream()
                .map(this::convertToResp)
                .collect(Collectors.toList());
    }
}