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

import cn.estsh.i3plus.ext.mes.api.base.jx.IJxBadnessClassifyService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesBadnessClassify;
import cn.estsh.i3plus.ext.mes.pojo.model.jx.JxBadnessClassifyModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesBadnessClassifyRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesBadnessTypeRepository;
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.HqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-qms-panasonic
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2022-06-07 10:45
 */
@Service
public class JxBadnessClassifyService implements IJxBadnessClassifyService {
    @Autowired
    private MesBadnessClassifyRepository badnessClassifyRepository;

    @Autowired
    private MesBadnessTypeRepository badnessTypeDao;

    @Override
    public ListPager<JxBadnessClassifyModel> queryBadnessClassifyPager(MesBadnessClassify badnessClassify, Pager pager) {
        DdlPackBean packBean = MesExtHqlPack.getSxBadnessClassify(badnessClassify);
        pager = PagerHelper.getPager(pager, badnessClassifyRepository.findByHqlWhereCount(packBean));
        packBean.setOrderByStr(" order by modifyDatetime desc ");
        List<MesBadnessClassify> sxQmsBadnessClassifies = badnessClassifyRepository.findByHqlWherePage(packBean, pager);
        return new ListPager(sxQmsBadnessClassifies, pager);
//        if(CollectionUtils.isEmpty(sxQmsBadnessClassifies)){
//            return new ListPager(sxQmsBadnessClassifies, pager);
//        }
        // 获取不良类型集合
//        List<MesBadnessType> buBadnessTypes = badnessTypeDao.findByProperty(
//                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
//                new Object[]{badnessClassify.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
//
//        Map<String, List<MesBadnessType>> buBadnessTypeMap = buBadnessTypes.stream().collect(Collectors.groupingBy(MesBadnessType::getBadnessTypeCode));

//        List<BadnessClassifyModel> buBadnessClassifyModels = new ArrayList<>();
//        sxQmsBadnessClassifies.stream().forEach(qmsBadnessClassify -> {
//            BadnessClassifyModel buBadnessClassifyModel = new BadnessClassifyModel();
//            BeanUtils.copyProperties(qmsBadnessClassify, buBadnessClassifyModel);
//            buBadnessClassifyModel.setBadnessTypeName(buBadnessTypeMap.get(buBadnessClassifyModel.getBadnessTypeCode()).get(0).getBadnessTypeName());
//            buBadnessClassifyModels.add(buBadnessClassifyModel);
//        });
//        return new ListPager(buBadnessClassifyModels, pager);
    }

    @Override
    public void insertBadnessClassify(MesBadnessClassify sxQmsBadnessClassify, String userName) {
        MesBadnessClassify sxQmsBadnessClassifyDb = badnessClassifyRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.BADNESS_TYPE_CODE, MesExtConstWords.BADNESS_CLASSIFY_CODE},
                new Object[]{sxQmsBadnessClassify.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), sxQmsBadnessClassify.getBadnessTypeCode(), sxQmsBadnessClassify.getBadnessClassifyCode()});

        if (null != sxQmsBadnessClassifyDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("根据[不良类型编码,不良分类编码]查询已经存在此条数据,请勿重复新增")
                    .build();
        }
        sxQmsBadnessClassify.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelInitialize(sxQmsBadnessClassify, userName);
        badnessClassifyRepository.insert(sxQmsBadnessClassify);
    }

    @Override
    public void updateBadnessClassify(MesBadnessClassify sxQmsBadnessClassify, String userName) {
        MesBadnessClassify badnessClassifyDb = badnessClassifyRepository.getById(sxQmsBadnessClassify.getId());
        if (null == badnessClassifyDb || CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == badnessClassifyDb.getIsDeleted()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]数据不存在", sxQmsBadnessClassify.getId())
                    .build();
        }

        MesBadnessClassify badnessClassifyUpdateDb = badnessClassifyRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.BADNESS_TYPE_CODE, MesExtConstWords.BADNESS_CLASSIFY_CODE},
                new Object[]{sxQmsBadnessClassify.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), sxQmsBadnessClassify.getBadnessTypeCode(), sxQmsBadnessClassify.getBadnessClassifyCode()});

        if (null != badnessClassifyUpdateDb && badnessClassifyUpdateDb.getId().compareTo(sxQmsBadnessClassify.getId()) != 0) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.QMS.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("根据[不良类型编码,不良分类编码]查询已经存在此条数据,修改失败")
                    .build();
        }

        badnessClassifyDb.setBadnessTypeCode(sxQmsBadnessClassify.getBadnessTypeCode());
        badnessClassifyDb.setBadnessTypeName(sxQmsBadnessClassify.getBadnessTypeName());
        badnessClassifyDb.setBadnessClassifyCode(sxQmsBadnessClassify.getBadnessClassifyCode());
        badnessClassifyDb.setBadnessClassifyName(sxQmsBadnessClassify.getBadnessClassifyName());
        badnessClassifyDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        badnessClassifyDb.setOrganizeCode(sxQmsBadnessClassify.getOrganizeCode());
        ConvertBean.serviceModelUpdate(badnessClassifyDb, userName);
        badnessClassifyRepository.save(badnessClassifyDb);
    }

    @Override
    public void deleteBadnessClassify(Long ids[], String userName) {

        StringBuffer wheres = new StringBuffer();
        //HqlPack.getInPack(String.join(",", ids), "id", wheres);

        int num = badnessClassifyRepository.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesExtConstWords.IS_DELETED, MesExtConstWords.SYSTEM_SYNC_STATUS, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{MesExtEnumUtil.TRUE_OR_FALSE.TRUE.getValue(),MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue(), AuthUtil.getSessionUser().getUserName(), TimeTool.getNowTime(true)}
        );
    }

    @Override
    public MesBadnessClassify getBadnessClassify(String organizeCode, String badnessTypeCode, String badnessClassifyCode) {
        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(badnessTypeCode) || StringUtils.isEmpty(badnessClassifyCode)) {
            return null;
        }
        return badnessClassifyRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.BADNESS_TYPE_CODE, MesExtConstWords.BADNESS_CLASSIFY_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), badnessTypeCode, badnessClassifyCode});
    }

    @Override
    public String getBadnessClassifyName(String organizeCode, String badnessTypeCode, String badnessClassifyCode) {
        MesBadnessClassify buBadnessClassify = getBadnessClassify(organizeCode, badnessTypeCode, badnessClassifyCode);
        return null != buBadnessClassify ? buBadnessClassify.getBadnessClassifyName() : null;
    }

    @Override
    public List<MesBadnessClassify> getBadnessClassifyList(String organizeCode) {
        if (StringUtils.isEmpty(organizeCode)) {
            return null;
        }
        return badnessClassifyRepository.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()});
    }

    @Override
    public Map<String, List<MesBadnessClassify>> getBadnessClassifyMap(String organizeCode) {
        List<MesBadnessClassify> badnessClassifyList = getBadnessClassifyList(organizeCode);
        return CollectionUtils.isEmpty(badnessClassifyList) ? null :
                badnessClassifyList.stream().filter(o -> null != o).collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getBadnessTypeCode()).add(o.getBadnessClassifyCode()).toString()));
    }

}
