package org.dromara.materials.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.materials.domain.BusCompany;
import org.dromara.materials.domain.BusMaterials;
import org.dromara.materials.domain.req.company.CompanyCreateReq;
import org.dromara.materials.domain.req.company.CompanyQueryReq;
import org.dromara.materials.domain.req.company.CompanyUpdateReq;
import org.dromara.materials.domain.vo.BusCompanyVo;
import org.dromara.materials.mapper.BusCompanyMapper;
import org.dromara.materials.service.IBusCompanyService;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 公司Service业务层处理
 *
 * @author lcj
 * @date 2025-03-06
 */
@Service
public class BusCompanyServiceImpl extends ServiceImpl<BusCompanyMapper, BusCompany>
    implements IBusCompanyService {

    @Resource
    private BusCompanyMapper baseMapper;

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private BusMaterialsServiceImpl materialService;

    /**
     * 查询公司
     *
     * @param id 主键
     * @return 公司
     */
    @Override
    public BusCompanyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询公司列表
     *
     * @param req       查询条件
     * @param pageQuery 分页信息
     * @return 公司分页列表
     */
    @Override
    public TableDataInfo<BusCompanyVo> queryPageList(CompanyQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<BusCompany> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(this.getCompanyVoPage(result));
    }

    /**
     * 查询符合条件的公司列表
     *
     * @param req 查询条件
     * @return 公司列表
     */
    @Override
    public List<BusCompanyVo> queryList(CompanyQueryReq req) {
        LambdaQueryWrapper<BusCompany> lqw = this.buildQuery(req);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 新增公司
     *
     * @param req 公司
     * @return 新增公司id
     */
    @Override
    public Long insertByBo(CompanyCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusCompany company = new BusCompany();
        BeanUtils.copyProperties(req, company);
        // 数据校验
        validEntityBeforeSave(company);
        // 写入数据库
        boolean save = this.save(company);
        if (!save) {
            throw new ServiceException("新增公司失败，数据库异常", HttpStatus.ERROR);
        }
        return company.getId();
    }

    /**
     * 修改公司
     *
     * @param req 公司
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CompanyUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusCompany company = new BusCompany();
        BeanUtils.copyProperties(req, company);
        // 数据校验
        validEntityBeforeSave(company);
        // 判断是否存在
        BusCompany oldCompany = this.getById(company.getId());
        if (oldCompany == null) {
            throw new ServiceException("修改公司失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(company);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusCompany entity) {
        // 做一些数据校验,如唯一约束
        String companyName = entity.getCompanyName();
        Long projectId = entity.getProjectId();
        if (StringUtils.isBlank(companyName)) {
            throw new ServiceException("公司名称不能为空", HttpStatus.BAD_REQUEST);
        }
        // 公司名不能重复
        LambdaQueryWrapper<BusCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusCompany::getCompanyName, companyName);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new ServiceException("公司名重复", HttpStatus.BAD_REQUEST);
        }
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        // 查询项目是否存在
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 校验并批量删除公司信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        List<BusCompany> companyList = this.listByIds(ids);
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            // 获取项目id列表
            List<Long> projectIdList = companyList.stream().map(BusCompany::getProjectId).toList();
            // 判断是否有权限操作对应项目下的内容
            projectService.validAuth(projectIdList, userId);
            // 判断公司中是否还存在材料信息
            QueryWrapper<BusMaterials> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("company_id", ids);
            if (materialService.count(queryWrapper) > 0) {
                throw new ServiceException("删除公司失败，公司中存在材料信息", HttpStatus.BAD_REQUEST);
            }
        }
        // 判断对应数据是否都存在
        if (companyList.size() != ids.size()) {
            throw new ServiceException("删除公司失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 构建查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusCompany> buildQuery(CompanyQueryReq req) {
        LambdaQueryWrapper<BusCompany> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String companyName = req.getCompanyName();
        Long projectId = req.getProjectId();
        String status = req.getStatus();
        String remark = req.getRemark();
        String qualification = req.getQualification();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(companyName), BusCompany::getCompanyName, companyName);
        lqw.like(StringUtils.isNotBlank(qualification), BusCompany::getQualification, qualification);
        lqw.like(StringUtils.isNotBlank(remark), BusCompany::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(status), BusCompany::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(id), BusCompany::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusCompany::getProjectId, projectId);
        return lqw;
    }

    /**
     * 获取公司分页对象视图
     *
     * @param companyPage 公司分页对象
     * @return 公司分页对象视图
     */
    @Override
    public Page<BusCompanyVo> getCompanyVoPage(Page<BusCompany> companyPage) {
        List<BusCompany> companyList = companyPage.getRecords();
        Page<BusCompanyVo> companyVoPage = new Page<>(companyPage.getCurrent(), companyPage.getSize(), companyPage.getTotal());
        if (CollUtil.isEmpty(companyList)) {
            return companyVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusCompanyVo> companyVoList = companyList.stream().map(company -> {
            BusCompanyVo companyVo = new BusCompanyVo();
            BeanUtils.copyProperties(company, companyVo);
            return companyVo;
        }).toList();
        companyVoPage.setRecords(companyVoList);
        return companyVoPage;
    }
}
