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

import cn.estsh.i3plus.ext.mes.api.busi.jx.IJxCenterWorkingBoardService;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesShift;
import cn.estsh.i3plus.pojo.mes.repository.MesShiftRepository;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.StringJoiner;

/**
 * @Author : wangjie
 * @CreateDate : 2022-02-15
 * @Modify:
 **/
@Slf4j
public class JxCenterWorkingBoardProxyShiftService extends JxCenterWorkingBoardCommonService implements IJxCenterWorkingBoardService {

    private MesShiftRepository shiftRepository;

    public JxCenterWorkingBoardProxyShiftService() {
        this.shiftRepository = (MesShiftRepository) SpringContextsUtil.getBean("mesShiftRepository");
    }

    @Override
    public Map<String, Object> queryCenterWorkingBoardData(Map<String, Object> dataMap) {
        String organizeCode = (String) dataMap.get(MesExtConstWords.ORGANIZE_CODE);
        String workCenterCode = (String) dataMap.get(MesExtConstWords.WORK_CENTER_CODE);
        String shiftCode = (String) dataMap.get(MesExtConstWords.SHIFT_CODE);

        if (StringUtils.isEmpty(shiftCode)) return dataMap;

        String item = new StringJoiner(MesExtConstWords.AND).add("SHIFT").add(workCenterCode).add(shiftCode).toString();
        String shift4Cached = (String) execCachedCenterWorkingBoardData(organizeCode, MesExtConstWords.ZERO_STR, item, null);
        MesShift shift = !StringUtils.isEmpty(shift4Cached) ? JSONObject.parseObject(shift4Cached, MesShift.class) : execShift(organizeCode, workCenterCode, shiftCode, item);
        if (null == shift) return dataMap;

        dataMap.put(MesShift.class.getSimpleName(), shift);

        return dataMap;
    }

    private MesShift execShift(String organizeCode, String workCenterCode, String shiftCode, String item) {
        MesShift shiftDb = shiftRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.WORK_CENTER_CODE, MesExtConstWords.SHIFT_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), workCenterCode, shiftCode});
        if (null != shiftDb) execCachedCenterWorkingBoardData(organizeCode, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValueStr(), item, JSONObject.toJSONString(shiftDb));
        return shiftDb;
    }

}
