package com.prolog.rdc.tms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.enums.LogTypeEnum;
import com.prolog.rdc.tms.dao.mapper.BmsLogOperationMapper;
import com.prolog.rdc.tms.model.dto.shipbill.BmsLogOperationDTO;
import com.prolog.rdc.tms.model.entity.BmsLogOperationModel;
import com.prolog.rdc.tms.service.BmsBillLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hongbo.pan
 * @date 2023/4/13
 */
@Service
public class BmsBillLogServiceImpl implements BmsBillLogService {

    @Autowired
    private BmsLogOperationMapper logOperationMapper;

    @Override
    public List<BmsLogOperationDTO> getLog(LogTypeEnum logTypeEnum, String code) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        Criteria criteria = Criteria.forClass(BmsLogOperationModel.class);
        Restriction r1 = Restrictions.eq(BmsLogOperationModel::getOrderNo, code);
        Restriction r2 = Restrictions.eq(BmsLogOperationModel::getEnterpriseId, user.getEnterpriseId());
        Restriction r3 = Restrictions.eq(BmsLogOperationModel::getLogType, logTypeEnum.getCode());
        criteria.setRestriction(Restrictions.and(r1, r2, r3));
        List<BmsLogOperationDTO> dtoList = Lists.newArrayList();
        List<BmsLogOperationModel> modelList = logOperationMapper.findByCriteria(criteria);
        if (CollectionUtil.isNotEmpty(modelList)) {
            dtoList = modelList.stream().map(dto -> BeanUtil.copyProperties(dto, BmsLogOperationDTO.class)).collect(Collectors.toList());
        }
        return dtoList;
    }

    @Override
    public void addLog(LogTypeEnum logTypeEnum, String code, String memo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        BmsLogOperationModel logVO = new BmsLogOperationModel();
        logVO.setCreatetime(DateUtil.date());
        logVO.setCreateperson(user.getNickname());
        logVO.setEnterpriseId(user.getEnterpriseId());
        logVO.setEnterpriseName(user.getEnterpriseName());
        logVO.setOrderNo(code);
        logVO.setLogMemo(memo);
        logVO.setLogType(logTypeEnum.getCode());
        logOperationMapper.save(logVO);
    }
}
