package com.jpsoft.shinestar.modules.base.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jpsoft.shinestar.modules.base.dao.PersonDeviceRelationDAO;
import com.jpsoft.shinestar.modules.base.dao.PersonInfoDAO;
import com.jpsoft.shinestar.modules.base.dto.PersonDeviceRelationDTO;
import com.jpsoft.shinestar.modules.base.entity.DeviceInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonDeviceRelation;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.service.DeviceInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonDeviceRelationService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.pacs.dto.IsPersonExistVo;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Transactional
@Component(value="personDeviceRelationService")
public class PersonDeviceRelationServiceImpl implements PersonDeviceRelationService {
	@Resource(name="personDeviceRelationDAO")
	private PersonDeviceRelationDAO personDeviceRelationDAO;

	@Autowired
	private IGuardService guardService;

	@Autowired
	private DeviceInfoService deviceInfoService;

	@Autowired
	private SysLogService sysLogService;

	@Autowired
	private PersonDeviceRelationService personDeviceRelationService;

	@Autowired
	private PersonInfoDAO personInfoDAO;

	@Autowired
	RabbitTemplate rabbitTemplate;

	@Autowired
	private ValueOperations<String,Object> valueOperations;

	@Override
	public PersonDeviceRelation get(String id) {
		// TODO Auto-generated method stub
		return personDeviceRelationDAO.get(id);
	}

	@Override
	public int insert(PersonDeviceRelation model) {
		// TODO Auto-generated method stub
		//model.setId(UUID.randomUUID().toString());

		return personDeviceRelationDAO.insert(model);
	}

	@Override
	public int update(PersonDeviceRelation model) {
		// TODO Auto-generated method stub
		return personDeviceRelationDAO.update(model);
	}

	@Override
	public int updateDevicePerson(PersonDeviceRelation model) throws Exception {

		List<PacsMsgResult> lapiMsgResultList = guardService.deletePersonFromDevice(model.getPersonId(),model.getDeviceId());

		int affectCount = 0;

		if(lapiMsgResultList.size()>0){
			PacsMsgResult lapiMsgResult = lapiMsgResultList.get(0);
			if(lapiMsgResult.isSuccess()){
				affectCount = personDeviceRelationDAO.update(model);
			}
		}
		return affectCount;
	}

	@Override
	public int delete(String id) {
		// TODO Auto-generated method stub
		return personDeviceRelationDAO.delete(id);
	}

	@Override
	public boolean exist(String id) {
		// TODO Auto-generated method stub
		int count = personDeviceRelationDAO.exist(id);

		return count > 0 ? true : false;
	}

	@Override
	public List<PersonDeviceRelation> list() {
		// TODO Auto-generated method stub
		return personDeviceRelationDAO.list();
	}

	@Override
	public List<PersonDeviceRelation> findByPersonId(Long personId){
		return personDeviceRelationDAO.findByPersonId(personId);
	}

	@Override
	public List<PersonDeviceRelation> findByDeviceId(String deviceId){
		return personDeviceRelationDAO.findByDeviceId(deviceId);
	}

	@Override
	public List<Long> findByDerviceName(String derviceName){
		return personDeviceRelationDAO.findByDerviceName(derviceName);
	}

	@Override
	public PersonDeviceRelation findByDeviceIdAndPersonId(String deviceId,Long personId){
		return personDeviceRelationDAO.findByDeviceIdAndPersonId(deviceId,personId);
	}



	@Override
	public Page<PersonDeviceRelation> pageSearch(Map<String, Object> searchParams, int pageNumber, int pageSize,boolean count,List<Sort> sortList) {
        Page<PersonDeviceRelation> page = PageHelper.startPage(pageNumber,pageSize,count).doSelectPage(()->{
            personDeviceRelationDAO.search(searchParams,sortList);
        });

        return page;
	}

//	@Override
//	public List<PersonDeviceRelation> findByPersonId(Long id) {
//
//		return personDeviceRelationDAO.findByPersonId(id);
//	}


	@Override
	public List<DeviceInfo> findDeviceByPersonId(Long personId) {
		return personDeviceRelationDAO.findDeviceByPersonId(personId);
	}

	@Override
	public List<PersonDeviceRelation> findByIsBoundAndUpdateTime(Date updateTime, Integer limit) {
		return personDeviceRelationDAO.findByIsBoundAndUpdateTime(updateTime,limit);
	}

	@Override
	public void updateIsBound(Long personInfoId, String deviceInfoId,Boolean isBound) {
		PersonDeviceRelation personDeviceRelation =  personDeviceRelationDAO.findByDeviceIdAndPersonId(deviceInfoId,personInfoId);
		if (personDeviceRelation != null){
				personDeviceRelation.setIsBound(isBound);
				personDeviceRelation.setUpdateTime(new Date());
				personDeviceRelationDAO.updateIsBound(personDeviceRelation);

		}
	}

	@Override
	public void updateListIsBound(List<IsPersonExistVo> list, String deviceInfoId) {
		for (IsPersonExistVo isPersonExistVo : list){
			PersonDeviceRelation personDeviceRelation = new PersonDeviceRelation();
			personDeviceRelation.setPersonId(isPersonExistVo.getPersonId());
			personDeviceRelation.setDeviceId(deviceInfoId);
			personDeviceRelation.setUpdateTime(new Date());
			personDeviceRelation.setIsBound(isPersonExistVo.getIsPersonExist());

			personDeviceRelationDAO.updateIsBound(personDeviceRelation);
		}
	}

	/**
	 * 绑定新设备
	 *
	 * @param deviceId
	 * @return
	 */
	@Override
	public int bindNewDevice(String deviceId) {
		int affectCount = 0;

		DeviceInfo deviceInfo = deviceInfoService.get(deviceId);

		List<PersonDeviceRelation> pdrList = personDeviceRelationService.findByDeviceId(deviceInfo.getId());


		valueOperations.set("bindNewDevice_progress_" + deviceId, "0/" + pdrList.size() , 5 , TimeUnit.SECONDS);

		int index = 0;

		for (PersonDeviceRelation pdr : pdrList) {
			PersonInfo personInfo = personInfoDAO.get(pdr.getPersonId());
			if(personInfo != null) {
				if (pdr.getIsBound() == null || !pdr.getIsBound()) {
					//有照片才同步
					if (StringUtils.isNotEmpty(personInfo.getFaceImageUrl())) {
						affectCount++;

						//todo 加入到导入图片队列中
						addImportQueue(deviceInfo, pdr);
					}
				}
			}
			index++;

			valueOperations.set("bindNewDevice_progress_" + deviceId, index + "/" + pdrList.size() , 5 , TimeUnit.SECONDS);
		}

		return affectCount;
	}

	private void addImportQueue(DeviceInfo deviceInfo,PersonDeviceRelation pdr) {
		if (deviceInfo.getIsOnline()!=null && deviceInfo.getIsOnline()){
			PersonDeviceRelationDTO dto = new PersonDeviceRelationDTO();
			dto.setPersonId(pdr.getPersonId());
			dto.setDeviceId(pdr.getDeviceId());

			rabbitTemplate.convertAndSend("importImageExchange", "importImage", dto);
		}
	}
}