/**
 * 文件：MateriaBomTreeServiceImpl.java
 * 版本：1.0.0
 * 日期：
 * Copyright &reg;
 * All right reserved.
 */

package com.mortals.xhx.module.materia.service.impl;

import com.google.common.collect.Lists;
import com.mortals.framework.common.code.YesNo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.common.code.BomStatusEnum;
import com.mortals.xhx.module.materia.dao.MateriaBomTreeDao;
import com.mortals.xhx.module.materia.model.*;
import com.mortals.xhx.module.materia.service.MateriaBomService;
import com.mortals.xhx.module.materia.service.MateriaBomTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>Title: 物料BOM类目(产品树)</p>
 * <p>Description: MateriaBomTreeServiceImpl service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author
 * @version 1.0.0
 */
@Service("materiaBomTreeService")
public class MateriaBomTreeServiceImpl extends AbstractCRUDServiceImpl<MateriaBomTreeDao, MateriaBomTreeEntity, Long> implements MateriaBomTreeService {

    @Autowired
    private MateriaBomService materiaBomService;


    @Override
    protected void updateBefore(MateriaBomTreeEntity entity, Context context) throws AppException {
        //检查当前树下是否存在bom 如果存在 则不允许修改关联物料
        MateriaBomQuery bomQuery = new MateriaBomQuery();
        bomQuery.setBomTreeId(entity.getId());

        MateriaBomEntity bomEntity = materiaBomService.find(bomQuery, context).stream().findAny().orElseGet(() -> null);
        if(!ObjectUtils.isEmpty(bomEntity)){
            if(!ObjectUtils.isEmpty(entity.getMateriaId())&&!entity.getMateriaId().equals(bomEntity.getMateriaId())){
                throw new AppException(String.format("当前产品树下已存在BOM关联的物料:%s,不允许重新关联其它物料！", bomEntity.getMateriaName()));
            }
        }
        super.updateBefore(entity, context);
    }

    @Override
    protected void saveBefore(MateriaBomTreeEntity entity, Context context) throws AppException {
        if (ObjectUtils.isEmpty(entity.getParentId())) {
            entity.setParentId(-1L);
        }
        entity.setCode(getCode(entity.getParentId(), entity.getCode()));

        if (entity.getId() != null) {
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(context.getUser().getRealName());
        } else {
            entity.setUpdateTime(new Date());
            entity.setUpdateUser(context.getUser().getRealName());
            entity.setCreateTime(new Date());
            entity.setCreateUser(context.getUser().getRealName());
        }

        //检查新增目录是否超过最大级数

        boolean checklevel = checklevel(entity.getParentId(), 1, context);
        if (!checklevel) {
            throw new AppException("添加的子目录超过最大目录数！");
        }
        //校验bom代码与名称 都不重复
        MateriaBomTreeQuery materiaBomTreeQuery = new MateriaBomTreeQuery();
        materiaBomTreeQuery.setName(entity.getName());
        materiaBomTreeQuery.setCode(entity.getCode());
        List<MateriaBomTreeQuery> conditions = Lists.newArrayList(materiaBomTreeQuery);
        MateriaBomTreeQuery treeQuery = new MateriaBomTreeQuery();
        treeQuery.setAndConditionList(conditions);
        treeQuery.setParentId(entity.getParentId());
        List<MateriaBomTreeEntity> materiaBomTreeEntities = this.find(treeQuery, context);
        if(materiaBomTreeEntities.size()>0){
            throw new AppException("当前产品树编码或名字已存在！");
        }


        super.saveBefore(entity, context);
    }

    @Override
    protected void saveAfter(MateriaBomTreeEntity entity, Context context) throws AppException {
        //更新父节点 为非叶子节点
        if (entity.getParentId() != -1) {
            MateriaBomTreeEntity materiaBomTreeEntity = this.get(entity.getParentId(), context);
            materiaBomTreeEntity.setIsLeaf(YesNo.NO.getValue());
            this.update(materiaBomTreeEntity, context);
        }

    }

    private String getCode(Long id, String str) {

        if (id != -1L) {
            MateriaBomTreeEntity materiaBomTreeEntity = this.get(id, null);
            if (!ObjectUtils.isEmpty(materiaBomTreeEntity)) {
                str = materiaBomTreeEntity.getCode() + "." + str;
                // return getCode(materiaBomTreeEntity.getParentId(),str);
            }
        }
        return str;
    }

    @Override
    public boolean checklevel(Long parentId, Integer level, Context context) {
        MateriaBomTreeEntity materiaBomTreeEntity = this.get(parentId, context);

        if (ObjectUtils.isEmpty(materiaBomTreeEntity)) {
            return true;
        }

        if (materiaBomTreeEntity.getParentId() != -1) {
            level++;
            return checklevel(materiaBomTreeEntity.getParentId(), level, context);
        } else {
            return level >= 3 ? false : true;
        }
    }

    @Override
    public void checkBom(Long treeId, Context context) {
        //1.校验产品树是否有绑定物料
        MateriaBomTreeEntity materiaBomTreeEntity = this.get(treeId, context);
        if (ObjectUtils.isEmpty(materiaBomTreeEntity) || ObjectUtils.isEmpty(materiaBomTreeEntity.getMateriaId())) {
            throw new AppException("当前选择的产品树没有绑定物料！");
        }

        //绑定了物料，查找
        MateriaBomQuery bomQuery = new MateriaBomQuery();
        bomQuery.setBomTreeId(treeId);
        bomQuery.setStatusList(Arrays.asList(BomStatusEnum.BOM_EDIT.getValue(), BomStatusEnum.BOM_AUDIT.getValue()));

        MateriaBomEntity bomEntity = materiaBomService.find(bomQuery, context).stream().findAny().orElseGet(() -> null);
        if (!ObjectUtils.isEmpty(bomEntity)) {
            throw new AppException("当前产品树下存在修订中或审核中的bom！");
        }


    }


}