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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.sys.homework.domain.HomeworkPicture;
import com.ssj.bean.weixin.download.domain.DownloadFile;
import com.ssj.bean.weixin.zyb.domain.ZuoybStudentWorkImg;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybQueryDao;
import com.ssj.dao.weixin.zuoyb.dao.ZuoybStudentWorkImgDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.framework.weixin.util.MUDload;
import com.ssj.framework.files.service.FileInfoService;
import com.ssj.service.sys.homework.service.HomeworkPictureService;
import com.ssj.service.weixin.download.service.DownloadFileService;
import com.ssj.service.weixin.zuoyb.service.ZuoybStudentWorkImgService;

/** 
 * @author  ZhangCaibao 
 * @version 2017年9月14日 下午3:05:13 
 * 类说明 
 */
@Service(version="1.0")
@Transactional
public class ZuoybStudentWorkImgServiceImpl extends BaseServiceImpl<ZuoybStudentWorkImg, String> implements ZuoybStudentWorkImgService{

	private   Logger logger = LoggerFactory.getLogger(this.getClass());
	 
	@Autowired
	private  ZuoybStudentWorkImgDao  zuoybStudentWorkImgDao;
	
	@Autowired
	private  DownloadFileService   downloadFileService;
	@Autowired
	private  FileInfoService   fileInfoService;

	@Autowired
	private HomeworkPictureService homeworkService;

	@Autowired
	private ZuoybQueryDao zuoybQueryDao;
	
	 @Autowired
    private TokenManager tokenManager;
	 
	@Override
	public PagingAndSortingRepository<ZuoybStudentWorkImg, String> getDao() {
		return zuoybStudentWorkImgDao;
	}

	@Override
	public void saveWorkImg(String[] imgages_localId, String[] imgages_serverId,
			String imgids, String workId) {
		if(imgids != null ){
			String ids[]= imgids.split(",");
			if(ids !=null && ids.length>0){
				for(int x=0; x< ids.length; x++){
					this.delete(ids[x]);
				}
			}
	  }
		logger.info("imgages_localId--"+Arrays.toString(imgages_localId));
		logger.info("imgages_serverId--"+Arrays.toString(imgages_serverId));
		if(imgages_serverId !=null && imgages_serverId.length>0){
			List<ZuoybStudentWorkImg> imglist = new  ArrayList<ZuoybStudentWorkImg>();
				for(int x=0; x< imgages_serverId.length; x++){
					logger.info(imgages_serverId[x]);
					DownloadFile file = new  DownloadFile();
					file.setCreateTime(new Date());
					file.setMediaId(imgages_serverId[x]);
					file.setStat(0);
					file.setType(1);//语音
					if(x<=imgages_localId.length-1){
						file.setLocalId(imgages_localId[x]);
					}
					String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
					String result=MUDload.downloadMedia(tokenManager.getSSJAccessToken(),imgages_serverId[x], fPath);
					if(result !=null){
						file.setStat(1);
						file.setUrl(result);
					}else{
						file.setStat(2);
					}
					downloadFileService.save(file);
					ZuoybStudentWorkImg  img = new ZuoybStudentWorkImg();
					 img.setCreateTime(new Date());
					 img.setObjectId(workId);
					 img.setImg(result);
					 img.setNum(x+1);
					 imglist.add(img);
				}
				this.save(imglist);
		}
	}

	@Override
	public void saveWorkImg(List<ZuoybStudentWorkImg> list, String imgids,
			String workId) {
		if(imgids != null ){
			String ids[]= imgids.split(",");
			if(ids !=null && ids.length>0){
				for(int x=0; x< ids.length; x++){
					this.delete(ids[x]);
				}
			}
	  }
		 int index = 1;	
	 for (ZuoybStudentWorkImg img : list) {
		  if(img ==null){
			  continue;
		  }
		  if(img.getId()==null){
			    logger.info("imgages_localId--"+img.getImgagesLocalId());
				logger.info("imgages_serverId--"+img.getImgagesServerId());
				 if(img.getImgagesServerId()==null) {continue;}
			  DownloadFile file = new  DownloadFile();
			  file.setCreateTime(new Date());
			  file.setMediaId(img.getImgagesServerId());
			  file.setStat(0);
			  file.setType(1);//语音
			  file.setLocalId(img.getImgagesLocalId());
			  String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
			  String result=MUDload.downloadMedia(tokenManager.getSSJAccessToken(),img.getImgagesServerId(), fPath);
			  if(result !=null){
				  file.setStat(1);
				  file.setUrl(result);
			  }else{
				  file.setStat(2);
			  }
			  img.setImg(result);
			  downloadFileService.save(file);
		  }else{
			  logger.info("img.getId()--"+img.getId());
		  }
			
			 img.setCreateTime(new Date());
			 img.setObjectId(workId);
			 img.setHowDetailsId(workId);//暂定为workid
			 img.setNum(index++);
			 this.save(img);
		  
	  }	
	}

	@Override
	public void deleteByObjectId(String objectId) {
		zuoybStudentWorkImgDao.deleteByObjectId(objectId);
		
	}

	@Override
	public void saveWorkHowDetailsImg(List<ZuoybStudentWorkImg> list,
			String detailsId, String workId) {
		 int index = 1;	
		 for (ZuoybStudentWorkImg img : list) {
			  if(img ==null){
				  continue;
			  }
			  if(img.getId()==null){
				    logger.info("saveWorkHowDetailsImg-imgages_localId--"+img.getImgagesLocalId());
					logger.info("saveWorkHowDetailsImg-imgages_serverId--"+img.getImgagesServerId());
				  if(img.getImgagesServerId()==null) {continue;}
				  DownloadFile file = new  DownloadFile();
				  file.setCreateTime(new Date());
				  file.setMediaId(img.getImgagesServerId());
				  file.setStat(0);
				  file.setType(1);//语音
				  file.setLocalId(img.getImgagesLocalId());
				  String fPath = DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
				  String result=MUDload.downloadMedia(tokenManager.getSSJAccessToken(),img.getImgagesServerId(), fPath);
				  if(result !=null){
					  file.setStat(1);
					  file.setUrl(result);
				  }else{
					  file.setStat(2);
				  }
				  img.setImg(result);
				  downloadFileService.save(file);
			  }else{
				  
				  logger.info("img.getId()"+img.getId());
			  }
				
				 img.setCreateTime(new Date());
				 img.setObjectId(workId);
				 img.setHowDetailsId(detailsId);//暂定为workid
				 img.setNum(index++);
				 this.save(img);
			  
		  }	
		
	}
	@Override
	public void saveWorkHowDetailsImgaes(List<ZuoybStudentWorkImg> list,
			String detailsId, String workId) throws Exception {
		int index = 1;	
		for (ZuoybStudentWorkImg img : list) {
			if(img ==null){
				continue;
			}
			
			img.setCreateTime(new Date());
			img.setObjectId(workId);
			img.setHowDetailsId(detailsId);//暂定为workid
			img.setNum(index++);
			this.save(img);
			
		}	
		
	}

	@Override
	public List<ZuoybStudentWorkImg> getObjectList(String pushId) {
		return zuoybStudentWorkImgDao.getObjectList(pushId);
	}

	@Override
	public Long countByObjectIdIn(List<String> objectIds) {
		return zuoybStudentWorkImgDao.countByObjectIdIn(objectIds);
	}

	@Override
	public int countImgByObjectIdIn(List<String> objectIds) {
		return zuoybStudentWorkImgDao.countDistinctByObjectIdIn(objectIds);
	}


	@Override
	public List<String> saveCorrectResult(String data, String zuoybWorkId, HomeworkPicture p) {
		Integer num = 1;
		JSONArray jArray = JSONArray.parseArray(data);
		List<String> result = new ArrayList<String>();

		//判断当前时间是15点以前还是15点以后
		String today = DateUtil.format_yyyyMMddHHmmss(DateUtil.getTodatDate());
		String tomorrow = DateUtil.format_yyyyMMddHHmmss(new Date());
//		if(DateUtil.getHour(new Date()) >= 15) {
//			//15点以后
//			today = DateHelper.getUserDate("yyyy-MM-dd");
//			tomorrow = DateHelper.getBeforeDate("yyyy-MM-dd",1);
//		}else {
//			//15点以前
//			today = DateHelper.getBeforeDate("yyyy-MM-dd",-1);
//			tomorrow = DateHelper.getUserDate("yyyy-MM-dd");
//		}
//		today = today + " 00:00:00";
//		tomorrow = tomorrow + " 00:00:00";

		List<HomeworkPicture> pictureList = homeworkService.findSortById(p.getSubject(), today, tomorrow, p.getVipId());
		int workNum  = 1;
		for (int i = 0; i < pictureList.size(); i++){
			if (p.getId().equals(pictureList.get(i).getId())){
				workNum = i + 1;
				break;
			}
		}

		for (Object object : jArray) {
			JSONObject obj = (JSONObject) object;
			JSONArray objArray = obj.getJSONArray("how_details_id");
			ZuoybStudentWorkImg img;
			String position  = StringUtil.isEmpty(obj.getString("position")) ? "0" : obj.getString("position");

			//如果有关联知识点，插入多条记录
			if (objArray != null && objArray.size() > 0){
			//	logger.info("有关联知识点,插入记录如下：");
				for (Object tmp : objArray) {
					img = new ZuoybStudentWorkImg();
					img.setCreateTime(new Date());
					img.setHowDetailsId(tmp.toString());
					img.setImg(obj.getString("img"));
					img.setWrongTitle(obj.getString("wrong_title"));
					img.setListNum(position);
					img.setWorkNum(workNum);
					img.setNum(num);
					img.setObjectId(zuoybWorkId);
					img.setType(1);
				//	logger.info("第" + num + "张错题：" + img);
					this.save(img);

					String how_details_id = tmp.toString();//知识点id
					result.add(how_details_id);
				}
			} else { //没有关联知识点，插入一条记录
				img = new ZuoybStudentWorkImg();
				img.setCreateTime(new Date());
				img.setImg(obj.getString("img"));
				img.setWrongTitle(obj.getString("wrong_title"));
				img.setListNum(position);
				img.setWorkNum(workNum);
				img.setNum(num);
				img.setObjectId(zuoybWorkId);
				img.setType(1);
			//	logger.info("没有关联知识点，插入一条记录：" + img);
				this.save(img);
			}
			num = num + 1;
		}
		return result;
	}

	@Override
	public void saveImgData(List<Map<String, Object>> list, String zuoybWorkId, HomeworkPicture p) {
		String today = DateUtil.format_yyyyMMddHHmmss(DateUtil.getTodatDate());
		String tomorrow = DateUtil.format_yyyyMMddHHmmss(new Date());
		List<HomeworkPicture> pictureList = homeworkService.findSortById(p.getSubject(), today, tomorrow, p.getVipId());
		ZuoybStudentWorkImg img;
		int lineNo = 0;
		int colNo = 0;
		String pid = p.getId();

		for (Map<String, Object> map : list){
			List<String> whdIds = (List<String>)map.get("workHowDetailIds");
			lineNo = StringUtil.isEmpty(map.get("lineNo") + "") ? 0 : Integer.parseInt(map.get("lineNo") + "");
			colNo = StringUtil.isEmpty(map.get("colNo") + "") ? 0 : Integer.parseInt(map.get("colNo") + "");
			if (whdIds != null && whdIds.size() > 0){
				for (String whdId : whdIds){
					saveImg(map.get("img") + "",
							map.get("wrong_title") + "",
							whdId,
							map.get("position") + "",
							getWorkNum(pictureList, p.getId()),
							zuoybWorkId,
							list.indexOf(map) + 1,
							lineNo,
							colNo,
							pid);
				}
			} else {
				saveImg(map.get("img") + "",
						map.get("wrong_title") + "",
						null,
						map.get("position") + "",
						getWorkNum(pictureList, p.getId()),
						zuoybWorkId,
						list.indexOf(map) + 1,
						lineNo,
						colNo,
						pid);
			}

		}
	}

	private void saveImg (String imgPath, String title, String howDetailId, String position, int workNum,
						  String zuoybWorkId, int num, int lineNo, int colNo, String pid) {
		ZuoybStudentWorkImg img = new ZuoybStudentWorkImg();
		img.setCreateTime(new Date());
		img.setImg(imgPath);
		img.setWrongTitle(title);
		img.setHowDetailsId(howDetailId);
		img.setHomeworkPictureId(pid);
		img.setListNum(position);
		img.setLineNum(lineNo);
		img.setColumnNum(colNo);
		img.setWorkNum(workNum);
		img.setNum(num);
		img.setObjectId(zuoybWorkId);
		img.setType(1);
		this.save(img);
	}

	private int getWorkNum (List<HomeworkPicture> pictureList, String pid) {
		int workNum  = 1;
		for (int i = 0; i < pictureList.size(); i++){
			if (pid.equals(pictureList.get(i).getId())){
				workNum = i + 1;
				break;
			}
		}
		return workNum;
	}

	@Override
	public List<String> findWrongQuestion (String studentWorkId) {
		List<ZuoybStudentWorkImg> list = zuoybStudentWorkImgDao.findByObjectId(studentWorkId);
		Set<String> result = new HashSet<String>();
		if (list != null){
			for (ZuoybStudentWorkImg img : list){
				result.add(img.getImg());
			}
		}
		return new ArrayList<String>(result);
	}

	@Override
	public Page<Map<String, Object>> findWrongTopicBook (String vipId, String subject, boolean isCorrect, Pageable pageable) {
		return zuoybQueryDao.findWrongTopicDate(vipId, subject, isCorrect, pageable);
	}
}
