package com.jwipc.sys.logic.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.aggregation.ModelAggregationService;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.convert.PrintTempConvert;
import com.jwipc.sys.dto.PrintTempBaseDTO;
import com.jwipc.sys.dto.PrintTempListDTO;
import com.jwipc.sys.entity.SysPrintTemp;
import com.jwipc.sys.logic.PrintTempLogic;
import com.jwipc.sys.model.query.PrintTempQuery;
import com.jwipc.sys.service.ISysPrintTempService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class PrintTempLogicImpl implements PrintTempLogic {
    private final ISysPrintTempService sysPrintTempService;
    private final PrintTempConvert printTempConvert;
    private final ModelAggregationService modelAggregationService;

    @Override
    public PageView findByPage(PrintTempQuery query) {
        final Page<SysPrintTemp> page = PageUtil.toPage(query);
        final List<SysPrintTemp> list = sysPrintTempService.list(page);

        final List<PrintTempListDTO> record = printTempConvert.convert1(list);
        modelAggregationService.processRelationAggregation(record);
        return PageUtil.getPV(record, page.getTotal());
    }

    @Override
    public void saveOrUpdate(PrintTempBaseDTO saveOrUpdate) {
        SysPrintTemp sysPrintTemp = printTempConvert.convert2(saveOrUpdate);

        if (sysPrintTemp.getId() == null) {
            saveOrUpdate.setCreateId(LoginUtil.getUserId());
            saveOrUpdate.setUpdateId(LoginUtil.getUserId());
            saveOrUpdate.setCreateTime(LocalDateTime.now());
            saveOrUpdate.setUpdateTime(LocalDateTime.now());
            sysPrintTempService.save(sysPrintTemp);
        } else {
            saveOrUpdate.setUpdateId(LoginUtil.getUserId());
            saveOrUpdate.setUpdateTime(LocalDateTime.now());
            sysPrintTempService.updateById(sysPrintTemp);
        }
    }

    @Override
    public PrintTempBaseDTO getDetail(Long id) {
        final SysPrintTemp byId = sysPrintTempService.getById(id);
        if(Objects.isNull(byId)){
            return new PrintTempBaseDTO();
        }
        return printTempConvert.convert3(byId);
    }

    @Override
    public void del(Long id) {
        sysPrintTempService.removeById(id);
    }
}