package com.cku.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.cku.core.PageBeanResult;
import com.cku.core.RESTResponse;
import com.cku.model.CkuAdmin;
import com.cku.model.CkuCaiPan;
import com.cku.model.CkuImage;
import com.cku.model.CkuMatch;
import com.cku.model.CkuMatchWithBLOBs;
import com.cku.service.CkuAdminServiceImpl;
import com.cku.service.CkuCaiPanServiceImpl;
import com.cku.upyun.ImageFtp;
import com.cku.util.PageBean;
import com.cku.util.ServletUtils;
@Controller
@RequestMapping(value="admin")
public class CkuAdminController {
	private static final Logger logger = Logger.getLogger(CkuAdminController.class);
	@Autowired
	public CkuAdminServiceImpl ckuAdminService;
	
	@Autowired
	public CkuCaiPanServiceImpl CaiPanService;
	
	/**
	 * 得到list lyy
	 * @param response
	 * @param request
	 * @throws IOException 
	 */
	@RequestMapping(value = "/list")
	public void getList(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			String keyword = ServletUtils.getParameter(request, "keyword",null);
			String tableName = ServletUtils.getParameter(request, "table",null);
			PageBean pb = ServletUtils.getParameterBean(request);
			PageBeanResult<CkuAdmin> pbr = ckuAdminService.getList(tableName,keyword, pb);
			result = new RESTResponse("items", pbr);
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	@RequestMapping(value = "/matchList")
	public void matchList(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			String keyword = ServletUtils.getParameter(request, "keyword",null);
			PageBean pb = ServletUtils.getParameterBean(request);
			PageBeanResult<CkuMatch> pbr = ckuAdminService.getMatchList(keyword, pb);
			result = new RESTResponse("items", pbr);
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 根据赛事id得到 相应的赛事酒店，赛事场馆，赛事裁判List
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/getDetail")
	public void getDetail(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			int type = ServletUtils.getParameterInt(request, "type",0);
			int matchId = ServletUtils.getParameterInt(request, "matchId");
			List<CkuAdmin> list = ckuAdminService.getDetail(type,matchId);
			result = new RESTResponse("items", list);
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 根据赛事id删除  相应的赛事酒店，赛事场馆，赛事裁判
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/delDetail")
	public void delDetail(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			int type = ServletUtils.getParameterInt(request, "type",0);
			int matchId = ServletUtils.getParameterInt(request, "matchId");
			int detailId = ServletUtils.getParameterInt(request, "detailId");
			int delResult = ckuAdminService.delDetail(type,matchId,detailId);
			result = new RESTResponse("items", delResult);
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 根据赛事id添加  相应的赛事酒店，赛事场馆，赛事裁判
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping(value = "/addDetail")
	public void addDetail(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			int type = ServletUtils.getParameterInt(request, "type",0);
			int matchId = ServletUtils.getParameterInt(request, "matchId");
			int detailId = ServletUtils.getParameterInt(request, "detailId");
			int addResult = ckuAdminService.addDetail(type,matchId,detailId);
			result = new RESTResponse("items", addResult);
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 得到image lyy
	 * @param response
	 * @param request
	 * @throws IOException 
	 */
	@RequestMapping(value = "/getImage")
	public void getImage(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			Long id = ServletUtils.getParameterLong(request, "id");
			String tableName = ServletUtils.getParameter(request, "table",null);
			List<CkuImage> list = ckuAdminService.getImage(tableName,id);
			result = new RESTResponse("items", list);
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	@RequestMapping(value = "/delImage")
	public void delImage(HttpServletResponse response, HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try{
			Integer id = ServletUtils.getParameterInt(request, "id");
			ckuAdminService.delImage(id);
			result = new RESTResponse("items", "");
		}catch (Exception e){
			result = new RESTResponse(e);
			logger.error(e);
		}
		ServletUtils.writeResponse(response, result);
	}
	@RequestMapping(value = "/saveLocalImage")
	public void saveLocalImage(HttpServletRequest request, HttpServletResponse response,
							@RequestParam(value = "file",required = false) MultipartFile file,
							@RequestParam(value = "type",required = false) String type,
							@RequestParam(value = "typeId",required = false) String typeId) throws IllegalStateException, IOException{
		RESTResponse result = null;
		String fileName = file.getOriginalFilename();
		int lastIndex = fileName.lastIndexOf(".");
		String fileNameEnd = fileName.substring(lastIndex);
//		String localPath = request.getRealPath("/userfiles/localImage");
		String newFileName = UUID.randomUUID()+fileNameEnd;
//		String filePath = localPath+File.separator+newFileName;
//		System.out.println(filePath);
//		File localFile = new File(filePath);
//		file.transferTo(localFile);
		//return newFileName;
		String resultOra = "";
		String resultMin = "";
		try {
			resultOra = ImageFtp.uploadBytes(ImageFtp.IMAGE_PATH_TEST, newFileName, file.getBytes());
			resultMin = ImageFtp.uploadGmkerlBytes(ImageFtp.IMAGE_PATH_TEST, newFileName, file.getBytes());
			CkuImage ci = ckuAdminService.saveImageDB(type,typeId,resultOra,resultMin);
			result = new RESTResponse("items", ci);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ServletUtils.writeResponse(response, result);
	}

	@RequestMapping(value = "/uploadXls")
	public void uploadXls(HttpServletRequest request, HttpServletResponse response,
							   @RequestParam(value = "file",required = false) MultipartFile file,
							   @RequestParam(value = "type",required = false) String type,
							   @RequestParam(value = "tableName",required = false) String tableName) throws IllegalStateException, IOException, ParseException {
		RESTResponse result = null;
		XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
		//得到sheet
		XSSFSheet sheet = wb.getSheetAt(0);
		//总行数
		int rowCount = sheet.getLastRowNum()+1;
		XSSFRow row0 = sheet.getRow(0);
		//总列数  
		short colCount = row0.getLastCellNum();
		boolean headFlag = true;
		//TODO  校验标头
		String[] headerName = new String[]{"举办方式","主办单位","赛制","赛事编号","参赛费","赛事开始日期","赛事结束日期","赛事名称","赛事地点","报名截止日期","比赛报名","主赛事名称","场次明细","犬只报名上限","裁判阵容"};
		for(int k=0;k<colCount;k++){
			Cell cell = row0.getCell(k);
			if(cell!=null){
				cell.setCellType(Cell.CELL_TYPE_STRING);
				if(!headerName[k].equals(cell.getStringCellValue().trim())){
					headFlag = false;
					break;
				}
			}
		}
		if(!headFlag){
			result = new RESTResponse(-1,"模板标题不匹配！");
			ServletUtils.writeResponse(response, result);
			return;
		}
		int successCount = 0;
		HashMap<String,Integer> map = new HashMap<String,Integer>();
		for(int j=1;j<rowCount;j++){
			XSSFRow rowNext = sheet.getRow(j);
			CkuMatchWithBLOBs cm= new CkuMatchWithBLOBs();
			cm.setAddData(new Date());
			boolean isInsertFlag = true;
			for(int v=0;v<colCount;v++){
				Cell cell = rowNext.getCell(v);
				if(cell!=null){
					if(v==0){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setGametype(cell.getStringCellValue());
					}else if(v==1){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setOrganizer(cell.getStringCellValue());
					}else if(v==2){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setShowsystem(cell.getStringCellValue());
					}else if(v==3){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setShowNum(cell.getStringCellValue());
					}else if(v==4){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setBmfei(new BigDecimal(cell.getStringCellValue()));
					}else if(v==5){
						cm.setStartingData(cell.getDateCellValue());
					}else if(v==6){
						cm.setEndingData(cell.getDateCellValue());
					}else if(v==7){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setShowName(cell.getStringCellValue());
					}else if(v==8){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setShowLocation(cell.getStringCellValue());
					}else if(v==9){
						if(cell.getDateCellValue()==null){
							isInsertFlag = false;
						}
						cm.setCkuEndtime(cell.getDateCellValue());
					}else if(v==10){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setShowEnrolment(cell.getStringCellValue());
					}else if(v==11){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setMainGameName(cell.getStringCellValue());
					}else if(v ==12){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setShowsDetail(cell.getStringCellValue());
					}else if(v ==13){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setTopDog(cell.getStringCellValue());
					}else if(v ==14){
						cell.setCellType(Cell.CELL_TYPE_STRING);
						cm.setCkuCaipanid(cell.getStringCellValue());
					}
				}
			}
			if(isInsertFlag){
				successCount += ckuAdminService.instertMatchXls(cm);
			}
			
		}
		map.put("successCount", successCount);
		map.put("errorCount", rowCount-successCount-1);
		result = new RESTResponse("items",map);
		//TODO  向数据库插入数据  （统计导入成功行数，导入错误行数，总行数）

		ServletUtils.writeResponse(response, result);
	}
	@RequestMapping(value="/upImg")
	public void upImg() throws IOException, InterruptedException{
		String path = "";
		String resultOra = "";
		String resultMin = "";
		List<CkuCaiPan> caipan = CaiPanService.getCaiPan();
		for (int j = 0; j < caipan.size(); j++) {
			path = "/home/admin/caipan/"+caipan.get(j).getCkuPicture();
			File file = new File(path);
			FileImageInputStream input = null;
			if(file.exists()){
				/*byte[] data = null;
				input = new FileImageInputStream(new File(path));
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				byte[] buf = new byte[1024];
				int numBytesRead = 0;
				numBytesRead = input.read(buf);
				output.write(buf, 0, numBytesRead);
				data = output.toByteArray();*/
				String name = file.getName();
				
				//----
				BufferedImage image = ImageIO.read(new FileInputStream(path)); //用ImageIO将本地图片文件转换成虚拟图片信息

				ByteArrayOutputStream bos = new ByteArrayOutputStream();      //字节输出流

				ImageIO.write(image, "bmp", bos);      //将虚拟图片信息写入到字节输出流中

				byte[] b = bos.toByteArray();//generate byte[] 
				//----
				
				resultOra = ImageFtp.uploadBytes("cab_test/image/caipan", name, b);
				resultMin = ImageFtp.uploadGmkerlBytes("cab_test/image/caipan", name, b);
				System.out.println(resultOra);
				CkuImage ci = ckuAdminService.saveImageDB("ckuCaiPan",caipan.get(j).getId().toString(),resultOra,resultMin);
				System.out.println("已执行》》》》》》》》》》》》》》》》");
				Thread.sleep(3000);
			}
		}
	}


}
