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

import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.sys.fx.domain.Device;
import com.ssj.bean.sys.fx.domain.DeviceAct;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.dao.sys.fx.dao.DeviceDao;
import com.ssj.dao.sys.fx.dao.FxQueryDao;
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.service.sys.fx.service.DeviceActService;
import com.ssj.service.sys.fx.service.DeviceActiveService;
import com.ssj.service.sys.fx.service.DeviceService;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.task.SyncPushFxDeviceToFX;
import com.ssj.taskthread.ThreadPool;
import org.apache.commons.lang3.StringUtils;
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 java.util.Date;
import java.util.List;
import java.util.Map;


@Service(version="1.0")
public class DeviceServiceImpl extends BaseServiceImpl<Device, String> implements DeviceService {

	private   Logger logger = LoggerFactory.getLogger(this.getClass());
	 
	@Autowired
	private DeviceDao dao;
	
	@Autowired
	private FxQueryDao fxQueryDao;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private DeviceActService deviceActService;
	
	@Autowired
	private DeviceActiveService deviceActiveService;
	

	
    @Override
    public PagingAndSortingRepository<Device, String> getDao() {
        return dao;
    }
    
    
	@Override
	public int matchDeviceByMerchant(List<String> ids, String posCode,Admin admin,
			String emsNumber,String emsAddress,String emsUsername,String emsTelephone,String emsImg,String remarks) {
		int isNum=0;
		Merchant merchant=merchantService.getMerchantByPosCode(posCode);
		DeviceAct deviceAct=null;
	    String batchCode=DateHelper.format(new Date(), "yyyyMMddHHmmssSS");
		for (String id : ids) {
			try {
				Device device=dao.getOne(id);
				if(device==null) {
					continue;
				}
				String fromMerchantId=device.getMerchantId();
				
				device.setLastMerchantId(device.getMerchantId());
				device.setMerchantId(merchant.getId());
				device.setPosCode(posCode);
				device.setStatus(1);
				device.setReceiveTime(null);
				device.setOrgCode(merchant.getOrgCode());
				device.setUpdateTime(new Date());
				device.setEmsNumber(emsNumber);
				device.setEmsAddress(emsAddress);
				device.setEmsTelephone(emsTelephone);
				device.setEmsUsername(emsUsername);
				if(StringUtils.isNotEmpty(remarks)){
					device.setRemarks(remarks);
				}
				if(StringUtils.isNotEmpty(emsImg)){
					if(StringUtils.isNotEmpty(device.getEmsImg())){
						device.setEmsImg(device.getEmsImg()+";"+emsImg);
					}else{
						device.setEmsImg(emsImg);
					}
				}
				dao.save(device);
				
				//分配给自己不会记录
				if(!fromMerchantId.equals(merchant.getId())){
					/**
					 * 分配记录，由当前商户分配到下级商户
					 */
					deviceAct=new DeviceAct();
					deviceAct.setFromMerchantId(fromMerchantId);
					deviceAct.setToMerchantId(merchant.getId());
					deviceAct.setOperatorAdminId(admin.getId());
					deviceAct.setDeviceId(device.getId());
					deviceAct.setImei(device.getImei());
					deviceAct.setIsUsed(device.getIsSpan());
					deviceAct.setCreateTime(new Date());
					deviceAct.setType(1);
					deviceAct.setEmsNumber(emsNumber);
					deviceAct.setEmsAddress(emsAddress);
					deviceAct.setEmsTelephone(emsTelephone);
					deviceAct.setEmsUsername(emsUsername);
					deviceAct.setEmsImg(emsImg);
					deviceAct.setBatchCode(batchCode);
					deviceAct.setRemarks("设备出库：分配下级");
					if(StringUtils.isNotEmpty(remarks)){
						deviceAct.setRemarks(deviceAct.getRemarks()+"【"+remarks+"】");
					}
					deviceActService.save(deviceAct);
					
					/**
					 * 入库记录，由当前商户分配到下级商户
					 */
					deviceAct=new DeviceAct();
					deviceAct.setFromMerchantId(fromMerchantId);
					deviceAct.setToMerchantId(merchant.getId());
					deviceAct.setOperatorAdminId(admin.getId());
					deviceAct.setDeviceId(device.getId());
					deviceAct.setImei(device.getImei());
					deviceAct.setIsUsed(device.getIsSpan());
					deviceAct.setCreateTime(new Date());
					deviceAct.setType(3);
					deviceAct.setEmsNumber(emsNumber);
					deviceAct.setEmsAddress(emsAddress);
					deviceAct.setEmsTelephone(emsTelephone);
					deviceAct.setEmsUsername(emsUsername);
					deviceAct.setEmsImg(emsImg);
					deviceAct.setBatchCode(batchCode);
					deviceAct.setRemarks("设备入库：上级分配");
					if(StringUtils.isNotEmpty(remarks)){
						deviceAct.setRemarks(deviceAct.getRemarks()+"【"+remarks+"】");
					}
					deviceActService.save(deviceAct);
					
					device.setDeviceAct(deviceAct);
					//deviceActService.save(deviceAct);
				}
				isNum=isNum+1;
				try {
					updateMerchantLeveAndActive(posCode,id);
				} catch (Exception e) {
					logger.error("posCode:"+posCode+"   imeis:"+ids+"  生成失fx_device_active数据失败..."+e.getMessage());
				}
				
			} catch (Exception e) {
				logger.error("posCode:"+posCode+"   imeis:"+ids+"  分配失败..."+e.getMessage());
			}
		}
		return isNum;
	}


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

	@Override
	public Merchant checkIsRage(String imei, String checkLng, String checkLat, String activeLng, String activeLat) {
		Device device = this.findDeviceByImei(imei);
		if(device!=null){
			Merchant merchant = merchantService.getById(device.getMerchantId());
			Thread t1 = new Thread(new Runnable() {
				public void run() {
					deviceActiveService.activeDeviceActiveByImei(device, merchant,imei);
				}
			});
			t1.start();
			return merchant; 
		}
		return null; 
	}


	private Device findDeviceByImei(String imei) {
    	return dao.getDeviceByImei(imei);
	}


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

	@Override
	public Device getDeviceByImei(String imei) {
		Device device=dao.getDeviceByImei(imei);
		return device;
	}

	@Override
	public Integer countDeviceByPosCode(String posCode) {
		return dao.countDeviceByPosCode(posCode);
	}

	@Override
	public void updateMerchantLeveAndActive(String posCode,String id) {
		//大于等于2级的商户才需要升级
		Merchant merchant=merchantService.getMerchantByPosCode(posCode);
		Integer level=merchant.getLevel()!=null ? merchant.getLevel() : 0;
		if(level>=2){
			Integer  deviceNum=deviceActService.countDeviceByMerchantId(merchant.getId());
			//当前为三级的，当>=200的时候升级   
			if(level==3){
				if(deviceNum>=200){
					updateMerchantLeve(merchant);
				}
			}else if(level==2){
				if(deviceNum>=500){
					updateMerchantLeve(merchant);
				}
			}
		}
		deviceActiveService.saveDeviceActiveByImei(merchant, id);
	}
	
	//升一级
	public void updateMerchantLeve(Merchant merchant) {
		//查出上一级商户，再查出上上级的商户。
		if(StringUtils.isNotEmpty(merchant.getParentPosCode())){
			Merchant pmerchant=merchantService.getMerchantByPosCode(merchant.getParentPosCode());
			if(StringUtils.isNotEmpty(pmerchant.getParentPosCode())){
				Merchant ppmerchant=merchantService.getMerchantByPosCode(pmerchant.getParentPosCode());
				merchant.setParentPosCode(ppmerchant.getParentPosCode());
				merchant.setOrgCode(ppmerchant.getOrgCode()+"-"+merchant.getPosCode());
				merchant.setLevel(pmerchant.getLevel());
				merchantService.save(merchant);
			}
		}
	}

	@Override
	public void matchDeviceByMQ(Device device) {
		if(device!=null && StringUtils.isNotEmpty(device.getPosCode())){
			this.save(device);
			
			DeviceAct olddeviceAct= device.getDeviceAct();
			if(olddeviceAct!=null){
				DeviceAct deviceAct=new DeviceAct();
				deviceAct.setFromMerchantId(olddeviceAct.getFromMerchantId());
				deviceAct.setToMerchantId(olddeviceAct.getToMerchantId());
				deviceAct.setOperatorAdminId(olddeviceAct.getOperatorAdminId());
				deviceAct.setDeviceId(device.getId());
				deviceAct.setImei(device.getImei());
				deviceAct.setCreateTime(new Date());
				deviceAct.setType(3);
				deviceAct.setEmsNumber(olddeviceAct.getEmsNumber());
				deviceAct.setEmsAddress(olddeviceAct.getEmsAddress());
				deviceAct.setEmsTelephone(olddeviceAct.getEmsTelephone());
				deviceAct.setEmsUsername(olddeviceAct.getEmsUsername());
				deviceAct.setEmsImg(olddeviceAct.getEmsImg());
				deviceAct.setBatchCode(olddeviceAct.getBatchCode());
				deviceAct.setRemarks("设备入库：爱加分配");
				deviceActService.save(deviceAct);
				
			}
		    logger.info("成功消费爱加系统推送设备信息队列数据");
		}
	}

	@Override
	public void pushDeviceToAijia(Device device) {
		ThreadPool.getInstance().addTask(new SyncPushFxDeviceToFX(device));
	}

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

	@Override
	public Page<Map<String, Object>> deviceInAndOutList(Map<String, Object> params, Pageable initPage) {
		return fxQueryDao.deviceInAndOutList(params,initPage);
	}

	@Override
	public Page<Map<String, Object>> deviceOutList(Map<String, Object> params, Pageable initPage) {
		return fxQueryDao.deviceOutList(params,initPage);
	}


}


