package com.ssj.service.weixin.library.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.sys.imlibuser.TbClass;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.libmy.domain.TbLibManagerAudit;
import com.ssj.dao.weixin.library.dao.ILibJoinDao;
import com.ssj.dao.weixin.library.dao.ILibJoinQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.HttpRemote;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.service.sys.imlibuser.service.TbClassService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.LibManagerAuditService;
import com.ssj.service.weixin.sales.service.LibBorrowedServiceService;
import com.ssj.service.weixin.sales.service.LibCommissionService;
import com.ssj.service.weixin.sales.service.LibSalesPriceService;
import com.ssj.service.weixin.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;

@Service
@Transactional
public class LibJoinServiceImpl extends BaseServiceImpl<TbLibJoin, String> implements ILibJoinService{
	@Autowired
	private ILibJoinDao  libJoinDao;
	@Autowired
	private ILibJoinQueryDao  libJoinQueryDao;
	@Autowired
	private TokenManager  tokenManager;
	@Autowired
	private UserService userService;

	@Autowired
	private LibSalesPriceService libSalesPriceService;

	@Autowired
	private LibCommissionService libCommissionService;

	@Autowired
	private LibBorrowedServiceService libBorrowedServiceService;

	@Autowired
	private TbClassService tbClassService;

	@Autowired
	private IBookManagerService managerService;

	@Autowired
	private LibManagerAuditService auditService;
	 
	 
	@Override
	public PagingAndSortingRepository<TbLibJoin, String> getDao() {
		return libJoinDao;
	}

	@Override
	public Page<TbLibJoin> findByPage(Map<String, Object> params, Pageable sp) {
		   Map<String, SearchFilter> filters = SearchFilter.parse(params);
			Specification<TbLibJoin> specification = DynamicSpecifications.bySearchFilter(filters.values(), TbLibJoin.class);    
			return  libJoinDao.findAll(specification, sp);
	}

	@Override
	public Page<Map<String, Object>> findForPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libJoinQueryDao.findForPage(searchParams, pageable);
	}

	@Override
	public void libManagerDelete(String id,int type) {
		libJoinDao.libManagerDelete(id);
		if(type == 4){
			//删除audit 记录
			libJoinDao.libAuditDelete(id);
		}
	}

	@Override
	public void addAdmin(String[] ids, String libId ,Integer type,String mobiles[],String names[]) {
		if(ids.length>0){
			Date now = new Date();
			TbLibJoin join =  this.getById(libId);
			for (int i = 0; i < ids.length; i++) {
				String userId = ids[i];
				libJoinDao.libManagerDeleteIn(libId, userId,type);
				TbLibManager  tb = new  TbLibManager();
				tb.setLibId(libId);
				tb.setUserId(userId);
				tb.setType(type);
				tb.setName(names[i]==null?userService.getById(userId).getName():names[i]);
				if(StringUtil.isNotEmpty(mobiles[i])){
					tb.setTelephone(mobiles[i]);
				}

				tb.setCreateTime(now);
				tb.setLibtype(join.getLibtype()>1?2:1);
				tb.setState(1);
				tb = managerService.save(tb);
				if(type==1){
					userId="JIEYUE"+userId;//图书借阅
		         }else if(type==2){
		        	 userId ="ZUOYB"+userId;//作业吧
		         }else if(type==3){
		        	 userId ="XUEBA"+userId; //学霸老师
		         }else{
		        	 userId ="CD"+userId;
		         }
				if(type==4){
					//校长，插入audit记录
					TbLibManagerAudit  audit = new  TbLibManagerAudit();
					audit.setStatus(1);
					audit.setTelephone(tb.getTelephone());
					audit.setLibManagerId(tb.getId());
					audit.setLibId(tb.getLibId());
					audit.setType(tb.getType());
					audit.setCreateTime(now);
					audit.setLastUpdateTime(now);
					audit.setUserId(tb.getUserId());
					audit.setName(tb.getName());
					//BeanUtils.copyProperties(tb,audit);
					auditService.save(audit);
				}
				 tokenManager.createManageType(userId,libId);
				 tokenManager.delToken(userId);
			}
			//libJoinQueryDao.insertTbLibManager(list);
		}
	}

	@Override
	public Page<Map<String, Object>> findBookDetailForPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libJoinQueryDao.findBookDetailForPage(searchParams, pageable);
	}

	@Override
	public Page<Map<String, Object>> findForVIPPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libJoinQueryDao.findForVIPPage(searchParams, pageable);
	}

	@Override
	public List<Map<String, Object>> getAllSchoolMap(Map<String, Object> params) {
		return libJoinQueryDao.getAllSchoolMap(params);
	}

	@Override
	public List<TbLibJoin> getValidLibJoin() {
		return libJoinDao.getValidLibJoin();
	}

	@Override
	public List<Map<String, Object>> getLocationJoin(String league_lat, String league_lng,Integer type) {
		return libJoinQueryDao.getLocationJoin(league_lat, league_lng,type);
	}
	@Override
	 public Page<Map<String, Object>>  getLocationArea(Map<String, Object> searchParams, Pageable pageable){
		return libJoinQueryDao.getLocationArea(searchParams, pageable);
	}
	@Override
	public Page<Map<String, Object>>  getLocationJoin(Map<String, Object> searchParams, Pageable pageable){
		return libJoinQueryDao.getLocationJoin(searchParams, pageable);
	}
	@Override
	public Page<Map<String, Object>>  getLocationJoinService(Map<String, Object> searchParams, Pageable pageable){
		return libJoinQueryDao.getLocationJoinService(searchParams, pageable);
	}
    
	@Override
	public List<Map<String, Object>> getNoLocationJoin(Integer type) {
		return libJoinQueryDao.getNoLocationJoin(type);
	}

	@Override
	 public List<TbLibJoin> getLibJoinByCode(List<String> orgCode){
		if(orgCode!=null&&orgCode.size()>0){
			return libJoinDao.getLibJoinByCode(orgCode);
		}
		return  new ArrayList<TbLibJoin>(0);
	 }

	@Override
	public List<Map<String, Object>> pushNotice(String libId) {
		return libJoinQueryDao.pushNotice(libId);
	}

	@Override
	public List<Map<String, Object>> getPositionArea(String league_lat,
			String league_lng, Integer type,String schoolName) {
		return libJoinQueryDao.getPositionArea(league_lat, league_lng, type,schoolName);
	}

	@Override
	public List<Map<String, Object>> getJoinAll(int i) {
		
		return libJoinQueryDao.getJoinAll(i);
	}

	@Override
	public List<Map<String, Object>> getNearJoin(String league_lat, String league_lng, int i) {
		
		return libJoinQueryDao.getNearJoin(league_lat,league_lng,i);
	}

	@Override
	public TbLibJoin getAnnexLib(String locationLat, String locationLng,
			int type) {
		return libJoinDao.getAnnexLib(locationLat, locationLng, type);
	}

	@Override
	public List<TbLibJoin> findByMasterId(String masterId) {
		return libJoinDao.findByMasterId(masterId);
	}

	@Override
	public TbLibJoin findByLeagueCode(String leagueCode) {
		return libJoinDao.findByLeagueCode(leagueCode);
	}

	@Override
	public TbLibJoin findOneByCourseId(String courseId) {
		return libJoinDao.findOneByCourseId(courseId);
	}

	@Override
	public TbLibJoin findOneByCancelStat() {
	
		return libJoinDao.findOneByCancelStat();
	}

	@Override
	public List<TbLibJoin> findByLikeNameAndCity(String name, String province, String city, String area,Integer pageNo,Integer pageSize) {
		return libJoinQueryDao.findByLikeNameAndCity(name, province, city, area,pageNo, pageSize);
	}

	@Override
	public Long countByLikeNameAndCity(String name, String province, String city, String area) {
		return libJoinQueryDao.countByLikeNameAndCity(name, province, city, area);
	}

	@Override
	public void libJoinSave(TbLibJoin lib) throws Exception{
		if(lib.getCreateTime()==null){
			lib.setCreateTime(new Date());
		}
		if(lib.getWorkStart() == null || "".equals(lib.getWorkStart())){
			lib.setWorkStart("13:00");
		}
		if(lib.getWorkEnd() == null || "".equals(lib.getWorkEnd())){
			lib.setWorkEnd("21:00");
		}
		if(lib.getWeekeedStart() == null || "".equals(lib.getWeekeedStart())){
			lib.setWeekeedStart("09:00");
		}
		if(lib.getWeekeedEnd() == null || "".equals(lib.getWeekeedEnd())){
			lib.setWeekeedEnd("21:00");
		}
		if(StringUtil.isEmpty(lib.getStartJiaTime())){
			lib.setStartJiaTime("2017-02-01");
		}
		if(StringUtil.isEmpty(lib.getEndJiaTime())){
			lib.setEndJiaTime("2017-02-01");
		}
		String lngUrl = "http://apis.map.qq.com/ws/geocoder/v1/";
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("address", lib.getLeagueAddress());
		data.put("key", "CA5BZ-KRF3J-3RXFX-FUAYV-EUIC7-ADBDK");
		JSONObject jsonObject = JSONObject.parseObject(HttpRemote.GETMethod(lngUrl, data));
		if(jsonObject.getInteger("status") == 0){  //正常
			String lat = jsonObject.getJSONObject("result").getJSONObject("location").getString("lat"); //纬度
			String lng = jsonObject.getJSONObject("result").getJSONObject("location").getString("lng"); //经度
			lib.setLeagueLng(lng);
			lib.setLeagueLat(lat);
			//baseService.updateTemp(map.get("id").toString(),lat,lng);
		}
		lib=this.save(lib);
	    	/*Integer stat =1;
	    	if(lib.getId()==null){
	    		stat =2;
	    	}*/
	    	/*if(stat ==2){
	    	    // 新建图书馆的时候，把每个尊享卡（已激活）加入到该馆的服务(?1图书馆ID)
	    		libVipServiceService.insertIntoLibIdService(lib.getId());
	    	}*/
		if(lib !=null && lib.getQrCode() ==null && lib.getId() !=null){
			String file_path = (String) SystemResourceLocator.getValue("file_save_path");
			String fPath = "/BOOK/"+lib.getLeagueName();
			fPath += DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
			if (!fPath.endsWith("/")) {
				fPath += "/";
			}
			File f = new File(file_path+fPath);
			if (!f.exists()) {
				f.mkdirs();
			}
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/payment/vipbuy_BOOKDetails.html";
			String fPathId = fPath + lib.getId() + ".jpg";
			url=url.replace("BOOKDetails", lib.getId());
			BarcodeFactory.bookencode(url,file_path+fPathId,400, 400);
			lib.setQrCode(fPathId);
			lib=this.save(lib);
		}

	//	libSalesPriceService.insertLibSalesPrice(lib.getId(),lib.getLibtype());
		libCommissionService.insertCommission(lib.getId());
		libBorrowedServiceService.insertBorrowedService(lib.getId(),lib.getLibtype());

//		try {
//			TbClass tbClass=tbClassService.getTbClassByLibId(lib.getId(), "一班");
//			if(tbClass==null) {
//				tbClass=new TbClass();
//				tbClass.setLibId(lib.getId());
//				tbClass.setSchool(lib.getLeagueName());
//				tbClass.setClassName("一班");
//				tbClass.setCreateTime(new Date());
//				tbClass.setStatus(2);
//				tbClassService.save(tbClass);
//			}
//		} catch (Exception e) {
//			throw new Exception("添加馆创建班级异常...");
//		}
	}
}