package com.boot.security.server.service.impl;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.boot.security.server.dao.AdvertDao;
import com.boot.security.server.model.AdvertiserData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.boot.security.server.dao.FileInfoDao;
import com.boot.security.server.model.FileInfo;
import com.boot.security.server.service.FileService;
import com.boot.security.server.utils.FileUtil;

@Service
public class FileServiceImpl implements FileService {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	@Value("${files.path}")
	private String filesPath;
	@Autowired
	private FileInfoDao fileInfoDao;
	@Autowired
	private AdvertDao advertDao;

	@Override
	public FileInfo save(MultipartFile file) throws IOException {
		String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("缺少后缀名");
		}

		String md5 = FileUtil.fileMd5(file.getInputStream());
		FileInfo fileInfo = fileInfoDao.getById(md5);
		if (fileInfo != null) {
			fileInfoDao.update(fileInfo);
			return fileInfo;
		}

		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		String pathname = FileUtil.getPath() + md5 + fileOrigName;
		String fullPath = filesPath + pathname;
		FileUtil.saveFile(file, fullPath);

		long size = file.getSize();
		String contentType = file.getContentType();

		fileInfo = new FileInfo();
		fileInfo.setId(md5);
		fileInfo.setContentType(contentType);
		fileInfo.setSize(size);
		fileInfo.setPath(fullPath);
		fileInfo.setUrl(pathname);
		fileInfo.setType(contentType.startsWith("image/") ? 1 : 0);

		fileInfoDao.save(fileInfo);

		log.debug("上传文件{}", fullPath);

		return fileInfo;

	}

	@Override
	public void delete(String id) {
		FileInfo fileInfo = fileInfoDao.getById(id);
		if (fileInfo != null) {
			String fullPath = fileInfo.getPath();
			FileUtil.deleteFile(fullPath);

			fileInfoDao.delete(id);
			log.debug("删除文件：{}", fileInfo.getPath());
		}
	}

	@Override
	public void saveExel(MultipartFile file) throws IOException {
		Workbook wb = null;
		wb = new XSSFWorkbook(file.getInputStream());
		Sheet sheet = null;
		Row row = null;
		List<AdvertiserData> list = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		DecimalFormat df = new DecimalFormat("#.00");
		if(wb != null){
			//用来存放表中数据
			list = new ArrayList<AdvertiserData>();
			//获取第一个sheet
			sheet = wb.getSheetAt(0);
			//获取最大行数
			int rownum = sheet.getPhysicalNumberOfRows();
			//获取第一行
			row = sheet.getRow(0);
			//获取最大列数
			//int colnum = row.getPhysicalNumberOfCells();
			for (int i = 0; i<rownum; i++) {
				row = sheet.getRow(i);
				if(row !=null){
					Cell cell = row.getCell(0);
					if(cell.getDateCellValue()!=null){
						AdvertiserData advertiserData = new AdvertiserData();
						Date date = cell.getDateCellValue();
						advertiserData.setReportDate(simpleDateFormat.format(date));
						cell = row.getCell(1);
						if(cell.getCellType().equals(CellType.STRING)){
							advertiserData.setCodeId(cell.getStringCellValue());
						}else {
							advertiserData.setCodeId(String.valueOf((int) cell.getNumericCellValue()));
						}
						cell = row.getCell(2);
						advertiserData.setIncome(cell.getNumericCellValue());
						list.add(advertiserData);
					}

				}else{
					break;
				}
			}
		}
		for (AdvertiserData advertiserData : list) {
			AdvertiserData cliExExcel = advertDao.getCliExExcel(advertiserData);
			if(cliExExcel!=null){
				advertiserData.setEcpm(Double.valueOf(df.format(advertiserData.getIncome()/cliExExcel.getExposure()*1000)));
				advertiserData.setCpc(Double.valueOf(df.format(advertiserData.getIncome()/cliExExcel.getClick())));
				advertiserData.setAdvertiserId(cliExExcel.getAdvertiserId());
				advertiserData.setAdvertiserName(cliExExcel.getAdvertiserName());
				advertiserData.setExposure(cliExExcel.getExposure());
				advertiserData.setClick(cliExExcel.getClick());
			}
		}

		advertDao.insertAdvertDataCount(list);
		//根据advert_data_count计算总收入、昨日收入、七日收入、30日收入插入到advertiser_data_count
		List<AdvertiserData> advertiserDataIncome = advertDao.getAdvertiserDataIncome();
		advertDao.insertAdvertiserDataIncome(advertiserDataIncome);
		List<AdvertiserData> advertiserDataTotalIncome = advertDao.getAdvertiserDataTotalIncome();
		advertDao.insertAdvertiserDataTotalIncome(advertiserDataTotalIncome);
		List<AdvertiserData> advertiserDataSevenIncome = advertDao.getAdvertiserDataSevenIncome();
		advertDao.insertAdvertiserDataSevenIncome(advertiserDataSevenIncome);
		List<AdvertiserData> advertiserDataThirtyIncome = advertDao.getAdvertiserDataThirtyIncome();
		advertDao.insertAdvertiserDataThirtyIncome(advertiserDataThirtyIncome);
	}

}
