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

import cn.estsh.i3plus.ext.mes.api.base.IShiftProdService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftProd;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftProdCenter;
import cn.estsh.i3plus.ext.mes.pojo.model.ShiftProdModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesShiftProdCenterRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesShiftProdRepository;
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.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.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 org.springframework.util.StringUtils;

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

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

    @Autowired
    private MesShiftProdRepository shiftProdRepository;

    @Autowired
    private MesShiftProdCenterRepository shiftProdCenterRepository;

    @Override
    public ListPager<ShiftProdModel> queryShiftProdByPager(ShiftProdModel shiftProd, Pager pager) {
        DdlPackBean hqlPack = MesExtHqlPack.getShiftProd(shiftProd);
        pager = PagerHelper.getPager(pager, shiftProdRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(shiftProd.orderBy());
        List<MesShiftProd> shiftProdList = shiftProdRepository.findByHqlWherePage(hqlPack, pager);
        List<ShiftProdModel> modelList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shiftProdList)) {
            for (MesShiftProd prod : shiftProdList) {
                ShiftProdModel model = new ShiftProdModel();
                BeanUtils.copyProperties(prod, model);
                if (null == prod) {
                    continue;
                }
                model.setProdCategoryName(StringUtils.isEmpty(prod.getProdCategory()) ?
                        null : MesExtEnumUtil.SHIFT_PROD_CATEGORY.valueOfDescription(prod.getProdCategory()));
                model.setProdTypeName(StringUtils.isEmpty(prod.getProdType()) ?
                        null : MesExtEnumUtil.SHIFT_PROD_TYPE.valueOfDescription(prod.getProdType()));
                model.setIsProdTimeName(StringUtils.isEmpty(prod.getIsProdTime()) ?
                        null : MesExtEnumUtil.SHIFT_PROD_IS_PROD_TIME.valueOfDescription(prod.getIsProdTime()));
                model.setPlanRateStr(StringUtils.isEmpty(prod.getPlanRate()) ? null : prod.getPlanRate() + MesExtConstWords.PERCENT);
                modelList.add(model);
            }
        }
        return new ListPager(modelList, pager);
    }

    @Override
    public MesShiftProd insertShiftProd(MesShiftProd shiftProd) {
        DdlPackBean packBean = MesExtHqlPack.getAllBaseData(shiftProd.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(shiftProd.getProdCode(), MesExtConstWords.PROD_CODE, packBean);
        MesShiftProd shiftProdDb = shiftProdRepository.getByProperty(packBean);
        if (null != shiftProdDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("作业内容代码[%s]记录已存在", shiftProd.getProdCode())
                    .build();
        }
        ConvertBean.serviceModelInitialize(shiftProd, shiftProd.getCreateUser());
        return shiftProdRepository.insert(shiftProd);
    }

    @Override
    public MesShiftProd updateShiftProd(MesShiftProd shiftProd) {
        MesShiftProd shiftProdDb = shiftProdRepository.getById(shiftProd.getId());
        if (shiftProdDb == null) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("作业内容代码[%s]记录不存在", shiftProd.getProdCode())
                    .build();
        }

        shiftProdDb.setProdName(shiftProd.getProdName());
        shiftProdDb.setIsProdTime(shiftProd.getIsProdTime());
        shiftProdDb.setProdCategory(shiftProd.getProdCategory());
        shiftProdDb.setPlanRate(shiftProd.getPlanRate());
        ConvertBean.serviceModelUpdate(shiftProdDb, shiftProd.getModifyUser());
        return shiftProdRepository.save(shiftProdDb);
    }

    @Override
    public int updateShiftProdValidById(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();
        }
        MesShiftProd shiftProdDb = shiftProdRepository.getById(id);
        if (shiftProdDb == null || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == shiftProdDb.getIsDeleted()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", id)
                    .build();
        }
        if (status == CommonEnumUtil.IS_VAILD.INVAILD.getValue()) {
            checkIsJoinShiftProdCenter(organizeCode, shiftProdDb.getProdCode());
        }
        return shiftProdRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, userName, TimeTool.getNowTime(true)});
    }

    private void checkIsJoinShiftProdCenter(String organizeCode, String prodCode) {
        DdlPackBean packBean = MesExtHqlPack.getAllBaseData(organizeCode);
        DdlPreparedPack.getStringEqualPack(prodCode, MesExtConstWords.PROD_CODE, packBean);
        MesShiftProdCenter shiftProdCenterDb = shiftProdCenterRepository.getByProperty(packBean);
        if (null != shiftProdCenterDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("作业内容代码[%s]已经被关联产线班次固定作业内容信息,操作失败", prodCode)
                    .build();
        }
    }

    @Override
    public int deleteShiftProdById(Long id, String organizeCode, String userName) {
        //对id做有效性校验
        MesShiftProd shiftProdDb = shiftProdRepository.getById(id);
        if (shiftProdDb == null || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == shiftProdDb.getIsDeleted()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", id)
                    .build();
        }

        checkIsJoinShiftProdCenter(organizeCode, shiftProdDb.getProdCode());

        return shiftProdRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_DELETED, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), userName, TimeTool.getNowTime(true)});
    }

    @Override
    public List<MesShiftProd> getShiftProdList(String organizeCode) {
        if (StringUtils.isEmpty(organizeCode)) return null;
        return shiftProdRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
    }

}
