package com.liangjian.dataplatform.member.service.impl;

import com.liangjian.dataplatform.member.dao.primary.LayoutConfigRepository;
import com.liangjian.dataplatform.member.entity.po.primary.LayoutConfig;
import com.liangjian.dataplatform.member.entity.vo.LayoutConfigVo;
import com.liangjian.dataplatform.member.service.ILayoutConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: 黄子奇
 * @Date: 2019/9/26 14:19
 */
@Service
public class LayoutConfigService implements ILayoutConfigService {
    @Autowired
    private LayoutConfigRepository layoutConfigRepository;

    @Override
    public LayoutConfigVo queryOne() {
        List<LayoutConfig> list = layoutConfigRepository.getOne(PageRequest.of(0,1));
        if(list.isEmpty()) {
            return null;
        } else {
            return LayoutConfigVo.transfer(list.get(0));
        }
    }

    @Override
    public boolean updateOne(LayoutConfigVo vo) {
        LayoutConfigVo fromDb = queryOne();
        vo.setUpdateDate(new Date());
        if(vo.getName() != null && !vo.getName().equalsIgnoreCase("index")) {
            try{
                LayoutConfig po = LayoutConfigVo.reTransfer(vo);
                layoutConfigRepository.save(po);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        } else {
            try {
                if (fromDb == null) {
                    LayoutConfig po = LayoutConfigVo.reTransfer(vo);
                    layoutConfigRepository.save(po);
                    return true;
                } else {
                    vo.setId(fromDb.getId());
                    LayoutConfig po = LayoutConfigVo.reTransfer(vo);
                    layoutConfigRepository.save(po);
                    return true;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        }
    }

    @Override
    public LayoutConfigVo getConfig(String name) {
        LayoutConfig layoutConfig = layoutConfigRepository.queryByName(name);
        if(layoutConfig == null ){
            return null;
        } else {
            return LayoutConfigVo.transfer(layoutConfig);
        }
    }
}
