package cn.estsh.i3plus.ext.mes.pcn.apiservice.daoimpl;


import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.IMesEquipmentLogDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesEquipVariableCollectContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesEquipmentLog;
import cn.estsh.i3plus.pojo.mes.bean.MesEquipmentRecord;
import cn.estsh.i3plus.pojo.mes.bean.MesEquipmentVariable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

@Service
public class MesEquipmentLogDao implements IMesEquipmentLogDao {

    @Value("${mes.sharding.append.org:}")
    public String mesShardingAppendOrg;

    @Autowired
    private EntityManager entityManager;

    private final static String TWO_S_APPEND = "%s_%s";
    
    private final static String[] equipmentLogDetailFields = {MesPcnExtConstWords.ID, MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.IS_DELETED, 
            MesPcnExtConstWords.CREATE_USER, MesPcnExtConstWords.CREATE_DATE_TIME, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME,
            MesPcnExtConstWords.DESCRIPTION, MesPcnExtConstWords.REMARK, MesPcnExtConstWords.SYSTEM_SYNC_DATE_TIME, MesPcnExtConstWords.SYSTEM_SYNC_STATUS,
            MesPcnExtConstWords.AREA_CODE, MesPcnExtConstWords.WORK_CENTER_CODE, MesPcnExtConstWords.WORK_CELL_CODE, MesPcnExtConstWords.EQUIPMENT_CODE,
            MesPcnExtConstWords.PROCESS_CODE, MesPcnExtConstWords.CRAFT_CODE, MesPcnExtConstWords.MOULD_RECORD_ID, MesPcnExtConstWords.EXTEND,
            MesPcnExtConstWords.ORG_EQUIP_ID, MesPcnExtConstWords.EQUIP_ID, MesPcnExtConstWords.EQUIP_VARIABLE_ID, MesPcnExtConstWords.EQUIP_VARIABLE_NAME,
            MesPcnExtConstWords.EQUIP_VARIABLE_DESC, MesPcnExtConstWords.READ_WRITE_FLAG, MesPcnExtConstWords.DATA_TYPE, MesPcnExtConstWords.EQUIP_VARIABLE_VALUE,
            MesPcnExtConstWords.VARIABLE_TYPE, MesPcnExtConstWords.CATEGORY_LEVEL_TWO, MesPcnExtConstWords.QUALITY};

    @Override
    public List<MesEquipVariableCollectContext> queryMesEquipmentLog(List<MesEquipmentVariable> equipmentVariableList, String organizeCode, Integer equipId, Integer variableType) {

        List<MesEquipVariableCollectContext> equipVariableCollectContextList = generateEquipVariableCollectContextList(equipmentVariableList);

        if (CollectionUtils.isEmpty(equipmentVariableList) || StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(equipId) || StringUtils.isEmpty(variableType)) return null;

        StringBuffer builder = new StringBuffer();

        builder.append(" select e.equip_variable_id, e.equip_variable_value, e.equip_variable_status, e.quality, e.modify_date_time, e.id ");
        builder.append(" from mes_equipment_log_");
        if (!StringUtils.isEmpty(mesShardingAppendOrg) && mesShardingAppendOrg.toUpperCase().equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.name())) builder.append(organizeCode.toLowerCase()).append(MesPcnExtConstWords.E_UNDERLINE);
        builder.append(equipId);
        builder.append(" e where e.organize_code = :organizeCode and e.variable_type = :variableType ");

        Query query = entityManager.createNativeQuery(builder.toString());
        query.setParameter(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        query.setParameter(MesPcnExtConstWords.VARIABLE_TYPE, variableType);
        List list = query.getResultList();

        if (CollectionUtils.isEmpty(list)) return equipVariableCollectContextList;

        List<String> equipVariableIdList = equipmentVariableList.stream().filter(o -> null != o).map(o -> o.getId().toString()).collect(Collectors.toList());

        for (Object equipmentLog : list) {

            if (null == equipmentLog) continue;

            Object[] equipmentLogArr = (Object[]) equipmentLog;

            if (null == equipmentLogArr || equipmentLogArr.length != 6 || StringUtils.isEmpty(equipmentLogArr[0]) || !equipVariableIdList.contains(equipmentLogArr[0].toString())) continue;

            equipVariableCollectContextList.stream().filter(o -> (null != o && o.getEquipVariableId().toString().equals(equipmentLogArr[0].toString()))).findFirst().get().copyValue(equipmentLogArr[1], equipmentLogArr[2], equipmentLogArr[3], equipmentLogArr[4], equipmentLogArr[5]);

        }

        return equipVariableCollectContextList;
    }

    @Override
    public void updateEquipVariableStatus(String organizeCode, Integer equipId, Map<Long, String> equipmentLogIdMap, Integer equipVariableStatus) {

        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(equipId) || CollectionUtils.isEmpty(equipmentLogIdMap) || StringUtils.isEmpty(equipVariableStatus)) return;

        StringBuffer builder = new StringBuffer();

        for (int i = 0; i < equipmentLogIdMap.size(); i ++) {

            builder.append(" update mes_equipment_log_");
            if (!StringUtils.isEmpty(mesShardingAppendOrg) && mesShardingAppendOrg.toUpperCase().equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.name())) builder.append(organizeCode.toLowerCase()).append(MesPcnExtConstWords.E_UNDERLINE);
            builder.append(equipId);
            builder.append(" set equip_variable_status = :equipVariableStatus_");
            builder.append(i);
            builder.append(" where id = :id_");
            builder.append(i);
            builder.append(" and modify_date_time = :modifyDatetime_");
            builder.append(i);
            builder.append(" ;");

        }

        Query update = entityManager.createNativeQuery(builder.toString());

        Integer index = 0;
        for (Map.Entry<Long, String> entry : equipmentLogIdMap.entrySet()) {
            if (null == entry) continue;
            update.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIP_VARIABLE_STATUS, index), equipVariableStatus);
            update.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.ID, index), entry.getKey());
            update.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.MODIFY_DATE_TIME, index), entry.getValue());
            index ++;
        }

        update.executeUpdate();

    }

    private List<MesEquipVariableCollectContext> generateEquipVariableCollectContextList(List<MesEquipmentVariable> equipmentVariableList) {
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = new ArrayList<>();
        if (CollectionUtils.isEmpty(equipmentVariableList)) return equipVariableCollectContextList;
        equipmentVariableList.stream().filter(o -> null != o).forEach(o -> {
            MesEquipVariableCollectContext equipVariableCollectContext = new MesEquipVariableCollectContext(o.getId());
            BeanUtils.copyProperties(o, equipVariableCollectContext);
            equipVariableCollectContextList.add(equipVariableCollectContext);
        });
        return equipVariableCollectContextList;
    }

    @Override
    public List<MesEquipVariableCollectContext> queryMesEquipmentLog(String organizeCode, Integer equipId, Integer variableType, List<Long> equipVariableIdList) {

        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(equipId) || StringUtils.isEmpty(variableType) || CollectionUtils.isEmpty(equipVariableIdList)) return null;

        equipVariableIdList = equipVariableIdList.stream().filter(o -> !StringUtils.isEmpty(o)).distinct().collect(Collectors.toList());

        StringBuffer builder = new StringBuffer();

        builder.append(" select e.equip_variable_id, e.equip_variable_value, e.equip_variable_status, e.quality, e.modify_date_time, e.id ");
        builder.append(" from mes_equipment_log_");
        if (!StringUtils.isEmpty(mesShardingAppendOrg) && mesShardingAppendOrg.toUpperCase().equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.name())) builder.append(organizeCode.toLowerCase()).append(MesPcnExtConstWords.E_UNDERLINE);
        builder.append(equipId);
        builder.append(" e where e.organize_code = :organizeCode and e.variable_type = :variableType ");
        if (equipVariableIdList.size() == 1) builder.append(" and e.equip_variable_id = :equipVariableId ");
        else builder.append(" and e.equip_variable_id in (:equipVariableId) ");

        Query query = entityManager.createNativeQuery(builder.toString());
        query.setParameter(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        query.setParameter(MesPcnExtConstWords.VARIABLE_TYPE, variableType);
        if (equipVariableIdList.size() == 1) query.setParameter(MesPcnExtConstWords.EQUIP_VARIABLE_ID, equipVariableIdList.get(0));
        else query.setParameter(MesPcnExtConstWords.EQUIP_VARIABLE_ID, equipVariableIdList);
        List list = query.getResultList();

        return backEquipVariableCollectContextList(list);
    }

    @Override
    public List<MesEquipVariableCollectContext> queryMesEquipmentLog(String organizeCode, Integer equipId, Integer variableType) {

        if (StringUtils.isEmpty(organizeCode) || StringUtils.isEmpty(equipId) || StringUtils.isEmpty(variableType)) return null;

        StringBuffer builder = new StringBuffer();

        builder.append(" select e.equip_variable_id, e.equip_variable_value, e.equip_variable_status, e.quality, e.modify_date_time, e.id ");
        builder.append(" from mes_equipment_log_");
        if (!StringUtils.isEmpty(mesShardingAppendOrg) && mesShardingAppendOrg.toUpperCase().equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.name())) builder.append(organizeCode.toLowerCase()).append(MesPcnExtConstWords.E_UNDERLINE);
        builder.append(equipId);
        builder.append(" e where e.organize_code = :organizeCode and e.variable_type = :variableType ");

        Query query = entityManager.createNativeQuery(builder.toString());
        query.setParameter(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        query.setParameter(MesPcnExtConstWords.VARIABLE_TYPE, variableType);
        List list = query.getResultList();

        return backEquipVariableCollectContextList(list);

    }

    private List<MesEquipVariableCollectContext> backEquipVariableCollectContextList(List list) {

        if (CollectionUtils.isEmpty(list)) return null;

        List<MesEquipVariableCollectContext> equipVariableCollectContextList = new ArrayList<>();

        for (Object equipmentLog : list) {

            if (null == equipmentLog) continue;

            Object[] equipmentLogArr = (Object[]) equipmentLog;

            if (null == equipmentLogArr || equipmentLogArr.length != 6 || StringUtils.isEmpty(equipmentLogArr[0])) continue;

            equipVariableCollectContextList.add(new MesEquipVariableCollectContext(Long.valueOf(equipmentLogArr[0].toString())).copyValue(equipmentLogArr[1], equipmentLogArr[2], equipmentLogArr[3], equipmentLogArr[4], equipmentLogArr[5]));

        }

        return equipVariableCollectContextList;
    }

    @Override
    public void insertBatchEquipmentLogDetail(String organizeCode, Integer equipId, String userInfo, MesEquipmentRecord equipmentRecord, List<MesEquipmentLog> equipmentLogList) {
        
        StringBuffer builder = new StringBuffer();

        Integer index = 0;
        for (MesEquipmentLog equipmentLog : equipmentLogList) {
            if (null == equipmentLog) continue;

            builder.append(" insert into mes_equipment_log_detail_");
            if (!StringUtils.isEmpty(mesShardingAppendOrg) && mesShardingAppendOrg.toUpperCase().equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.name())) builder.append(organizeCode.toLowerCase()).append(MesPcnExtConstWords.E_UNDERLINE);
            builder.append(equipId);
            builder.append("( id, organize_code, is_valid, is_deleted, create_user, create_date_time, modify_user, modify_date_time,");
            builder.append(" description, remark, system_sync_date_time, system_sync_status,");
            builder.append(" area_code, work_center_code, work_cell_code, equipment_code, process_code, craft_code,");
            builder.append(" mould_record_id, extend, org_equip_id, equip_id, equip_variable_id, equip_variable_name, equip_variable_desc,");
            builder.append(" read_write_flag, data_type, equip_variable_value, variable_type, category_level_two, quality)");
            builder.append(" values ( ");

            for (int i = 0; i < equipmentLogDetailFields.length; i ++) {
                if (StringUtils.isEmpty(equipmentLogDetailFields[i])) continue;

                builder.append(MesPcnExtConstWords.COLON);
                builder.append(equipmentLogDetailFields[i]);
                builder.append(MesPcnExtConstWords.E_UNDERLINE);
                builder.append(index);
                if (i != equipmentLogDetailFields.length - 1) builder.append(" , ");
            }

            builder.append(" );");

            index ++;

        }

        Query insert = entityManager.createNativeQuery(builder.toString());

        String nowTime = TimeTool.getNowTime(true);
        String orgEquipId = new StringJoiner(MesPcnExtConstWords.E_UNDERLINE).add(organizeCode).add(equipId.toString()).toString();

        index = 0;
        for (MesEquipmentLog equipmentLog : equipmentLogList) {
            if (null == equipmentLog) continue;

            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.ID, index), equipmentLog.getId());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.ORGANIZE_CODE, index), organizeCode);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.IS_VALID, index), CommonEnumUtil.IS_VAILD.VAILD.getValue());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.IS_DELETED, index), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.CREATE_USER, index), userInfo);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.CREATE_DATE_TIME, index), nowTime);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.MODIFY_USER, index), userInfo);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.MODIFY_DATE_TIME, index), nowTime);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.DESCRIPTION, index), null);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.REMARK, index), null);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.SYSTEM_SYNC_DATE_TIME, index), null);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.SYSTEM_SYNC_STATUS, index), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.AREA_CODE, index), equipmentRecord.getAreaCode());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.WORK_CENTER_CODE, index), equipmentRecord.getWorkCenterCode());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.WORK_CELL_CODE, index), equipmentRecord.getWorkCellCode());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIPMENT_CODE, index), equipmentRecord.getEquipmentCode());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.PROCESS_CODE, index), equipmentRecord.getProcessCode());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.CRAFT_CODE, index), equipmentRecord.getCraftCode());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.MOULD_RECORD_ID, index), equipmentRecord.getId());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EXTEND, index), equipmentRecord.getProduceSnJson());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.ORG_EQUIP_ID, index), orgEquipId);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIP_ID, index), equipId);
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIP_VARIABLE_ID, index), equipmentLog.getEquipVariableId());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIP_VARIABLE_NAME, index), equipmentLog.getEquipVariableName());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIP_VARIABLE_DESC, index), equipmentLog.getEquipVariableDesc());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.READ_WRITE_FLAG, index), equipmentLog.getReadWriteFlag());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.DATA_TYPE, index), equipmentLog.getDataType());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.EQUIP_VARIABLE_VALUE, index), equipmentLog.getEquipVariableValue());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.VARIABLE_TYPE, index), equipmentLog.getVariableType());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.CATEGORY_LEVEL_TWO, index), equipmentLog.getCategoryLevelTwo());
            insert.setParameter(String.format(TWO_S_APPEND, MesPcnExtConstWords.QUALITY, index), equipmentLog.getQuality());

            index ++;
        }

        insert.executeUpdate();

    }

}
