package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base;

import cn.estsh.i3plus.ext.mes.api.base.ISxContainerService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.model.ContainerExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.PartContainerCapacityExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.bu.MesContainerTypeModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesContainer;
import cn.estsh.i3plus.pojo.mes.bean.MesContainerType;
import cn.estsh.i3plus.pojo.mes.bean.MesPartContainerCapacity;
import cn.estsh.i3plus.pojo.mes.repository.MesContainerRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesContainerTypeRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesPartContainerCapacityRepository;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class SxContainerService implements ISxContainerService {

    @Autowired
    private MesContainerTypeRepository containerTypeRepository;

    @Autowired
    private MesContainerRepository containerRepository;

    @Autowired
    private MesPartContainerCapacityRepository partContainerCapacityRepository;

    @Autowired
    private MesPartExtRepository partExtRepository;

    @Override
    public ListPager<MesContainerTypeModel> queryContainerTypeByPager(MesContainerType containerType, Pager pager) {
        DdlPackBean hqlPack = MesExtHqlPack.getContainerType(containerType);
        pager = PagerHelper.getPager(pager, containerTypeRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(containerType.orderBy());
        List<MesContainerType> containerTypeList = containerTypeRepository.findByHqlWherePage(hqlPack, pager);
        List<MesContainerTypeModel> containerTypeModels = new ArrayList<>();
        containerTypeList.stream().forEach(mesContainerType -> {
            MesContainerTypeModel containerTypeModel = new MesContainerTypeModel();
            BeanUtils.copyProperties(mesContainerType, containerTypeModel);
            //容器类别
            containerTypeModel.setUseLimitName(MesExtEnumUtil.CT_TYPE.valueOfDescription(containerTypeModel.getUseLimit()));
            containerTypeModels.add(containerTypeModel);
        });
        return new ListPager(containerTypeModels, pager);
    }

    @Override
    public MesContainerType insertContainerType(MesContainerType containerType) {
        DdlPackBean packBean = MesExtHqlPack.getAllBaseData(containerType.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(containerType.getCtCode(), MesExtConstWords.CT_CODE, packBean);
        MesContainerType containerTypeDb = containerTypeRepository.getByProperty(packBean);
        if (null != containerTypeDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("容器类型代码[%s]记录已存在", containerType.getCtCode())
                    .build();
        }
        containerType.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelInitialize(containerType, containerType.getCreateUser());
        return containerTypeRepository.insert(containerType);
    }

    @Override
    public MesContainerType updateContainerType(MesContainerType containerType) {
        MesContainerType containerTypeDb = containerTypeRepository.getById(containerType.getId());
        if (containerTypeDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("容器类型代码[%s]记录不存在", containerType.getCtCode())
                    .build();
        }

        containerTypeDb.setUseLimit(containerType.getUseLimit());
        containerTypeDb.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(containerTypeDb, containerType.getModifyUser());
        return containerTypeRepository.save(containerTypeDb);
    }

    @Override
    public int updateContainerTypeValidById(Long id, Integer status, String organizeCode, String userName) {
        if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("启用，禁用枚举状态值[%s]未被定义", status)
                    .build();
        }
        MesContainerType containerTypeDb = containerTypeRepository.getById(id);
        if (containerTypeDb == null || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == containerTypeDb.getIsDeleted()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", id)
                    .build();
        }
        return containerTypeRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.SYNC_STATUS},
                new Object[]{status, userName, TimeTool.getNowTime(true), MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue()});
    }

    @Override
    public ListPager<ContainerExtModel> queryContainerByPager(MesContainer container, Pager pager) {
        List<ContainerExtModel> resultList = new ArrayList<>();
        DdlPackBean hqlPack = MesExtHqlPack.getContainer(container);
        pager = PagerHelper.getPager(pager, containerRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(container.orderBy());
        List<MesContainer> containerList = containerRepository.findByHqlWherePage(hqlPack, pager);
        if (!CollectionUtils.isEmpty(containerList)) {
            Map<String, Object> ctCodeEntityMap;
            try {
                ctCodeEntityMap = MesCommonUtil.getCodeEntityMap(containerTypeRepository, MesExtConstWords.CT_CODE, container.getOrganizeCode(), "容器类型表");
            } catch (Exception e) {
                ctCodeEntityMap = null;
            }
            for (MesContainer item : containerList) {
                if (null == item) {
                    continue;
                }
                ContainerExtModel result = new ContainerExtModel();
                BeanUtils.copyProperties(item, result);
                if (!CollectionUtils.isEmpty(ctCodeEntityMap) && ctCodeEntityMap.containsKey(item.getCtCode())) {
                    result.setCtName(((MesContainerType)ctCodeEntityMap.get(item.getCtCode())).getCtName());
                    result.setUseLimit(MesExtEnumUtil.CT_TYPE.valueOfDescription(((MesContainerType) ctCodeEntityMap.get(item.getCtCode())).getUseLimit()));
                }
                result.setUseStatusName(MesExtEnumUtil.CONTAINER_USE_STATUS.valueOfDescription(item.getUseStatus()));
                resultList.add(result);
            }
        }
        return new ListPager(resultList, pager);
    }

    @Override
    public MesContainer insertContainer(MesContainer container) {
        DdlPackBean packBean = MesExtHqlPack.getAllBaseData(container.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(container.getCtNo(), MesExtConstWords.CT_NO, packBean);
        MesContainer containerDb = containerRepository.getByProperty(packBean);
        if (null != containerDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("容器代码[%s]记录已存在", container.getCtNo())
                    .build();
        }
        container.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelInitialize(container, container.getCreateUser());
        return containerRepository.insert(container);
    }

    @Override
    public MesContainer updateContainer(MesContainer container) {
        MesContainer containerDb = containerRepository.getById(container.getId());
        if (containerDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("容器代码[%s]记录不存在", container.getCtNo())
                    .build();
        }

        containerDb.setCtCode(container.getCtCode());
        containerDb.setUseStatus(container.getUseStatus());
        containerDb.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(containerDb, container.getModifyUser());
        return containerRepository.save(containerDb);
    }

    @Override
    public int updateContainerValidById(Long id, Integer status, String organizeCode, String userName) {
        if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("启用，禁用枚举状态值[%s]未被定义", status)
                    .build();
        }
        MesContainer containerDb = containerRepository.getById(id);
        if (containerDb == null || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == containerDb.getIsDeleted()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", id)
                    .build();
        }
        return containerRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.SYNC_STATUS},
                new Object[]{status, userName, TimeTool.getNowTime(true), MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue()});
    }

    @Override
    public ListPager<PartContainerCapacityExtModel> queryPartContainerCapacityByPager(MesPartContainerCapacity partContainerCapacity, Pager pager) {
        List<PartContainerCapacityExtModel> resultList = new ArrayList<>();
        DdlPackBean hqlPack = MesExtHqlPack.getPartContainerCapacity(partContainerCapacity);
        pager = PagerHelper.getPager(pager, partContainerCapacityRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(partContainerCapacity.orderBy());
        List<MesPartContainerCapacity> partContainerCapacityList = partContainerCapacityRepository.findByHqlWherePage(hqlPack, pager);
        if (!CollectionUtils.isEmpty(partContainerCapacityList)) {
            Map<String, Object> partCodeEntityMap;
            try {
                partCodeEntityMap = MesCommonUtil.getCodeEntityMap(partExtRepository, MesExtConstWords.PART_NO, partContainerCapacity.getOrganizeCode(), "物料表");
            } catch (Exception e) {
                partCodeEntityMap = null;
            }
            Map<String, Object> ctCodeEntityMap;
            try {
                ctCodeEntityMap = MesCommonUtil.getCodeEntityMap(containerTypeRepository, MesExtConstWords.CT_CODE, partContainerCapacity.getOrganizeCode(), "容器类型表");
            } catch (Exception e) {
                ctCodeEntityMap = null;
            }
            for (MesPartContainerCapacity item : partContainerCapacityList) {
                if (null == item) {
                    continue;
                }
                PartContainerCapacityExtModel result = new PartContainerCapacityExtModel();
                BeanUtils.copyProperties(item, result);
                if (!CollectionUtils.isEmpty(partCodeEntityMap) && partCodeEntityMap.containsKey(item.getPartNo())) {
                    result.setPartName(((MesPartExt)partCodeEntityMap.get(item.getPartNo())).getPartName());
                }
                if (!CollectionUtils.isEmpty(ctCodeEntityMap) && ctCodeEntityMap.containsKey(item.getCtCode())) {
                    result.setCtName(((MesContainerType)ctCodeEntityMap.get(item.getCtCode())).getCtName());
                }
                resultList.add(result);
            }
        }
        return new ListPager(resultList, pager);
    }

    @Override
    public MesPartContainerCapacity insertPartContainerCapacity(MesPartContainerCapacity partContainerCapacity) {
        DdlPackBean packBean = MesExtHqlPack.getAllBaseData(partContainerCapacity.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(partContainerCapacity.getPartNo(), MesExtConstWords.PART_NO, packBean);
        DdlPreparedPack.getStringEqualPack(partContainerCapacity.getCtCode(), MesExtConstWords.CT_CODE, packBean);
        MesPartContainerCapacity partContainerCapacityDb = partContainerCapacityRepository.getByProperty(packBean);
        if (null != partContainerCapacityDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("物料代码[%s]容器类型[%s]的产品容器容量配置记录已存在", partContainerCapacity.getPartNo(), partContainerCapacity.getCtCode())
                    .build();
        }
        partContainerCapacity.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelInitialize(partContainerCapacity, partContainerCapacity.getCreateUser());
        return partContainerCapacityRepository.insert(partContainerCapacity);
    }

    @Override
    public MesPartContainerCapacity updatePartContainerCapacity(MesPartContainerCapacity partContainerCapacity) {
        MesPartContainerCapacity partContainerCapacityDb = partContainerCapacityRepository.getById(partContainerCapacity.getId());
        if (partContainerCapacityDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("物料代码[%s]容器类型[%s]记录不存在", partContainerCapacity.getPartNo(), partContainerCapacity.getCtCode())
                    .build();
        }

        partContainerCapacityDb.setCtQty(partContainerCapacity.getCtQty());
        partContainerCapacityDb.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(partContainerCapacityDb, partContainerCapacity.getModifyUser());
        return partContainerCapacityRepository.save(partContainerCapacityDb);
    }

    @Override
    public int updatePartContainerCapacityValidById(Long id, Integer status, String organizeCode, String userName) {
        if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("启用，禁用枚举状态值[%s]未被定义", status)
                    .build();
        }
        MesPartContainerCapacity partContainerCapacityDb = partContainerCapacityRepository.getById(id);
        if (partContainerCapacityDb == null || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == partContainerCapacityDb.getIsDeleted()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", id)
                    .build();
        }
        return partContainerCapacityRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.SYNC_STATUS},
                new Object[]{status, userName, TimeTool.getNowTime(true), MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue()});
    }
}
