package com.ssj.service.course.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ssj.bean.course.domain.CourseDetailFeedbackLib;
import com.ssj.bean.course.domain.CourseFeedbackFile;
import com.ssj.bean.course.domain.CourseSeries;
import com.ssj.bean.course.domain.CourseSeriesDetail;
import com.ssj.bean.course.domain.CourseSeriesDetailFeedback;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.course.dao.ICourseLibFeedbackDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.course.req.TeacherFeedbackReqV2;
import com.ssj.service.course.service.CourseSeriesDetailFeedbackService;
import com.ssj.service.course.service.CourseSeriesJoinService;
import com.ssj.service.course.service.ICSDetailService;
import com.ssj.service.course.service.ICSService;
import com.ssj.service.course.service.ICourseFeedbackFileService;
import com.ssj.service.course.service.ICouseLibFeedbackService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;

@Transactional
@Service(version="1.0")
public class CourseLibFeedbackServiceImpl extends BaseServiceImpl<CourseDetailFeedbackLib, String> implements ICouseLibFeedbackService {

	@Autowired
	private ICourseLibFeedbackDao dao;
	
	@Autowired
	private ILibVipService vipService;
	 @Autowired
	private PushTemplateService  pushTemplateService;
	@Autowired
	private CourseSeriesJoinService joinService;
	@Autowired
	private UserService userService;
	
	@Autowired
	private ICSDetailService csDetailService;
	@Autowired
	private ICSService csService;
	
	@Autowired
	private ICourseFeedbackFileService backFileService;
	
	@Autowired
	private ICSService courseService;
	
	@Autowired
	private CourseSeriesDetailFeedbackService feedbackService;
	
	@Override
	public PagingAndSortingRepository<CourseDetailFeedbackLib, String> getDao() {
		
		return dao;
	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseDetailFeedbackLib findTodayVOByAnyParams(String courseDetailId, String libId) {
		return dao.findTodayVOByAnyParams(courseDetailId,libId);
	}

	@Override
	public void courseFeedbackSendV2(TeacherFeedbackReqV2 req,String userId) {
		
		//LibVip vip = vipService.getById(req.getVipId());
		CourseDetailFeedbackLib back = dao.findTodayVOByAnyParams(req.getCourseDetailId(),req.getLibId());
		int isSend = 0;
		if(back != null){ 
			if(back.getIsSend()==1){
				isSend = 1;
			}
		}else{
			back=new CourseDetailFeedbackLib();
		}
		CourseSeriesDetail courseDetail = csDetailService.getById(req.getCourseDetailId());
		CourseSeries courseSeries = csService.getById(courseDetail.getSeriesId());
		back.setUserId(userId);
		back.setCourseContent(JSON.toJSONString(req.getCourseContentList()));//后续看怎么处理用；隔开
		back.setCourseSeriesId(req.getCourseSeriesId());
		back.setCourseTask(req.getClassTask());
		back.setCreateTime(new Date());
		back.setIsSend(1);
		back.setLibId(req.getLibId());
		back.setOpenTime(new Date());
		back.setTodayLine(JSON.toJSONString(req.getInfoList()));
		back.setCourseDetailsId(req.getCourseDetailId());
		back.setTeacherSay(req.getSaying());
		this.save(back);
		
		
		//课程信息
		Map<String, Object> studentsearch = new HashMap<String, Object>();
		studentsearch.put("userId", userId);
		studentsearch.put("courseSeriesId", req.getCourseSeriesId());
		studentsearch.put("libId", req.getLibId());
		//查找课程学生列表
		studentsearch.put("courseDetailId", req.getCourseDetailId());
		List<Map<String, Object>> studentMaplist = courseService.getCourseStudentListV2(studentsearch);
		List<CourseSeriesDetailFeedback> cFeedbackList=new ArrayList<CourseSeriesDetailFeedback>();
		CourseSeriesDetailFeedback cFeedback=null;
		for (Map<String, Object> map : studentMaplist) {
			String vipId=map.get("vip_id").toString();
			String vUserId=map.get("user_id").toString();
			
			cFeedback=new CourseSeriesDetailFeedback();
			cFeedback.setIsSend(1);
			cFeedback.setLibId(req.getLibId());
			cFeedback.setUserId(vUserId);
			cFeedback.setVipId(vipId);
			cFeedback.setSaying(req.getSaying());
			cFeedback.setCreateTime(new Date());
			cFeedback.setCourseDetailsId(req.getCourseDetailId());
			cFeedback.setCourseSeriesId(courseDetail.getSeriesId());
			cFeedback.setLibFeedbackId(back.getId());
			cFeedback.setActiveScore((double)0);
			cFeedback.setFocusScore((double)0);
			cFeedbackList.add(cFeedback);
		}
		
		if(cFeedbackList.size()>0){
			feedbackService.save(cFeedbackList);
		}
		
		
		List<String> imgList = req.getImgList();
		if(imgList !=null && imgList.size()>0){
			for (String string : imgList) {
				CourseFeedbackFile file = new CourseFeedbackFile();
				file.setCreateTime(new Date());
				file.setLibId(req.getLibId());
				file.setImgurl(string);
				file.setCourseDetailsId(req.getCourseDetailId());
				file.setVipId(back.getId()); //如果是小红花vipId就是学生id，如果是课堂风采vipId就是反馈id
				backFileService.save(file);
			}
		}
		
		if(isSend == 0){
			//查询学生列表
			Map<String, Object> search = new HashMap<String, Object>();
			search.put("libId", req.getLibId());
			search.put("courseDetailId", req.getCourseDetailId());
			List<Map<String, Object>> studentlist = csService.getCourseStudentList(search);
			for (Map<String, Object> map : studentlist) {
				String vipId = map.get("vip_id").toString();
				LibVip vip = vipService.getById(vipId);
				//发送报告
				User user = userService.getById(vip.getUserId());
				
				String parentContentMessage = "亲爱的"+ vip.getChildName()+"家长您好！老师已完成本节课的课后反馈，请及时查收，以便跟进孩子学习情况!";
				Map<String, String> data = new HashMap<String, String>();
				data.put("first", parentContentMessage+"\n");
				data.put("keyword1", courseSeries.getCourseName()+courseDetail.getCourseUnit());
				data.put("keyword2", DateUtil.dateToString(new Date()));
				String template_id = "OPENTM408875752";
				Miniprogram miniprogram = new Miniprogram();
				miniprogram.setAppid(WxUtil.map.get("courseAppId"));
				miniprogram.setPagepath("pages/feedback_report/feedback_report?type=11&feedbackId="+back.getId()+"&vipId="+vipId);
				SendTemplateShort sendTemplateShort = new SendTemplateShort(user.getAccount(), template_id, null,
						data, miniprogram);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				
				//讲join表的状态更新为已反馈
				joinService.updateStateSend(back.getCourseDetailsId(),vipId,back.getLibId());
			}
			
		}
	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseDetailFeedbackLib getCourseDetailFeedbackLibByTeacherId(
			String libId, String courseDetailsId) {
		return dao.getCourseDetailFeedbackLibByTeacherId(libId, courseDetailsId);
	}
}
