/*
 * Copyright [2022] [https://www.baiduc.com]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.baiduc.com
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.baiduc.com
 */
package vip.xiaonuo.sale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.sale.entity.ErpBaseMaterial;
import vip.xiaonuo.sale.mapper.ErpBaseMaterialMapper;
import vip.xiaonuo.sale.param.ErpBaseMaterialAddParam;
import vip.xiaonuo.sale.param.ErpBaseMaterialEditParam;
import vip.xiaonuo.sale.param.ErpBaseMaterialIdParam;
import vip.xiaonuo.sale.param.ErpBaseMaterialPageParam;
import vip.xiaonuo.sale.service.ErpBaseMaterialService;

import java.util.List;

/**
 * erp_base_materialService接口实现类
 *
 * @author 1
 * @date  2025/02/18 13:54
 **/
@Service
public class ErpBaseMaterialServiceImpl extends ServiceImpl<ErpBaseMaterialMapper, ErpBaseMaterial> implements ErpBaseMaterialService {

    @Autowired
    private ErpBaseMaterialMapper erpBaseMaterialMapper;

    @Override
    public Page<ErpBaseMaterial> page(ErpBaseMaterialPageParam erpBaseMaterialPageParam) {
        QueryWrapper<ErpBaseMaterial> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(erpBaseMaterialPageParam.getSortField(), erpBaseMaterialPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(erpBaseMaterialPageParam.getSortOrder());
            queryWrapper.orderBy(true, erpBaseMaterialPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(erpBaseMaterialPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ErpBaseMaterial::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult<String>  add(ErpBaseMaterialAddParam erpBaseMaterialAddParam) {
        ErpBaseMaterial erpBaseMaterial = BeanUtil.toBean(erpBaseMaterialAddParam, ErpBaseMaterial.class);
        if (StringUtils.isBlank(erpBaseMaterial.getOrgId())){
            throw new CommonException("请选择公司");
        }
        if(erpBaseMaterialMapper.exists(new QueryWrapper<ErpBaseMaterial>().eq("org_id",erpBaseMaterial.getOrgId()).eq("material_name", erpBaseMaterial.getMaterialName()).eq("fspecification",erpBaseMaterial.getFspecification()))){
            throw new CommonException("物料名称、规格重复");
        }
        if(StringUtils.isNotBlank(erpBaseMaterial.getErpId() ) && erpBaseMaterialMapper.exists(new QueryWrapper<ErpBaseMaterial>().eq("org_id",erpBaseMaterial.getOrgId()).eq("erp_id", erpBaseMaterial.getErpId()))){
            throw new CommonException("erp编码重复");
        }
        if (erpBaseMaterial.getAttr() == 0 && erpBaseMaterialMapper.selectCount(new QueryWrapper<ErpBaseMaterial>().eq("org_id",erpBaseMaterial.getOrgId()).eq("attr",0).eq("parent_id",erpBaseMaterial.getParentId()))>0){
            throw new CommonException("已有换算物料，请修改");
        }
        Integer parentId = erpBaseMaterial.getParentId();
        if (parentId ==0){
            erpBaseMaterial.setLevel(1);
        }else {
            erpBaseMaterial.setLevel(erpBaseMaterialMapper.selectById(parentId).getLevel()+1);
        }
        this.save(erpBaseMaterial);
        return CommonResult.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ErpBaseMaterialEditParam erpBaseMaterialEditParam) {

        ErpBaseMaterial erpBaseMaterial = BeanUtil.toBean(erpBaseMaterialEditParam, ErpBaseMaterial.class);
        if (StringUtils.isBlank(erpBaseMaterial.getOrgId())){
            throw new CommonException("请选择公司");
        }
        if(erpBaseMaterialMapper.selectCount(new QueryWrapper<ErpBaseMaterial>().eq("org_id",erpBaseMaterial.getOrgId()).eq("material_name", erpBaseMaterial.getMaterialName()).eq("fspecification",erpBaseMaterial.getFspecification()).ne("id",erpBaseMaterial.getId()))>0){
            throw new CommonException("物料名称、规格重复");
        }
        if(StringUtils.isNotBlank(erpBaseMaterial.getErpId() ) && erpBaseMaterialMapper.selectCount(new QueryWrapper<ErpBaseMaterial>().eq("org_id",erpBaseMaterial.getOrgId()).eq("erp_id", erpBaseMaterial.getErpId()).ne("id",erpBaseMaterial.getId()))>0){
            throw new CommonException("erp编码重复");
        }
        if (erpBaseMaterial.getAttr() == 0 && erpBaseMaterialMapper.selectCount(new QueryWrapper<ErpBaseMaterial>().eq("org_id",erpBaseMaterial.getOrgId()).eq("attr",0).eq("parent_id",erpBaseMaterial.getParentId()).ne("id",erpBaseMaterial.getId()))>0){
            throw new CommonException("已有换算物料，请修改");
        }
        this.updateById(erpBaseMaterial);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ErpBaseMaterialIdParam> erpBaseMaterialIdParamList) {
        for (ErpBaseMaterialIdParam erpBaseMaterialIdParam : erpBaseMaterialIdParamList) {
            if (erpBaseMaterialMapper.exists(new QueryWrapper<ErpBaseMaterial>().eq("parent_id",erpBaseMaterialIdParam.getId()))){
                throw new CommonException("该物料有下级无聊，请删除");
            }
        }
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(erpBaseMaterialIdParamList, ErpBaseMaterialIdParam::getId));
    }

    @Override
    public ErpBaseMaterial detail(ErpBaseMaterialIdParam erpBaseMaterialIdParam) {
        return this.queryEntity(erpBaseMaterialIdParam.getId());
    }

    @Override
    public ErpBaseMaterial queryEntity(Integer id) {
        ErpBaseMaterial erpBaseMaterial = this.getById(id);
        if(ObjectUtil.isEmpty(erpBaseMaterial)) {
            throw new CommonException("erp_base_material不存在，id值为：{}", id);
        }
        return erpBaseMaterial;
    }

    @Override
    public Object getHuan(ErpBaseMaterialEditParam erpBaseMaterialIdParam) {
        return null;
    }
}
