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

import com.liangjian.dataplatform.member.dao.primary.FeatureLogRepository;
import com.liangjian.dataplatform.member.entity.po.primary.FeatureInfo;
import com.liangjian.dataplatform.member.entity.po.primary.FeatureLog;
import com.liangjian.dataplatform.member.service.IFeatureInfoService;
import com.liangjian.dataplatform.member.service.IFeatureLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: 黄子奇
 * @Date: 2019/9/24 14:44
 */
@Service
public class FeatureLogService implements IFeatureLogService {
    @Autowired
    private FeatureLogRepository featureLogRepository;
    @Autowired
    private IFeatureInfoService iFeatureInfoService;

    @Override
    public Page<FeatureLog> queryByInfoId(String infoId, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size, Sort.Direction.DESC,"updateDate");
        return featureLogRepository.queryByInfoId(infoId,pageable);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean addFeatureLog(FeatureLog log) {
        if(log.getInfoId() == null || log.getInfoId().isEmpty()) {
            return false;
        }
        try {
            String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String version = log.getVersion() + "." + dateStr;
            log.setVersion(version);
            log.setUpdateDate(new Date());
            featureLogRepository.saveWithCycle(log);

            FeatureInfo info = iFeatureInfoService.queryById(log.getInfoId());
            info.setLastUpdate(new Date());
            String desc = info.getDescrition() + "\n" + log.getUpdateDesc();
            info.setDescrition(desc);
            info.setVersion(version);
            iFeatureInfoService.saveFeaturesInfo(info);

            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteFeatureLog(String id) {
        try{
            featureLogRepository.deleteById(id);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
