package com.cku.service;

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 id AS id,show_location as name, closing_time closing_time "+
			"from show_main "+
			") 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 = "dog_type";
			columnName = "breed_cn_name";
		}else if("ckuCaiPan".equals(tableType)){
			tableName = "show_judge";
			columnName = "judge_name";
		}else if ("gameTimeTab".equals(tableType)){
			tableName = "( select id AS id,show_location as name "+
			"from show_main "+
			" ) ckuMatch";
			columnName = "name";
		}else if("ckuTopMatch".equals(tableType)){
			tableName="(select id as id,show_location as name from show_main where isTop='1') ckuTopMatch";
			columnName="name";
		}
		buildSql(listSql,countSql,tableName,keyword,columnName,pb,tableType);
		List<CkuAdmin> list =ckuAdminMapper.getList(listSql.toString());
		for(int i=0;i<list.size();i++ ){
			String 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,String matchId){
		List<CkuAdmin> resultList = new ArrayList<CkuAdmin>();
		CkuMatch cm= ckuMatchMapper.getMatchById(matchId);
		if(type==0){
			List<CkuMatchHotel> hotelList = ckuMatchHotelMapper.getHotel(cm.getShowLocation());
			if(hotelList.size()>0){
				for(CkuMatchHotel cmh :hotelList){
					resultList.add(new CkuAdmin(cmh.getId().toString(),cmh.getHotelName(),cmh.getHotelAddress()));
				}
			}
		}else if(type==1){
			if(cm.getVenueId()!=null){
				CkuMatchVenue venue = ckuMatchVenueMapper.selectByPrimaryKey(Long.valueOf(cm.getVenueId()));
				resultList.add(new CkuAdmin(venue.getId().toString(),venue.getVenueName(),venue.getVenueAddress()));
			}
		}else if(type==2){
			List<CkuCaiPan> caiPanList = new ArrayList<CkuCaiPan>();
			if(cm.getCkuCaipanid()!=null && !"".equals(cm.getCkuCaipanid())){
				caiPanList = ckuCaiPanMapper.getRefereeMessage(cm.getCkuCaipanid());
			}
			if(caiPanList.size()>0){
				for(CkuCaiPan cp :caiPanList){
					resultList.add(new CkuAdmin(cp.getId().toString(),cp.getCkuTitle(),cp.getCkuPosition()));
				}
			}
		}
		return resultList;
	}
	/**
	 * 根据赛事id添加  相应的赛事酒店，赛事场馆，赛事裁判
	 */
	public int addDetail(int type,String matchId,String detailId){
		int result = 0;
		CkuMatch cm= ckuMatchMapper.getMatchById(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,String matchId,String detailId){
		int result = 0;
		CkuMatch cm= ckuMatchMapper.getMatchById(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,String id){
		StringBuffer sql = new StringBuffer();
		if("ckuMatch".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN show_main tg ON ci.remarks = tg.show_location 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 dog_type 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 show_judge 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 show_main tg ON ci.showLocation = tg.show_location WHERE tg.id="+"'"+id+"'");
		}else if("ckuTopMatch".equals(tableType)){
			sql.append("SELECT ci.* FROM cku_image ci LEFT JOIN show_main 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(typeId);
			ckuImage.setRemarks(cm.getShowLocation());
		}else if("ckuMatchHotel".equals(tableType)){
			ckuImage.setMatchHotelId(typeId);
		}else if("ckuMatchVenue".equals(tableType)){
			ckuImage.setMatchVenueId(typeId);
		}else if("ckuDogClass".equals(tableType)){
			ckuImage.setDogClassId(typeId);
		}else if("ckuCaiPan".equals(tableType)){
			ckuImage.setMatchRefereeId(typeId);		
		}else if("gameTimeTab".equals(tableType)){
			CkuMatch cm = ckuMatchMapper.getMatchById(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,String tableType){
		//list
		listSql.append("select id,"+columnName+" as name");
		listSql.append(" from "+tableName);
				if(keyword!=null && !"".equals(keyword)){
					listSql.append(" where "+columnName+" like '%"+keyword+"%'");
				}
				if("ckuMatch".equals(tableType)){
					listSql.append(" ORDER BY closing_time DESC ");
				} else {
					listSql.append(" ORDER BY id desc ");
				}
				listSql.append("limit "+pb.get_start()+","+pb.get_limit());
		//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);
		
	}
}
