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

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.service.UserFirmService;
import com.zsElectric.boot.business.model.entity.UserFirm;
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 java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

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

    private final UserFirmConverter userFirmConverter;

    /**
    * 获取企业与用户关系分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UserFirmVO>} 企业与用户关系分页列表
    */
    @Override
    public IPage<UserFirmVO> getUserFirmPage(UserFirmQuery queryParams) {
        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) {
        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);
    }

}
