package com.cku.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import com.cku.core.PageBeanResult;
import com.cku.dao.CkuAdminMapper;
import com.cku.dao.CkuCaiPanMapper;
import com.cku.dao.CkuImageMapper;
import com.cku.dao.CkuMatchHotelMapper;
import com.cku.dao.CkuMatchHotelRelationMapper;
import com.cku.dao.CkuMatchMapper;
import com.cku.dao.CkuMatchVenueMapper;
import com.cku.model.CkuAdmin;
import com.cku.model.CkuCaiPan;
import com.cku.model.CkuImage;
import com.cku.model.CkuMatch;
import com.cku.model.CkuMatchHotel;
import com.cku.model.CkuMatchHotelRelation;
import com.cku.model.CkuMatchVenue;
import com.cku.model.CkuMatchWithBLOBs;
import com.cku.upyun.ImageFtp;
import com.cku.util.PageBean;

@Service("ckuAdminService")
public class CkuAdminServiceImpl {
	@Autowired
	public CkuAdminMapper ckuAdminMapper;
	@Autowired
	public CkuImageMapper ckuImageMapper;
	@Autowired
	public CkuMatchMapper ckuMatchMapper;
	@Autowired
	public CkuMatchHotelMapper ckuMatchHotelMapper;
	@Autowired
	public CkuMatchHotelRelationMapper ckuMatchHotelRelationMapper;
	@Autowired
	public CkuMatchVenueMapper ckuMatchVenueMapper;
	@Autowired
	public CkuCaiPanMapper ckuCaiPanMapper;
	/**
	 * 统一处理赛事配图sql
	 * @param tableType
	 * @param keyword
	 * @param pb
	 * @return
	 */
	public PageBeanResult<CkuAdmin> getList(String tableType,String keyword, PageBean pb){
		PageBeanResult<CkuAdmin> pbr = new PageBeanResult<CkuAdmin>();
		String tableName = "";
		String columnName = "";
		StringBuffer listSql = new StringBuffer();
		StringBuffer countSql = new StringBuffer();
		if("ckuMatch".equals(tableType)){
			tableName = "( select min(id) AS id,赛事地点 as name "+
			"from tab_games "+
			"GROUP BY 赛事地点  ) ckuMatch";
			columnName = "name";
		}else if("ckuMatchHotel".equals(tableType)){
			tableName = "cku_match_hotel";
			columnName = "hotel_name";
		}else if("ckuMatchVenue".equals(tableType)){
			tableName = "cku_match_venue";
			columnName = "venue_name";
		}else if("ckuDogClass".equals(tableType)){
			tableName = "tab_dog_class_code";
			columnName = "犬种类中文名称";
		}else if("ckuCaiPan".equals(tableType)){
			tableName = "cku_caipan";
			columnName = "cku_title";
		}else if ("gameTimeTab".equals(tableType)){
			tableName = "( select min(id) AS id,赛事地点 as name "+
			"from tab_games "+
			"GROUP BY 赛事地点  ) ckuMatch";
			columnName = "name";
		}else if("ckuTopMatch".equals(tableType)){
			tableName="(select min(id) as id,[赛事地点] as name from tab_games where istop='1' GROUP BY [赛事地点]) ckuTopMatch";
			columnName="name";
		}
		buildSql(listSql,countSql,tableName,keyword,columnName,pb);
		List<CkuAdmin> list =ckuAdminMapper.getList(listSql.toString());
		for(int i=0;i<list.size();i++ ){
			Long id = list.get(i).getId();
			List<CkuImage> ciList = getImage(tableType,id);
			list.get(i).setImageCount((long)ciList.size());
		}
		pbr.list = list;
		pbr.totalCount = ckuAdminMapper.getCount(countSql.toString());

		return pbr;
	}

	/**
	 * 赛事配置查询list
	 * @param keyword
	 * @param pb
     * @return
     */
	public PageBeanResult<CkuMatch> getMatchList(String keyword, PageBean pb){
		PageBeanResult<CkuMatch> pbr = new PageBeanResult<CkuMatch>();
		List<CkuMatch> list = ckuMatchMapper.getMatchList(keyword,pb.get_limit(),pb.get_start());
		Long count = ckuMatchMapper.getMatchCount(keyword);
		pbr.list = list;
		pbr.totalCount = count;
		return pbr;
	}
	/**
	 * 得到相应的  赛事酒店，赛事场馆，赛事裁判
	 * @param type
	 * @param matchId
	 * @return
	 */
	public List<CkuAdmin> getDetail(int type,int matchId){
		List<CkuAdmin> resultList = new ArrayList<CkuAdmin>();
		CkuMatch cm= ckuMatchMapper.getMatchById((long)matchId);
		if(type==0){
			List<CkuMatchHotel> hotelList = ckuMatchHotelMapper.getHotel(cm.getShowLocation());
			if(hotelList.size()>0){
				for(CkuMatchHotel cmh :hotelList){
					resultList.add(new CkuAdmin((long)cmh.getId(),cmh.getHotelName(),cmh.getHotelAddress()));
				}
			}
		}else if(type==1){
			if(cm.getVenueId()!=null){
				CkuMatchVenue venue = ckuMatchVenueMapper.selectByPrimaryKey((long)cm.getVenueId());
				resultList.add(new CkuAdmin((long)venue.getId(),venue.getVenueName(),venue.getVenueAddress()));
			}
		}else if(type==2){
			List<CkuCaiPan> caiPanList = ckuCaiPanMapper.getRefereeMessage(cm.getCkuCaipanid());
			if(caiPanList.size()>0){
				for(CkuCaiPan cp :caiPanList){
					//resultList.add(new CkuAdmin((long)cp.getId(),cp.getCkuTitle(),cp.getCkuPosition()));
				}
			}
		}
		return resultList;
	}
	/**
	 * 根据赛事id添加  相应的赛事酒店，赛事场馆，赛事裁判
	 */
	public int addDetail(int type,int matchId,int detailId){
		int result = 0;
		CkuMatch cm= ckuMatchMapper.getMatchById((long)matchId);
		if(type==0){
			CkuMatchHotelRelation record = new CkuMatchHotelRelation();
			record.setMatchId(cm.getId());
			record.setShowLocation(cm.getShowLocation());
			record.setHotelId(detailId);
			result = ckuMatchHotelRelationMapper.insertSelective(record);
		}else if(type==1){
			cm.setVenueId(detailId);
			result = ckuMatchMapper.updateOfAdmin(cm);
		}else if(type==2){
			String dbcpid = cm.getCkuCaipanid();
			if(dbcpid==null || "".equals(dbcpid)){
				dbcpid = detailId+"";
			}else{
				dbcpid = dbcpid+","+detailId;
			}
			cm.setCkuCaipanid(dbcpid);
			result = ckuMatchMapper.updateOfAdmin(cm);
		}
		return result;
	}
	/**
	 * 根据赛事id删除  相应的赛事酒店，赛事场馆，赛事裁判
	 */
	public int delDetail(int type,int matchId,int detailId){
		int result = 0;
		CkuMatch cm= ckuMatchMapper.getMatchById((long)matchId);
		if(type==0){
			result = ckuMatchHotelRelationMapper.deleteByMatchIdAndHotelId(matchId,detailId);
		}else if(type==1){
			cm.setVenueId(null);
			result = ckuMatchMapper.updateOfAdmin(cm);
		}else if(type==2){
			String interId = "";
			String dbcpid = cm.getCkuCaipanid();
			String[] dbcpArr = dbcpid.split(",");
			for(int i=0;i<dbcpArr.length;i++){
				if(!(detailId+"").equals(dbcpArr[i])){
					if("".equals(interId)){
						interId = dbcpArr[i];
					}else{
						interId = interId+","+dbcpArr[i];
					}
				}
			}
			cm.setCkuCaipanid(interId);
			result = ckuMatchMapper.updateOfAdmin(cm);
		}
		return result;
	}
	public List<CkuImage> getImage(String tableType,Long id){
		StringBuffer sql = new StringBuffer();
		if("ckuMatch".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN tab_games tg ON ci.remarks = tg.[赛事地点] WHERE tg.id="+id);
		}else if("ckuMatchHotel".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN cku_match_hotel tg ON ci.match_hotel_id = tg.id WHERE tg.id="+id);
		}else if("ckuMatchVenue".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN cku_match_venue tg ON ci.match_venue_id = tg.id WHERE tg.id="+id);
		}else if("ckuDogClass".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN tab_dog_class_code tg ON ci.dog_class_id = tg.id WHERE tg.id="+id);
		}else if("ckuCaiPan".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN cku_caipan tg ON ci.match_referee_id = tg.id WHERE tg.id="+id);
		}else if("gameTimeTab".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN tab_games tg ON ci.showLocation = tg.[赛事地点] WHERE tg.id="+id);
		}else if("ckuTopMatch".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN tab_games tg ON ci.showLocation_istop = tg.id WHERE tg.id="+id);
		}
		List<CkuImage> list = ckuImageMapper.selectByColumn(sql.toString());
		return list;
	}
	public void delImage(Integer id){
		//http://chongaibao.b0.upaiyun.com/cab_test/image/image/19_1_1460000890422.jpg
		CkuImage ckuImage = ckuImageMapper.selectByPrimaryKey(id);
		if(ckuImage.getImageMinUrl()!=null && !"".equals(ckuImage.getImageMinUrl())){
			if(ckuImage.getImageMinUrl().indexOf(ImageFtp.UPYUNWEBURL)==0){
				ImageFtp.deleteFile(ckuImage.getImageMinUrl().replace(ImageFtp.UPYUNWEBURL, ""));
			}
		}
		if(ckuImage.getImageMaxUrl()!=null && !"".equals(ckuImage.getImageMaxUrl())){
			if(ckuImage.getImageMaxUrl().indexOf(ImageFtp.UPYUNWEBURL)==0){
				ImageFtp.deleteFile(ckuImage.getImageMaxUrl().replace(ImageFtp.UPYUNWEBURL, ""));
			}
		}
		ckuImageMapper.deleteByPrimaryKey(id);
	}
	public CkuImage saveImageDB(String tableType,String typeId,String resultOra,String resultMin){
		CkuImage ckuImage = new CkuImage();
		ckuImage.setImageMaxUrl(resultOra);
		ckuImage.setImageMinUrl(resultMin);
		ckuImage.setCreateTime(new Date());
		if("ckuMatch".equals(tableType)){
			CkuMatch cm = ckuMatchMapper.getMatchById(Long.parseLong(typeId));
			ckuImage.setRemarks(cm.getShowLocation());
		}else if("ckuMatchHotel".equals(tableType)){
			ckuImage.setMatchHotelId(Integer.parseInt(typeId));
		}else if("ckuMatchVenue".equals(tableType)){
			ckuImage.setMatchVenueId(Integer.parseInt(typeId));
		}else if("ckuDogClass".equals(tableType)){
			ckuImage.setDogClassId(Integer.parseInt(typeId));
		}else if("ckuCaiPan".equals(tableType)){
			ckuImage.setMatchRefereeId(Integer.parseInt(typeId));		
		}else if("gameTimeTab".equals(tableType)){
			CkuMatch cm = ckuMatchMapper.getMatchById(Long.parseLong(typeId));
			ckuImage.setShowLocation(cm.getShowLocation());
		}else if("ckuTopMatch".equals(tableType)){
			ckuImage.setShowLocationIsTop(typeId);
		}
		int i = ckuImageMapper.insertSelective(ckuImage);
		if(i>0){
			return ckuImage;
		}
		return null;
	}
	//通用构建sql
	public void buildSql(StringBuffer listSql,StringBuffer countSql,String tableName,String keyword,String columnName,PageBean pb){
		//list
		listSql.append("select top "+pb.get_limit()+" id,"+columnName+" as name");
		listSql.append(" from "+tableName);
		listSql.append(" where id not in (");
				listSql.append(" select top "+pb.get_start()+" id from "+tableName);
				if(keyword!=null && !"".equals(keyword)){
					listSql.append(" where "+columnName+" like '%"+keyword+"%'");
				}
				listSql.append(" order by id desc)");
				if(keyword!=null && !"".equals(keyword)){
					listSql.append(" and "+columnName+" like '%"+keyword+"%'");
				}
				listSql.append(" ORDER BY id desc");
		//count
		countSql.append("select count(*) as countNum from "+tableName);
		if(keyword!=null && !"".equals(keyword)){
			countSql.append(" where "+columnName+" like '%"+keyword+"%'");
		}
	}
	@Transactional
	public int instertMatchXls(CkuMatchWithBLOBs cm){
		return ckuMatchMapper.insertSelective(cm);
		
	}
}
