package com.sw.mes.yb.production.service.impl;


import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.api.auth.AuthFeignClient;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.mqtt.service.NotificationService;
import com.sw.mes.utils.EAPHttpUtil;
import com.sw.mes.yb.ipc.dto.IpcRefresh;
import com.sw.mes.yb.production.dao.EquipmentExtendStateDao;
import com.sw.mes.yb.production.entity.EquipmentExtendState;
import com.sw.mes.yb.production.notification.IpcLoginMessage;
import com.sw.mes.yb.production.notification.IpcRefreshMessage;
import com.sw.mes.yb.production.service.EquipmentExtendStateService;

import lombok.extern.slf4j.Slf4j;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
@Slf4j
public class EquipmentExtendStateServiceImpl extends BaseServiceImpl<EquipmentExtendState> implements EquipmentExtendStateService {
    EquipmentExtendStateDao dao;

    @Autowired
    public void setDao(EquipmentExtendStateDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    private AuthFeignClient authFeignClient;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Override
    public EquipmentExtendState getByCode(String equimentCode) {
        return dao.getByEquipmentCode(equimentCode);
    }

    @Override
    public void loginUpdate(String equipmentCode, String series, String loginName, String token, String teamGroup, String classNo) {
        try {
            Equipment equipment = equipmentService.findByCode(equipmentCode);
            if (StringUtils.isNotBlank(series) && series.contains(equipment.getSeries())) {
                //Result<UserDto> user = authFeignClient.findByLoginName(loginName);
                EquipmentExtendState state = getByCode(equipmentCode);
                if (state == null) {
                    state = new EquipmentExtendState();
                    state.setEquipmentCode(equipment.getCode());
                    state.setEquipmentState(2);
                    state.setLevelStickState(false);
                    state.setSeries(equipment.getSeries());
                    state.setArea(equipment.getArea());
                    state.setClassNo(classNo);
                    state.setTeamGroup(teamGroup);
                    saveOrUpdate(state);
                }
                dao.updateLoginInfo(loginName, new Date(), token, teamGroup, classNo, equipment.getSeries());
                //推送登录信息到EAP - 单独线程发送  时间比较长
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            DictionaryItem dic = dictionaryItemService.findByThemeValueAndNameAndEnable("EapApi", "EapUser", true);
                            List<EquipmentExtendState> equipmentExtendStates = dao.findBySeries(equipment.getSeries());
                            for (EquipmentExtendState equipmentExtendState : equipmentExtendStates) {
                                try {
                                    String params = "{\"deviceCode\":\"" + equipmentExtendState.getEquipmentCode() + "\",\"key\":\"operatorUser\",\"value\":\"" + equipmentExtendState.getUserName() + "\"}";
                                    String result = EAPHttpUtil.post(dic.getValue(), params, 1000);
                                    log.info("EAP登录用户请求发送返回值:" + result);
                                } catch (Exception e) {
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                });
                thread.start();
                //发送MQTT 刷新登录通知
                IpcLoginMessage message = new IpcLoginMessage();
                message.setArea(equipment.getArea());
                message.setEquipmentCode(equipmentCode);
                message.setId(equipment.getId());
                message.setSeries(equipment.getSeries());
                notificationService.sendNotification(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("设备编号："+equipmentCode+"不存在，无法登陆");
        }
    }

    @Override
    public void logoutUpdate(String equipmentCode, String series) {
        Equipment equipment = equipmentService.findByCode(equipmentCode);

//		if(equipment.getSeries() == series) {
        dao.updateLogoutInfo(equipmentCode, equipment.getSeries());
//		}else {
//			throw new RuntimeException("选择系列不可登录本炉台");
//		}
    }

	@Override
	public void ipcRefresh(IpcRefresh dto) {
		//发送MQTT 刷新登录通知
        IpcRefreshMessage message = new IpcRefreshMessage();
        message.setArea(dto.getArea());
        message.setEquipmentCode(dto.getEquimentCode());
        message.setSeries(dto.getSeries());
        notificationService.sendNotification(message);
	}

}
