package com.zsElectric.boot.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsElectric.boot.business.mapper.UserFirmMapper;
import com.zsElectric.boot.business.mapper.UserInfoMapper;
import com.zsElectric.boot.business.service.UserFirmService;
import com.zsElectric.boot.business.model.entity.UserFirm;
import com.zsElectric.boot.business.model.entity.UserInfo;
import com.zsElectric.boot.business.model.form.UserFirmForm;
import com.zsElectric.boot.business.model.query.UserFirmQuery;
import com.zsElectric.boot.business.model.vo.UserFirmVO;
import com.zsElectric.boot.business.converter.UserFirmConverter;
import com.zsElectric.boot.core.exception.BusinessException;

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

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.zsElectric.boot.security.util.SecurityUtils;
import com.zsElectric.boot.business.service.FirmInfoService;

/**
 * 企业与用户关系服务实现类
 *
 * @author zsElectric
 * @since 2025-12-12 10:29
 */
@Service
@RequiredArgsConstructor
public class UserFirmServiceImpl extends ServiceImpl<UserFirmMapper, UserFirm> implements UserFirmService {

    /**
     * 三方用户角色编码
     */
    private static final String ROLE_SFUSER = "SFUSER";

    private final UserFirmConverter userFirmConverter;
    private final FirmInfoService firmInfoService;
    private final UserInfoMapper userInfoMapper;

    /**
    * 获取企业与用户关系分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UserFirmVO>} 企业与用户关系分页列表
    */
    @Override
    public IPage<UserFirmVO> getUserFirmPage(UserFirmQuery queryParams) {
        // 判断当前用户是否为三方用户，如果是则只查询自己所属公司的数据
        Set<String> roles = SecurityUtils.getRoles();
        if (roles != null && roles.contains(ROLE_SFUSER)) {
            // 三方用户只能查询自己所属部门关联的企业数据
            Long deptId = SecurityUtils.getDeptId();
            Long firmId = firmInfoService.getFirmIdByDeptId(deptId);
            queryParams.setFirmId(firmId);
        }
        Page<UserFirmVO> pageVO = this.baseMapper.getUserFirmPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取企业与用户关系表单数据
     *
     * @param id 企业与用户关系ID
     * @return 企业与用户关系表单数据
     */
    @Override
    public UserFirmForm getUserFirmFormData(Long id) {
        UserFirm entity = this.getById(id);
        return userFirmConverter.toForm(entity);
    }
    
    /**
     * 新增企业与用户关系
     *
     * @param formData 企业与用户关系表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveUserFirm(UserFirmForm formData) {
        // 通过手机号查询c_user_info表，验证用户是否存在
        String phone = formData.getPhone();
        Assert.isTrue(StrUtil.isNotBlank(phone), "手机号不能为空");
        
        UserInfo userInfo = userInfoMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getPhone, phone)
                        .eq(UserInfo::getIsDeleted, 0)
        );
        
        if (userInfo == null) {
            throw new BusinessException("该手机号用户不存在，请先在小程序端注册");
        }
        
        // 检查该用户是否已经关联了企业
        UserFirm existingUserFirm = this.getOne(
                new LambdaQueryWrapper<UserFirm>()
                        .eq(UserFirm::getUserId, userInfo.getId())
                        .eq(UserFirm::getIsDeleted, 0)
        );
        
        if (existingUserFirm != null) {
            throw new BusinessException("该用户已经关联了企业，不能重复添加");
        }
        
        // 设置用户ID
        formData.setUserId(userInfo.getId());
        
        UserFirm entity = userFirmConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新企业与用户关系
     *
     * @param id   企业与用户关系ID
     * @param formData 企业与用户关系表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateUserFirm(Long id,UserFirmForm formData) {
        UserFirm entity = userFirmConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除企业与用户关系
     *
     * @param ids 企业与用户关系ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUserFirms(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的企业与用户关系数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
