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

import cn.estsh.i3plus.ext.mes.api.busi.jx.ISxWorkCellTaktCollectRecordService;
import cn.estsh.i3plus.ext.mes.pojo.bean.SxWorkCellTaktCollectRecord;
import cn.estsh.i3plus.ext.mes.pojo.model.jx.JxCellTaktReportModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.SxWorkCellTaktCollectRecordRepository;
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.tool.MathOperation;
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.base.tool.HqlPack;
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.*;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-jx
 * @DESCRIPTION: 松下工位节拍采集记录
 * @USER: xinwang.yi
 * @DATE: 2023-12-05 14:21
 */
@Service
public class SxWorkCellTaktCollectRecordService implements ISxWorkCellTaktCollectRecordService {

    @Autowired
    private SxWorkCellTaktCollectRecordRepository workCellTaktCollectRecordRepository;

    @Override
    public ListPager<SxWorkCellTaktCollectRecord> queryWorkCellTaktCollectRecordListByPager(SxWorkCellTaktCollectRecord workCellTaktCollectRecord, Pager pager) {
        if (workCellTaktCollectRecord == null) {
            pager = PagerHelper.getPager(pager, workCellTaktCollectRecordRepository.listCount());
            return new ListPager(workCellTaktCollectRecordRepository.listPager(pager), pager);
        } else {
            DdlPackBean hqlPack = MesExtHqlPack.getSxWorkCellTaktCollectRecord(workCellTaktCollectRecord);
            hqlPack.setOrderByStr(workCellTaktCollectRecord.orderBy());
            pager = PagerHelper.getPager(pager, workCellTaktCollectRecordRepository.findByHqlWhereCount(hqlPack));
            List<SxWorkCellTaktCollectRecord> byHqlWherePage = workCellTaktCollectRecordRepository.findByHqlWherePage(hqlPack, pager);
            return new ListPager(byHqlWherePage, pager);
        }
    }

    @Override
    public int updateWorkCellTaktCollectRecordValid(String[] ids, int status, String userName) {

        StringBuffer wheres = new StringBuffer();
        HqlPack.getInPack(String.join(",", ids), MesExtConstWords.ID, wheres);

        int num = workCellTaktCollectRecordRepository.updateByHqlWhere(
                wheres.toString(),
                new String[]{MesExtConstWords.SYSTEM_SYNC_STATUS, MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue(), status, userName, TimeTool.getNowTime(true)}
        );
        return num;

    }

    @Override
    public ListPager<JxCellTaktReportModel> queryCellTaktReportListByPager(JxCellTaktReportModel model, Pager pager) {

        List<JxCellTaktReportModel> resultList = new ArrayList<>();
        List<SxWorkCellTaktCollectRecord> recordDbList;

        DdlPackBean packBean = DdlPackBean.getDdlPackBean(model.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(model.getWorkCenterCode(), MesExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(model.getWorkCellCode(), MesExtConstWords.WORK_CELL_CODE, packBean);
        if (!StringUtils.isEmpty(model.getCreateDatetimeStart()) || !StringUtils.isEmpty(model.getCreateDatetimeEnd()))
            DdlPreparedPack.timeBuilder(model.getCreateDatetimeStart(), model.getCreateDatetimeEnd(), MesExtConstWords.MODIFY_DATE_TIME, packBean, true);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.ASC.getValue()}, new String[]{MesExtConstWords.CREATE_DATE_TIME}, packBean);

        if (model.getDimension() == 1) {
            pager = PagerHelper.getPager(pager, workCellTaktCollectRecordRepository.findByHqlWhereCount(packBean));
            recordDbList = workCellTaktCollectRecordRepository.findByHqlWherePage(packBean, pager);
            Integer index = (pager.getCurrentPage() - 1) * pager.getPageSize() + 1;
            for (SxWorkCellTaktCollectRecord recordDb : recordDbList) {
                JxCellTaktReportModel result = new JxCellTaktReportModel(model.getOrganizeCode(), model.getWorkCenterCode(), recordDb.getWorkCellCode());
                result.setDay(recordDb.getCreateDatetime().substring(0, 10));
                result.setTime(recordDb.getCreateDatetime().substring(11));
                result.setIndex(index);
                result.setWorkTakt(new Double(recordDb.getWorkTakt()));
                result.setPartNo(recordDb.getPartNo());
                result.setPartNameRdd(recordDb.getPartNameRdd());
                result.setStandardWork(recordDb.getStandardWork());
                result.setWorkerQty(recordDb.getWorkerQty());
                if (!StringUtils.isEmpty(result.getStandardWork()) && !StringUtils.isEmpty(result.getWorkerQty()))
                    result.setWorkTaktCalc(MathOperation.div(MathOperation.mul(result.getStandardWork(), new Double(60)), result.getWorkerQty()));
                resultList.add(result);
                index ++;
            }
        } else {
            recordDbList = workCellTaktCollectRecordRepository.findByHqlWhere(packBean);
            Map<String, List<SxWorkCellTaktCollectRecord>> recordDbMap2Cell = CollectionUtils.isEmpty(recordDbList) ? null : recordDbList.stream().filter(o -> null != o).collect(Collectors.groupingBy(SxWorkCellTaktCollectRecord::getWorkCellCode));
            DoubleSummaryStatistics statistics;
            if (!CollectionUtils.isEmpty(recordDbMap2Cell)) {
                recordDbMap2Cell = recordDbMap2Cell.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
                for (Map.Entry<String, List<SxWorkCellTaktCollectRecord>> entry : recordDbMap2Cell.entrySet()) {
                    if (null == entry) continue;
                    List<SxWorkCellTaktCollectRecord> recordDbList2Cell = entry.getValue();
                    statistics = recordDbList2Cell.stream().filter(o -> null != o).mapToDouble(o -> new Double(o.getWorkTakt())).summaryStatistics();
                    JxCellTaktReportModel result = new JxCellTaktReportModel(model.getOrganizeCode(), model.getWorkCenterCode(), entry.getKey());
                    result.setCreateDatetimeStart(model.getCreateDatetimeStart());
                    result.setCreateDatetimeEnd(model.getCreateDatetimeEnd());
                    result.setWorkTakt(statistics.getAverage());
                    result.setWorkTaktMax(statistics.getMax());
                    result.setWorkTaktMin(statistics.getMin());
                    resultList.add(result);
                }
            }
            statistics = CollectionUtils.isEmpty(resultList) ? null : resultList.stream().filter(o -> null != o).mapToDouble(JxCellTaktReportModel::getWorkTaktMin).summaryStatistics();
            pager = PagerHelper.getPager(pager, resultList.size());
            resultList = CollectionUtils.isEmpty(resultList) ? resultList :
                    resultList.subList((pager.getCurrentPage() - 1) * pager.getPageSize(), (pager.getCurrentPage() * pager.getPageSize()) > resultList.size() ? resultList.size() : pager.getCurrentPage() * pager.getPageSize());
            if (!CollectionUtils.isEmpty(resultList)) resultList.get(0).setWorkTaktCalc(statistics.getAverage());
        }

        return new ListPager(resultList, pager);
    }
}
