package com.ssj.service.sys.smarttime.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.conch.conch.domain.SmarttimePicture;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.dao.sys.smarttime.dao.SmarttimeDao;
import com.ssj.dao.sys.smarttime.dao.SmarttimeQueryDao;
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.service.conch.parents.request.DeleteSmarttimeRequest;
import com.ssj.service.conch.parents.request.SmarttimeExt;
import com.ssj.service.conch.student.dto.SmartTimeGroupDTO;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.sys.smarttime.service.SmarttimeService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.sys.util.face.FaceReq;
import org.json.JSONObject;
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.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(version="1.0")
@Transactional
public class SmarttimeServiceImpl extends BaseServiceImpl<SmarttimePicture, String> implements SmarttimeService {

    private Logger               logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SmarttimeDao           smarttimeDao;
	
	@Autowired
	private SmarttimeQueryDao smarttimeQueryDao;
	
	@Autowired
	private UserService userService;
	
	 @Autowired
	private PushTemplateService pushTemplateService;

	 @Autowired
	private SconXingeService sconXingeService;
    
    @Override
    public PagingAndSortingRepository<SmarttimePicture, String> getDao() {
        return smarttimeDao;
    }

    @Override
    public void addSmarttimePicture(String parentId,String childName, String fileKey, String derver,Integer type,String derverFileKey,String vipId) {
    	//判断fileKeys是否在表中存在
    	long count = smarttimeDao.countByFileKey(fileKey);
    	if(count > 0) {
    		//如果作业有相同图片则不上传
    		return;
    	}

        this.insertSmarttimePicture(parentId, fileKey, derver, type, derverFileKey,vipId);

        //推送小时光，通知家长
        //推送家长 通知
        String contentMessage = "尊敬的"+childName+"家长，您的孩子有些新奇发现，一起与孩子分享其中的快乐吧";
        sconXingeService.asynPushThreadTask(parentId, null,2, contentMessage,PushConstants.PUSH_OTHER);
        
        //小程序提醒家长
//        User parent = userService.getById(parentId);
//		Map<String,String> data =new HashMap<String, String>();
//		String template_id_short="OPENTM406494620";
//		data.put("first", contentMessage+"\n");
//		data.put("keyword1", "1");
//		data.put("keyword2",DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
//		data.put("remark", "您可以通过点击详情浏览照片，点击留住您孩子喜欢的瞬间。\n");
//		SendTemplateShort sendTemplateShort=new SendTemplateShort(parent.getAccount(), template_id_short, null, data);
//		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
        
    }

    @Override
    public void insertSmarttimePicture(String parentId, String fileKey, String derver, Integer type, String derverFileKey, String vipId) {
        SmarttimePicture smarttimePicture = new SmarttimePicture();
        smarttimePicture.setParentId(parentId);
        smarttimePicture.setIsDelete(0);
        smarttimePicture.setFileKey(fileKey);
        smarttimePicture.setDerver(derver);
        smarttimePicture.setVipId(vipId);
        smarttimePicture.setType(type);
        smarttimePicture.setCommentNums(0);
        smarttimePicture.setCreateTime(new Date());
        smarttimePicture.setDerverFileKey(derverFileKey);
        if (type != null) {
            smarttimePicture.setType(type);
        }
//        try {
//        	//调用百度图片识别，获取识别度最高的标签，设置图片标签
//        	JSONObject req = FaceReq.advancedGeneral(fileKey, new HashMap<String, String>(1));
//            if(req!=null && req.has("result")){
//               JSONObject o=((JSONObject)(req.getJSONArray("result").get(0)));
//               smarttimePicture.setKeyword(o.getString("keyword"));
//            }else {
//            	smarttimePicture.setKeyword("美好时光");
//            }
//        }catch (Exception e) {
//        	smarttimePicture.setKeyword("美好时光");
//		}
        smarttimePicture.setKeyword("美好时光");
        this.save(smarttimePicture);

    }

    @Override
    public List<SmarttimePicture> querySmarttimePictureList(String parentId) {
        
         
        return smarttimeDao.findByParentIdAndIsDeleteOrderByIdDesc(parentId, 0);
    }

    @Override
    public void deleteSmarttime(DeleteSmarttimeRequest request) {
       
        smarttimeDao.deleteById(request.getSmarttimeId());
    }

    @Override
    public Map<String, Object> searchSmarttimeList(Map<String, Object> params, Pageable pageable) {
       
        Map<String, SearchFilter> filters = SearchFilter.parse(params);
        Specification<SmarttimePicture> specification = DynamicSpecifications.bySearchFilter(filters.values(),
                                                                                             SmarttimePicture.class);
        Page<SmarttimePicture> page = smarttimeDao.findAll(specification, pageable);

        List<SmarttimeExt> smarttimeExt = new ArrayList<>();
        if (page.getSize() > 0) {
            for (SmarttimePicture smarttimePicture : page.getContent()) {
                SmarttimeExt ext = new SmarttimeExt();
                ext.setCreateTime(smarttimePicture.getCreateTime());
                ext.setParentId(smarttimePicture.getParentId());
                ext.setFileKey(smarttimePicture.getFileKey());
                ext.setSmarttimeId(smarttimePicture.getId());
                ext.setWeekday(DateUtil.getWeekDateToStr(smarttimePicture.getCreateTime()));
                ext.setAddress(smarttimePicture.getAddress().trim());
                ext.setSmartsay(smarttimePicture.getSmartsay());
                smarttimeExt.add(ext);
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("pages", page.getTotalElements());
        data.put("list", smarttimeExt);
        data.put("pageSize", pageable.getPageSize());
        data.put("pageNo", pageable.getPageNumber()+1);
        return data;

    }

    @Override
    public void updateSmarttime(DeleteSmarttimeRequest request) {

        smarttimeDao.updateSmartSay(request.getSmarttimeId(), request.getSmartsay());
    }

	@Override
	public Map<String, Object> searchSmarttimeGroupList(Map<String, Object> params, Pageable pageable) {
		
		Page<Map<String, Object>> page = smarttimeQueryDao.findGroupByKeyword(params, pageable);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> map : page.getContent()) {
			Map<String, Object> smarttimeMap = new HashMap<String,Object>();
			smarttimeMap.put("keyword", DateUtil.format(((Date) map.get("create_date")).getTime(), "yyyy.MM.dd"));
			//通过标签分类获取该分类下的所有小时光图片
			List<SmarttimePicture> SmarttimePictureList = smarttimeDao.findByCreateDateVipId(map.get("create_date").toString(), params.get("vipId").toString());
			List<Map<String, Object>> list2 = new ArrayList<>();
			for (SmarttimePicture smarttimePicture : SmarttimePictureList) {
				Map<String, Object> map2 = new HashMap<String,Object>();
				map2.put("smarttimeId", smarttimePicture.getId());
				map2.put("fileKey", smarttimePicture.getFileKey());
				map2.put("createTime", smarttimePicture.getCreateTime());
				map2.put("smartsay", smarttimePicture.getSmartsay());
				list2.add(map2);
			}
			smarttimeMap.put("smarttime", list2);
			list.add(smarttimeMap);
		}
		Map<String, Object> data = new HashMap<String, Object>();
        data.put("pages", page.getTotalElements());
        data.put("list", list);
        data.put("pageSize", pageable.getPageSize());
        data.put("pageNo", pageable.getPageNumber()+1);
        return data;
	}

	@Override
	public Page<SmarttimePicture> findAll(Specification<SmarttimePicture> specification, Pageable page) {
		return smarttimeDao.findAll(specification, page);
	}

    @Override
    public Page<SmartTimeGroupDTO> searchAppSmartTimeGroupList(Map<String, Object> params, Pageable pageable) {
        return smarttimeQueryDao.searchAppSmartTimeGroupList(params, pageable);
    }

}
