package com.unis.detectionnum.server.service.impl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.unis.detectionnum.common.vo.*;
import com.unis.detectionnum.server.utils.CommonDataMeasure;
import com.unis.detectionnum.server.utils.HttpClientMessageUtils;
import com.unis.detectionnum.server.utils.RobotCallJobUtils;
import com.unis.detectionnum.server.utils.SocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.unis.detectionnum.server.domain.DeviceAlarmDomain;
import com.unis.detectionnum.server.service.DeviceAlarmService;

/** 
 * @ClassName: DeviceAlarmServiceImpl 
 * @Description: TODO 
 * @author LiuFeng 
 * @date 2019年10月30日 下午1:53:01  
 */
@Service
public class DeviceAlarmServiceImpl implements DeviceAlarmService{

	@Autowired
	private DeviceAlarmDomain deviceAlarmDomain;

    //定义全局工具类
    SocketUtils socketUtils = new SocketUtils();
    //定义全局仓房编号
    String cfBH;
	/**
	 * <p>Title: storehouseStatistic</p> 
	 * <p>Description: </p> 
	 * @param zskdm
	 * @return 
	 * @see com.unis.detectionnum.server.service.DeviceAlarmService#storehouseStatistic(java.lang.String) 
	 */
	@Override
	public Map<String,Object> storehouseStatistic(String userCode) {
		
		return deviceAlarmDomain.storehouseStatistic(userCode);
	}

	/**
	 * <p>Title: alarmRecordList</p> 
	 * <p>Description: </p> 
	 * @param deviceAlarmQueryVO
	 * @return 
	 * @see com.unis.detectionnum.server.service.DeviceAlarmService#alarmRecordList(com.unis.detectionnum.common.vo.DeviceAlarmQueryVO) 
	 */
	@Override
	public List<DeviceAlarmRecodVO> alarmRecordList(DeviceAlarmQueryVO deviceAlarmQueryVO) {
		// TODO Auto-generated method stub
        if(deviceAlarmQueryVO.getuserCode().equals("U0000777")){
            deviceAlarmQueryVO.setuserCode("");
        }
		return deviceAlarmDomain.alarmRecordList(deviceAlarmQueryVO);
	}

	/**
	 * <p>Title: saveDeviceAlarm</p> 
	 * <p>Description: </p> 
	 * @param deviceAlarmVO
	 * @return 
	 * @see com.unis.detectionnum.server.service.DeviceAlarmService#saveDeviceAlarm(com.unis.detectionnum.common.vo.DeviceAlarmVO) 
	 */
	@Override
	public String saveDeviceAlarm(DeviceAlarmVO deviceAlarmVO) {

		return deviceAlarmDomain.saveDeviceAlarm(deviceAlarmVO);
	}


	//报警
    @Override
    public void triggerCallAlarm(String cfbh) {
	        cfBH=cfbh;

            ServerSocket server = null;
            try
            {
                server = new ServerSocket(8899);

                while (true)
                {
                    Socket socket = server.accept();
                    ClientHandler handler = new ClientHandler(socket);
                    Thread t = new Thread(handler);
                    t.start();
                    break;
                    //fixedThreadPool.execute(handler);
                }
            } catch (Exception e)
            {
                e.printStackTrace();

            } finally
            {
                if (server != null)
                {
                    try
                    {
                        server.close();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }


    private class ClientHandler implements Runnable{
            private Socket socket;

            public ClientHandler(Socket socket)
            {
                System.out.println("into");
                this.socket = socket;
            }

            @Override
            public void run()
            {
                try
                {
                    CallAlarmPhone(socket,cfBH);

                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                } catch (IOException e)
                {
                    e.printStackTrace();
                } finally
                {
                    if (socket != null)
                    {
                        try
                        {
                            socket.close();
                        } catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

    public void CallAlarmPhone(Socket socket,String cfBH) throws IOException, InterruptedException {

            CallAlarmQueryVO callAlarmQueryVO = deviceAlarmDomain.getCallAlarm(cfBH);
            String cfmc = "";
            String kdmc = "";
            String lxdh = "";
            String ryxm = "";
            if(callAlarmQueryVO != null)
            {
                //cfmc：仓房名称，kdmc：库点名称，lxdh：联系电话，ryxm：人员信息
                 cfmc = callAlarmQueryVO.getCfmc();
                 kdmc = callAlarmQueryVO.getKdmc();
                 lxdh = callAlarmQueryVO.getLxdh();
                 ryxm = callAlarmQueryVO.getRyxm();
            }


            if(cfBH.length()>2){
                //声光报警
                callAlarm(socket);

                /*
                 * 调用短信平台发送告警信息
                 */
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("contens", "您好，"+ryxm+","+kdmc+""+cfmc+"发生粮食数量变化，请您及时确认！");
                jsonObject.put("creater", "1233");
                //jsonObject.put("mobile", "15810682367");
                //jsonObject.put("mobile", "18501020163");
                //jsonObject.put("mobile", "17600466577");
                jsonObject.put("mobile", "18910102780");
                HttpClientMessageUtils.sendMessage("http://218.241.206.66:88/api/message/submitData/sendMessageAndContens", jsonObject);

                /**
                 * 调用智能报警电话
                 */
                RobotCallJobUtils robotCallJobUtils = new RobotCallJobUtils();
                //创建任务
                String robotCallJobIdA = robotCallJobUtils.createTask();
                JSONObject Obj = JSONObject.parseObject(robotCallJobIdA);
                Map map = (Map) Obj.get("data");
                //获取任务id
                String robotCallJobId = map.values().toString().substring(1,7);

                //获取电话列表
                robotCallJobUtils.getPhoneList();
                //获取工作列表
                robotCallJobUtils.getJobs();
                //获取话术列表
                robotCallJobUtils.getDialogFlowList();
                //向任务中导入客户
                robotCallJobUtils.importTaskCustomer(robotCallJobId,"18910102780",cfmc);
                //robotCallJobUtils.importTaskCustomer(robotCallJobId,"18501020163");

                //开始任务
                robotCallJobUtils.startTask(robotCallJobId);

            }else{
                //启动风扇
                fanStart(socket);
            }




    }
    /**
     * 发送报警
     */
    public void callAlarm(Socket socket) throws IOException, InterruptedException {


        //打开报警
        String openAlarm = CommonDataMeasure.HEAD + " " + CommonDataMeasure.SLAVE_ID + " " + " 00 00 00 00 07 AD";
        //关闭报警
        String closeAlarm = CommonDataMeasure.HEAD + " " + CommonDataMeasure.SLAVE_ID + " " + " 00 00 00 00 06 AC";
       /* // 真实加热  风扇
        String openAlarm = CommonDataMeasure.HEAD + " " + CommonDataMeasure.SLAVE_ID + " " + "00 00 00 00 09 AF";
        // 关闭风扇
        String closeAlarm = CommonDataMeasure.HEAD + " " + CommonDataMeasure.SLAVE_ID + " " + "00 00 00 00 08 AE";
*/
        socketUtils.sendRequest(socket,openAlarm);

        //延长十秒
        Thread thread = new Thread();
        thread.sleep(10000);

        socketUtils.sendRequest(socket,closeAlarm);

    }
    /**
     * 启动风扇
     */
    public void fanStart(Socket socket) throws IOException, InterruptedException {

        // 真实加热  风扇
        String openAlarm = CommonDataMeasure.HEAD + " " + CommonDataMeasure.SLAVE_ID + " " + "00 00 00 00 09 AF";
        // 关闭风扇
        String closeAlarm = CommonDataMeasure.HEAD + " " + CommonDataMeasure.SLAVE_ID + " " + "00 00 00 00 08 AE";

        socketUtils.sendRequest(socket,openAlarm);

        //延长十秒
        Thread thread = new Thread();
        thread.sleep(10000);

        socketUtils.sendRequest(socket,closeAlarm);

    }


}
