package com.dcsoft.job.service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.enums.exception.CommonExceptionEnum;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.job.domain.DeviceVo;
import com.dcsoft.job.domain.VisitorVo;
import com.dcsoft.job.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dcsoft.job.domain.SysJobLog;
import com.dcsoft.job.mapper.SysJobLogMapper;

/**
 * 定时任务调度日志信息 服务层
 *
 * @author dcsoft
 */
@Service
@Slf4j
public class SysJobLogServiceImpl implements ISysJobLogService
{
    @Autowired
    private SysJobLogMapper jobLogMapper;

    /**
     * 获取quartz调度器日志的计划任务
     *
     * @param jobLog 调度日志信息
     * @return 调度任务日志集合
     */
    @Override
    public List<SysJobLog> selectJobLogList(SysJobLog jobLog)
    {
        return jobLogMapper.selectJobLogList(jobLog);
    }

    /**
     * 通过调度任务日志ID查询调度信息
     *
     * @param jobLogId 调度任务日志ID
     * @return 调度任务日志对象信息
     */
    @Override
    public SysJobLog selectJobLogById(Long jobLogId)
    {
        return jobLogMapper.selectJobLogById(jobLogId);
    }

    /**
     * 新增任务日志
     *
     * @param jobLog 调度日志信息
     */
    @Override
    public void addJobLog(SysJobLog jobLog)
    {
        jobLogMapper.insertJobLog(jobLog);
    }

    /**
     * 批量删除调度日志信息
     *
     * @param logIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteJobLogByIds(Long[] logIds)
    {
        return jobLogMapper.deleteJobLogByIds(logIds);
    }

    /**
     * 删除任务日志
     *
     * @param jobId 调度日志ID
     */
    @Override
    public int deleteJobLogById(Long jobId)
    {
        return jobLogMapper.deleteJobLogById(jobId);
    }

    /**
     * 清空任务日志
     */
    @Override
    public void cleanJobLog()
    {
        jobLogMapper.cleanJobLog();
    }

    /**
     * 梯控刷卡回调接口设置
     * @param sequence
     */
    @Override
    public void setDeviceCallBackInfo(String sequence) {
        if(StringUtils.isNotEmpty(sequence)){
            String[] split = sequence.split(",");
            List<String> list = Arrays.asList(split);
            List<DeviceVo> deviceVos = jobLogMapper.queryDevice(list);
            for (DeviceVo deviceVo : deviceVos) {
                String body = null;
                try {
                    deviceVo.setIp("http://" + deviceVo.getIp() + ":8090" + "/SetDeviceCallBackInfo");
                    body = setDeviceCallBackInfo(deviceVo, "http://192.168.255.52:6609/system/sdk/saveLadderRecord");
                } catch (Exception e) {
                    continue;
                }
                log.info("设置设备识别回调ip:" + deviceVo.getIp());
                log.info("设置设备识别回调返回参:" + body);
                JSONObject object = JSONObject.parseObject(body);
                if(!Constants.CODE.equals(object.get("msg"))) {
                    throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "设置设备识别回调接口接口" +
                            CommonExceptionEnum.REQUEST_ERROR.getMessage() + "设置设备识别回调接口接口异常码" + object.get("msg").toString());
                }
            }
        }

    }

    private String setDeviceCallBackInfo(DeviceVo deviceVo, String url) {
        Map<String, String> map = new HashMap<>();
        map.put("callbackUrl", url);
        map.put("pass", deviceVo.getPassword());
        return HttpUtil.createPost(deviceVo.getIp()).timeout(5000).body(JSON.toJSONString(map)).execute().body();
    }

    /**
     * 刷新梯控设备在线离线状态
     * @param sequence
     */
    @Override
    public void updateLadderState(String sequence) throws IOException {
        String[] split = sequence.split(",");
        List<String> list = Arrays.asList(split);
        List<DeviceVo> deviceVos = jobLogMapper.queryDevice(list);
        for (DeviceVo deviceVo : deviceVos) {
            InetAddress address = InetAddress.getByName(deviceVo.getIp());
            boolean isIpReachable = address.isReachable(3000);
            if(isIpReachable) {
                deviceVo.setState(Constants.ZERO);
            } else {
                deviceVo.setState(Constants.ONE);
            }
        }
        jobLogMapper.updateLadderState(deviceVos);
    }

    /**
     * 删除宇泛人脸设备访客结束时间的数据
     */
    @Override
    public void deleteVisitorFaceDevice() {
        List<VisitorVo> visitorVo = jobLogMapper.queryGuidAndFaceGuid();
        List<DeviceVo> list = jobLogMapper.queryDeviceInfo();
        for (VisitorVo vo : visitorVo) {
            for (DeviceVo deviceVo : list) {
                try {
                    if(StringUtils.isNotEmpty(vo.getFaceGuid())) {
                        // 删除照片
                        imageDelete(vo.getFaceGuid(), deviceVo.getIp(), deviceVo.getPassword());
                    }

                    if(StringUtils.isNotEmpty(vo.getGuid())) {
                        // 删除人员
                        personDelete(vo.getGuid(), deviceVo.getIp(), deviceVo.getPassword());
                    }

                } catch (Exception e) {
                    log.error("删除宇泛人脸设备访客结束时间的数据:" + deviceVo.getIp() + "异常", e);
                }
            }
        }
    }

    /**
     * 设置宇泛二维码回调地址
     */
    @Override
    public void setQRCodeCallback(String sequence) {
        List<String> list = Arrays.asList(sequence.split(","));
        List<DeviceVo> deviceVos = jobLogMapper.queryDevice(list);
        for (DeviceVo deviceVo : deviceVos) {
            String body = null;
            try {
                deviceVo.setIp("http://" + deviceVo.getIp() + ":8090/device/setQRCodeCallback");
                body = setDeviceCallBackInfo(deviceVo, "http://192.168.255.52:6609/system/sdk/backUrlEwm");
            } catch (Exception e) {
                continue;
            }
            log.info("设置宇泛门镜设备识别回调ip:" + deviceVo.getIp());
            log.info("设置宇泛门镜设备识别回调返回参:" + body);
            JSONObject object = JSONObject.parseObject(body);
            if(!Constants.CODE.equals(object.get("msg"))) {
                throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "设置宇泛门镜设备识别回调接口接口" +
                        CommonExceptionEnum.REQUEST_ERROR.getMessage() + "设置宇泛门镜设备识别回调接口接口异常码" + object.get("msg").toString());
            }
        }
    }

    /**
     * 定时签离访客人员
     */
    @Override
    public void updateVisitorSignOff() {
        jobLogMapper.updateVisitorSignOff();
    }

    private String personDelete(String id, String ip, String pass) {
        String url="http://"+ip+":8090/person/delete";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("id",id);
        String response= HttpUtils.sendxwwwform(url,paramMap);
        return response;
    }

    private String imageDelete(String faceId, String ip, String pass) {
        String url="http://"+ip+":8090/face/delete";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("faceId",faceId);//可不传,设为空
        String response= HttpUtils.sendxwwwform(url,paramMap);
        return response;
    }

    /**
     * 查询设备信息接口
     */
    private String getDeviceInfo(DeviceVo deviceVo) {
        Map<String, String> map = new HashMap<>();
        map.put("pass", deviceVo.getPassword());
        map.put("idcardnum", "11111111");
        return HttpUtil.createGet("http://" + deviceVo.getIp() + ":8090" + "/cardinfo/find").timeout(5000).body(JSON.toJSONString(map)).execute().body();
    }

}
