package org.dromara.materials.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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 lombok.RequiredArgsConstructor;
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.json.utils.JsonUtils;
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.BusMaterials;
import org.dromara.materials.domain.BusMaterialsInventory;
import org.dromara.materials.domain.req.materials.MaterialsCreateReq;
import org.dromara.materials.domain.req.materials.MaterialsQueryReq;
import org.dromara.materials.domain.req.materials.MaterialsUpdateReq;
import org.dromara.materials.domain.vo.BusMaterialsVo;
import org.dromara.materials.mapper.BusMaterialsMapper;
import org.dromara.materials.service.IBusCompanyService;
import org.dromara.materials.service.IBusMaterialsInventoryService;
import org.dromara.materials.service.IBusMaterialsService;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 材料名称Service业务层处理
 *
 * @author lcj
 * @date 2025-03-06
 */
@RequiredArgsConstructor
@Service
public class BusMaterialsServiceImpl extends ServiceImpl<BusMaterialsMapper, BusMaterials>
    implements IBusMaterialsService {

    @Resource
    private BusMaterialsMapper baseMapper;

    @Resource
    private IBusCompanyService companyService;

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private IBusMaterialsInventoryService materialsInventoryService;

    /**
     * 查询材料名称
     *
     * @param id 主键
     * @return 材料名称
     */
    @Override
    public BusMaterialsVo queryById(Long id) {
        BusMaterials materials = this.getById(id);
        if (materials == null) {
            throw new ServiceException("材料名称信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getBusMaterialsVo(materials);
    }

    /**
     * 分页查询材料名称列表
     *
     * @param req       查询条件
     * @param pageQuery 分页条件
     * @return 材料名称分页列表
     */
    @Override
    public TableDataInfo<BusMaterialsVo> queryPageList(MaterialsQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<BusMaterials> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(this.getMaterialsVoPage(result));
    }

    /**
     * 查询符合条件的材料名称列表
     *
     * @param req 查询条件
     * @return 材料名称列表
     */
    @Override
    public List<BusMaterialsVo> queryList(MaterialsQueryReq req) {
        LambdaQueryWrapper<BusMaterials> lqw = this.buildQuery(req);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 新增材料名称
     *
     * @param req 材料名称
     * @return 新增材料信息id
     */
    @Override
    public Long insertByBo(MaterialsCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusMaterials materials = new BusMaterials();
        BeanUtils.copyProperties(req, materials);
        // 数据转换
        Map<String, Long> fileOssIdList = req.getFileOssIdMap();
        String fileOssIdStr = JsonUtils.toJsonString(fileOssIdList);
        materials.setFileOssId(fileOssIdStr);
        // 数据校验
        validEntityBeforeSave(materials);
        // 写入数据库
        boolean save = this.save(materials);
        if (!save) {
            throw new ServiceException("新增材料信息失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return materials.getId();
    }

    /**
     * 修改材料名称
     *
     * @param req 材料名称
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MaterialsUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusMaterials materials = new BusMaterials();
        BeanUtils.copyProperties(req, materials);
        // 数据转换
        Map<String, Long> fileOssIdList = req.getFileOssIdMap();
        String fileOssIdStr = JSONUtil.toJsonStr(fileOssIdList);
        materials.setFileOssId(fileOssIdStr);
        // 数据校验
        validEntityBeforeSave(materials);
        // 判断是否存在
        BusMaterials oldMaterials = this.getById(materials.getId());
        if (oldMaterials == null) {
            throw new ServiceException("修改材料信息失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(materials);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusMaterials entity) {
        // 做一些数据校验,如唯一约束
        String materialsName = entity.getMaterialsName();
        Long companyId = entity.getCompanyId();
        Long projectId = entity.getProjectId();
        if (StringUtils.isEmpty(materialsName)) {
            throw new ServiceException("请填写材料名称", HttpStatus.BAD_REQUEST);
        }
        if (companyId == null) {
            throw new ServiceException("请填写公司ID", HttpStatus.BAD_REQUEST);
        }
        if (companyService.getById(companyId) == null) {
            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.BAD_REQUEST);
        }
    }

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

    /**
     * 获取材料视图
     *
     * @param materials 材料
     * @return 材料视图
     */
    @Override
    public BusMaterialsVo getBusMaterialsVo(BusMaterials materials) {
        // 对象转封装类
        BusMaterialsVo materialsVo = new BusMaterialsVo();
        if (materials == null) {
            return materialsVo;
        }
        BeanUtils.copyProperties(materials, materialsVo);
        // 关联查询项目信息
        Long companyId = materials.getCompanyId();
        if (companyId != null) {
            materialsVo.setCompanyVo(companyService.queryById(companyId));
        }
        // 关联对象存储文件信息
        String fileOssId = materials.getFileOssId();
        if (StringUtils.isEmpty(fileOssId)) {
            return materialsVo;
        }
        Map<String, Long> fileOssMap = new HashMap<>();
        JSONObject parseObj = JSONUtil.parseObj(fileOssId);
        parseObj.forEach((key, value) -> fileOssMap.put(key, (Long) value));
        materialsVo.setFileOssMap(fileOssMap);
        return materialsVo;
    }

    /**
     * 构建查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusMaterials> buildQuery(MaterialsQueryReq req) {
        LambdaQueryWrapper<BusMaterials> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String materialsName = req.getMaterialsName();
        Long companyId = req.getCompanyId();
        Long projectId = req.getProjectId();
        String typeSpecificationName = req.getTypeSpecificationName();
        String usePart = req.getUsePart();
        String weightId = req.getWeightId();
        String remark = req.getRemark();
        String quantityCount = req.getQuantityCount();
        String status = req.getStatus();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(materialsName), BusMaterials::getMaterialsName, materialsName);
        lqw.like(StringUtils.isNotBlank(typeSpecificationName), BusMaterials::getTypeSpecificationName, typeSpecificationName);
        lqw.like(StringUtils.isNotBlank(usePart), BusMaterials::getUsePart, usePart);
        lqw.like(StringUtils.isNotBlank(remark), BusMaterials::getRemark, remark);
        lqw.like(StringUtils.isNotBlank(weightId), BusMaterials::getWeightId, weightId);
        lqw.like(StringUtils.isNotBlank(quantityCount), BusMaterials::getQuantityCount, quantityCount);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(status), BusMaterials::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(id), BusMaterials::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusMaterials::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(companyId), BusMaterials::getCompanyId, companyId);
        return lqw;
    }

    /**
     * 获取材料分页对象视图
     *
     * @param materialsPage 材料分页对象
     * @return 材料分页对象视图
     */
    @Override
    public Page<BusMaterialsVo> getMaterialsVoPage(Page<BusMaterials> materialsPage) {
        // 获取材料数据
        List<BusMaterials> materialsList = materialsPage.getRecords();
        // 添加分页信息
        Page<BusMaterialsVo> materialsVoPage = new Page<>(materialsPage.getCurrent(), materialsPage.getSize(), materialsPage.getTotal());
        if (CollUtil.isEmpty(materialsList)) {
            return materialsVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusMaterialsVo> materialsVoList = materialsList.stream().map(this::getBusMaterialsVo).toList();
        materialsVoPage.setRecords(materialsVoList);
        return materialsVoPage;
    }
}
