package org.dromara.materials.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PhoneUtil;
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.MatCompany;
import org.dromara.materials.domain.MatMaterials;
import org.dromara.materials.domain.dto.company.MatCompanyCreateReq;
import org.dromara.materials.domain.dto.company.MatCompanyQueryReq;
import org.dromara.materials.domain.dto.company.MatCompanyUpdateReq;
import org.dromara.materials.domain.vo.company.MatCompanyVo;
import org.dromara.materials.mapper.MatCompanyMapper;
import org.dromara.materials.service.IMatCompanyService;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 公司Service业务层处理
 *
 * @author lcj
 * @date 2025-03-06
 */
@Service
public class MatCompanyServiceImpl extends ServiceImpl<MatCompanyMapper, MatCompany>
    implements IMatCompanyService {

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private MatMaterialsServiceImpl materialService;

    /**
     * 查询公司
     *
     * @param id 主键
     * @return 公司
     */
    @Override
    public MatCompanyVo queryById(Long id) {
        MatCompany company = this.getById(id);
        if (company == null) {
            throw new ServiceException("对应材料提供商不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(company);
    }

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

    /**
     * 查询符合条件的公司列表
     *
     * @param req 查询条件
     * @return 公司列表
     */
    @Override
    public List<MatCompanyVo> queryList(MatCompanyQueryReq req) {
        LambdaQueryWrapper<MatCompany> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 新增公司
     *
     * @param req 公司
     * @return 新增公司id
     */
    @Override
    public Long insertByBo(MatCompanyCreateReq req) {
        // 将实体类和 DTO 进行转换
        MatCompany company = new MatCompany();
        BeanUtils.copyProperties(req, company);
        // 数据校验
        validEntityBeforeSave(company, true);
        // 公司名不能重复
        Long count = this.lambdaQuery().eq(MatCompany::getCompanyName, req.getCompanyName()).count();
        if (count > 0) {
            throw new ServiceException("公司名重复", HttpStatus.BAD_REQUEST);
        }
        // 写入数据库
        boolean save = this.save(company);
        if (!save) {
            throw new ServiceException("新增公司失败，数据库异常", HttpStatus.ERROR);
        }
        return company.getId();
    }

    /**
     * 修改公司
     *
     * @param req 公司
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MatCompanyUpdateReq req) {
        // 将实体类和 DTO 进行转换
        MatCompany company = new MatCompany();
        BeanUtils.copyProperties(req, company);
        // 数据校验
        validEntityBeforeSave(company, false);
        // 判断是否存在
        MatCompany oldCompany = this.getById(company.getId());
        if (oldCompany == null) {
            throw new ServiceException("修改公司失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        if (!req.getCompanyName().equals(oldCompany.getCompanyName())) {
            Long count = this.lambdaQuery().eq(MatCompany::getCompanyName, oldCompany.getCompanyName()).count();
            if (count > 0) {
                throw new ServiceException("公司名重复", HttpStatus.BAD_REQUEST);
            }
        }
        // 操作数据库
        return this.updateById(company);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MatCompany entity, Boolean create) {
        // 做一些数据校验,如唯一约束
        String companyName = entity.getCompanyName();
        Long projectId = entity.getProjectId();
        String principal = entity.getPrincipal();
        String principalPhone = entity.getPrincipalPhone();
        if (create) {
            if (StringUtils.isBlank(principal)) {
                throw new ServiceException("负责人不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(principalPhone)) {
                throw new ServiceException("负责人手机号不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(companyName)) {
                throw new ServiceException("公司名称不能为空", HttpStatus.BAD_REQUEST);
            }
            if (projectId == null) {
                throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        // 查询项目是否存在
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        if (StringUtils.isNotBlank(principalPhone) && !PhoneUtil.isPhone(principalPhone)) {
            throw new ServiceException("负责人手机号格式不正确", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除公司信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        List<MatCompany> companyList = this.listByIds(ids);
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            // 获取项目id列表
            List<Long> projectIdList = companyList.stream().map(MatCompany::getProjectId).toList();
            // 判断是否有权限操作对应项目下的内容
            projectService.validAuth(projectIdList, userId);
            // 判断公司中是否还存在材料信息
            QueryWrapper<MatMaterials> 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 this.removeBatchByIds(ids);
    }

    /**
     * 获取封装视图对象
     *
     * @param company 实体对象
     * @return 封装视图对象
     */
    @Override
    public MatCompanyVo getVo(MatCompany company) {
        // 对象转封装类
        MatCompanyVo companyVo = new MatCompanyVo();
        if (company == null) {
            return companyVo;
        }
        BeanUtils.copyProperties(company, companyVo);
        return companyVo;
    }

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

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