package com.pqs9000.serviceimpl.report;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.njcn.mapper.configuration.ReportMapper;
import com.njcn.mapper.configuration.ReportModelMapper;
import com.njcn.pojo.configuration.Report;
import com.njcn.pojo.configuration.ReportModel;
import com.njcn.shiro.token.TokenManager;
import com.njcn.sso.pojo.user.User;
import com.pqs9000.service.report.DeviceReportService;

@Service
public class DeviceReportServiceImpl implements DeviceReportService {
    @Autowired
    ReportModelMapper reportModelMapper;
    
    @Autowired
    ReportMapper reportMapper;
    
	@Override
	public String saveModel(String name){
		ReportModel model = new ReportModel();
		model.setModelIndex(UUID.randomUUID().toString());
		model.setModelName(name);
		model.setState(1);
		model.setUpdatetime(new Date());
		try{
			int falg = reportModelMapper.insert(model);
			return "success";
		}catch (Exception e) {
    		return "fail";
		}
	}
	
	@Override
	public String saveReport(String name){
		User user = TokenManager.getToken();
		
		Report tmp = new Report();
		tmp = reportMapper.testName(name);
		if(tmp != null){
			tmp.setSavetime(new Date());
			tmp.setUserIndex(user.getUserIndex());

			try{
				int flag = reportMapper.updateData(tmp);
				return "success";
			}catch (Exception e) {
				return "fail";
			}
		}else{
			Report report = new Report();
			report.setReportIndex(UUID.randomUUID().toString());
			report.setReportName(name);
			report.setSavetime(new Date());
			report.setUserIndex(user.getUserIndex());
			report.setUpdatetime(null);
			report.setUpuserIndex(null);
			
			try{
				int flag = reportMapper.insertData(report);
				return "success";
			}catch (Exception e) {
				return "fail";
			}
		}
	}
	
	@Override
	public String updateReport(String reportIndex,String reportName){
		Report report = new Report();
		report = reportMapper.selectByPrimaryKey(reportIndex);
		
		if(report == null){
			return "fail";
		}else{
			report.setUpdatetime(new Date());
			User user = TokenManager.getToken();
			report.setUpuserIndex(user.getUserIndex());

			try {
				int flag = reportMapper.updateByPrimaryKey(report);
				return "success";
			} catch (Exception e) {
				return "fail";
			}
		}
	}
}