package com.dcsoft.system.uniubi.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.utils.CollUtil;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.Person;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import com.dcsoft.system.utils.HttpUtil;
import com.dcsoft.system.visitor.domain.Visitor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户管理 服务层处理
 *
 * @author xueyi
 */
@Service
@Slf4j
public class SysSdkServiceImpl implements ISysSdkService {

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private ISysEmpowerRecordService empowerRecordService;

    @Autowired
    private ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private ISysPeopleService sysPeopleService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysEqDownRecordService sysEqDownRecordService;

    /**
     * 卡权限创建接口
     */
    public static final String create = "/cardinfo/create";


    @Override
    public String personCreate(Person person, String ip, String pass) {
        String url="http://"+ip+":8090/person/create";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        JSONObject personObject = JSONObject.parseObject(JSON.toJSONString(person));
        paramMap.put("pass",pass);
        paramMap.put("person",personObject);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public 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= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String ruleCreate(String name, String ip, String pass, Date startTime, Date endTime) {
        String url = "http://" + ip + ":8090/rule/create";
        JSONObject paramMap = new JSONObject();
        paramMap.put("pass", pass);
        paramMap.put("name", name);
        paramMap.put("type", 1);
        List<String> segment = Arrays.asList("00:00:00", "23:59:59");
        Map<String, Object> dayMap = new HashMap<>();
        dayMap.put("segment", segment);
        dayMap.put("endAt", endTime.getTime());
        dayMap.put("startAt", startTime.getTime());
        Map<String, Object> contentMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(dayMap);
        contentMap.put("day", list);
        contentMap.put("endAt", endTime.getTime());
        contentMap.put("startAt", startTime.getTime());
        paramMap.put("content", contentMap);
        return HttpUtil.postDataJson(url, paramMap);
    }

    @Override
    public String personUpdate(Person person, String ip, String pass) {
        String url="http://"+ip+":8090/person/update";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        JSONObject personObject = JSONObject.parseObject(JSON.toJSONString(person));
        paramMap.put("pass",pass);
        paramMap.put("person",personObject);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String personFind(String id, String ip, String pass) {
        String url="http://"+ip+":8090/person/find?pass="+pass+"&id="+id;
        String response= HttpUtil.getData(url);
        return response;
    }


    @Override
    public String icCardRegist(String id, String ip, String pass) {
        String url="http://"+ip+":8090/face/icCardRegist";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String createPasstime(JSONObject object, String ip, String pass) {
       /* {"personId":"9eecc839cd7941c5a4d3165202dd3c32","passtime":"09:00:00,10:
            00:00,17:00:00,17:30:00,18:30:00,20:25:00"}*/
        String url="http://"+ip+":8090/person/createPasstime";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("passtime",object);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String passtime(JSONObject object, String ip, String pass) {
       /* {"personId":"9eecc839cd7941c5a4d3165202dd3c32","passtime":"09:00:00,10:
            00:00,17:00:00,17:30:00,18:30:00,20:25:00"}*/
        String url="http://"+ip+":8090/person/passtime";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("passtime",object.get("passtime"));
        paramMap.put("personId",object.get("personId"));
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String deletePasstime(String id, String ip, String pass) {
        String url="http://"+ip+":8090/person/deletePasstime";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String permissionsCreate(String id, String time,String ip, String pass) {
        String url="http://"+ip+":8090/person/permissionsCreate";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("time",time);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String permissionTime(String id, String startTime, String endTime, String ip, String pass) {
        String url="http://"+ip+":8090/person/permissionTime";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String permissionsDelete(String id,String ip, String pass) {
        String url="http://"+ip+":8090/person/permissionsCreate";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String imageCreate64(String id, String imgBase64, String ip, String pass) {
        String url="http://"+ip+":8090/face/create";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        paramMap.put("faceId",id);//可不传,设为空
        paramMap.put("imgBase64",imgBase64);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String imageCreateUrl(String id,String imgUrl, String ip, String pass) {
        String url="http://"+ip+":8090/face/createByUrl";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        paramMap.put("faceId","");//可不传,设为空
        //照地址替换
        if(imgUrl.contains("http://tdmj.kmlygroup.com")){
            imgUrl=imgUrl.replace("http://tdmj.kmlygroup.com","http://192.168.1.35");
        }
        if(imgUrl.contains("https://mj.kmlygroup.com/")){
            imgUrl=imgUrl.replace("https://mj.kmlygroup.com/","http://192.168.255.51:9000/");
        }
        if(imgUrl.contains("https://fk.xyxaks.cn/")){
            imgUrl=imgUrl.replace("https://fk.xyxaks.cn/","http://192.168.33.96:9000/");
        }
        paramMap.put("imgUrl",imgUrl);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String imageCreateUrl(String id, String faceId, String imgUrl, String ip, String pass) {
        String url = "http://" + ip + ":8090/face/createByUrl";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pass", pass);
        paramMap.put("personId", id);
        paramMap.put("faceId", faceId);//可不传,设为空
        //照地址替换
        if (imgUrl.contains("http://tdmj.kmlygroup.com")) {
            imgUrl = imgUrl.replace("http://tdmj.kmlygroup.com", "http://192.168.251.16");
        }
        if (imgUrl.contains("https://mj.kmlygroup.com/")) {
            imgUrl = imgUrl.replace("https://mj.kmlygroup.com/", "http://192.168.255.51:9000/");
        }
        if (imgUrl.contains("https://fk.xyxaks.cn/")) {
            imgUrl = imgUrl.replace("https://fk.xyxaks.cn/", "http://192.168.33.96:9000/");
        }
        paramMap.put("imgUrl", imgUrl);
        String response = HttpUtil.sendxwwwform(url, paramMap);
        log.info("ip:{},imageCreateUrl:{}", ip, response);
        return response;
    }

    @Override
    public String imageDeletel(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= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String imageUpdate64(String id, String faceId, String imgBase64, String ip, String pass) {
        String url="http://"+ip+":8090/face/update";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        paramMap.put("faceId",faceId);
        paramMap.put("imgBase64",imgBase64);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String takeImg(String id, String ip, String pass) {
        String url="http://"+ip+":8090/face/takeImg";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String deletePerson(String id, String ip, String pass) {
        String url="http://"+ip+":8090/face/deletePerson";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String setIdentifyCallBack(String callbackUrl, String ip, String pass) {
        String url="http://"+ip+":8090/setIdentifyCallBack";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("callbackUrl",callbackUrl);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String openDoorControl(String ip, String pass) {
        String url="http://"+ip+":8090/device/openDoorControl";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String restartDevice(String ip, String pass) {
        String url="http://"+ip+":8090/restartDevice";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String resetDevice(String ip, String pass) {
        String url="http://"+ip+":8090/device/reset";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    //人像门禁服务-设备授权识别主体
    @Override
    public String authDevice(SysRule rule, SysPeople people) {
        String response="";
        String[] pointIds=rule.getPointId().split(",");
        List<SysEquipment> equipList=new ArrayList<>();
        if(pointIds!=null){
            for(String point:pointIds){
                SysEquipment equipment=new SysEquipment();
                equipment.setPointId(Long.parseLong(point));
                equipment.setIsCj("0");
                equipment.setFlag("0");
//                equipment.setProductId(3L);
                List<SysEquipment> equipmentDtoList=equipmentService.selectSysEquipmentList(equipment);
                equipList.addAll(equipmentDtoList);
            }
        }
        //通过规则获取绑定设备信息
        if(equipList!=null){
            for(SysEquipment e:equipList){
                //将人员信息下发到设备
                Person person=new Person();
                person.setName(people.getName());
                person.setId(people.getGuid());
                person.setiDNumber(people.getIdcard());
                person.setIdcardNum(people.getDoorNo());
                person.setPhone(people.getPhone());
                String ip=e.getIp();
                String pass=e.getPassword();
                String admitGuid="";
                String faceGuid="";
                if(3L == e.getProductId()) {
                    log.info("通过规则信息" + e);
                    this.personDelete(people.getGuid(),ip,pass);
                    String data=this.personCreate(person,ip,pass);
                    log.info("通过规则下发" + data);
                    JSONObject json= JSONObject.parseObject(data);

                    if(!"1".equals(json.get("result")+"")) {
                        continue;
                    }
                    JSONObject obj1 = (JSONObject) json.get("data");
                    admitGuid=obj1.get("id")+"";
                    if(StringUtils.isNotEmpty(people.getAvatar())) {
                        String datas=this.imageCreateUrl(admitGuid,people.getAvatar(),ip,pass);
                        JSONObject jsons= JSONObject.parseObject(datas);
                        if("1".equals(jsons.get("result")+"")){
                            faceGuid=jsons.get("data")+"";
                        }
                    }
                }


                //保存到人员设备关联表中
                SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
                sysPeopleEquipment.setGuid(admitGuid);
                sysPeopleEquipment.setFaceGuid(faceGuid);
                sysPeopleEquipment.setPeopleId(people.getId());
                sysPeopleEquipment.setEquipmentId(e.getId());
                peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
                JSONObject jsons = new JSONObject();
                if(3L == e.getProductId()) {
                    //人员权限下发设备
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date  endTime=rule.getEndTime();
                    response=this.permissionsCreate(admitGuid,sdf.format(endTime),ip,pass);
                    JSONObject obj=new JSONObject();
                    obj.put("personId",admitGuid);
                    obj.put("passtime",rule.getAdmittanceStart()+","+rule.getAdmittanceEnd());
                    this.createPasstime(obj,ip,pass);
                    jsons = JSONObject.parseObject(response);
                }

                //授权记录保存
                if("1".equals(jsons.get("result")+"")){
                    SysEmpowerRecord manageRecordDto=new SysEmpowerRecord();
                    manageRecordDto.setPeopleId(people.getId());
                    manageRecordDto.setEmpower(rule.getType());
                    manageRecordDto.setEquipmentId(e.getId());
                    manageRecordDto.setStatus("0");
                    manageRecordDto.setInfoDown("0");
                    manageRecordDto.setRuleId(rule.getId());
                    empowerRecordService.insertSysEmpowerRecord(manageRecordDto);
                }else{
                    SysEmpowerRecord manageRecordDto=new SysEmpowerRecord();
                    manageRecordDto.setPeopleId(people.getId());
                    manageRecordDto.setEmpower(rule.getType());
                    manageRecordDto.setEquipmentId(e.getId());
                    manageRecordDto.setStatus("0");
                    manageRecordDto.setInfoDown("1");
                    manageRecordDto.setRuleId(rule.getId());
                    empowerRecordService.insertSysEmpowerRecord(manageRecordDto);
                }
            }
        }
        return response;
    }

    //人像门禁服务-设备授权识别主体
    @Override
    public String authDevice(SysRule rule, SysPeople people, SysEquipment equipment) {
        String response="";
        //将人员信息下发到设备
        Person person=new Person();
        person.setName(people.getName());
        person.setiDNumber(people.getIdcard());
        person.setPhone(people.getPhone());
        person.setIdcardNum(people.getDoorNo());
        person.setId(people.getGuid());
        String ip=equipment.getIp();
        String pass=equipment.getPassword();
        this.personDelete(people.getGuid(),ip,pass);
        String data=this.personCreate(person,ip,pass);
        JSONObject json= JSONObject.parseObject(data);
        String admitGuid="";
        String faceGuid="";
        if("1".equals(json.get("result")+"")) {
            JSONObject obj= (JSONObject) json.get("data");
            admitGuid=obj.get("id")+"";
            String datas=this.imageCreateUrl(admitGuid,people.getAvatar(),ip,pass);
            JSONObject jsons= JSONObject.parseObject(datas);
            if("1".equals(jsons.get("result")+"")){
                faceGuid=jsons.get("data")+"";
            }
            //保存到人员设备关联表中
            SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
            sysPeopleEquipment.setGuid(admitGuid);
            sysPeopleEquipment.setFaceGuid(faceGuid);
            sysPeopleEquipment.setPeopleId(people.getId());
            sysPeopleEquipment.setEquipmentId(equipment.getId());
            peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
        }
        //人员权限下发设备
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date  endTime=rule.getEndTime();
        response=this.permissionsCreate(admitGuid,sdf.format(endTime),ip,pass);
        JSONObject obj=new JSONObject();
        obj.put("personId",admitGuid);
        obj.put("passtime",rule.getAdmittanceStart()+","+rule.getAdmittanceEnd());
        this.createPasstime(obj,ip,pass);
        return response;
    }

    @Override
    public String authDeviceExamine(Visitor visitor) {
        String response="";
        //将人员信息下发到设备
        Person person=new Person();
        person.setName(visitor.getName());
        person.setiDNumber(visitor.getIdcard());
        person.setPhone(visitor.getPhone());
        List<SysEquipment> equipmentDtoList=equipmentService.selectSysEquipmentList(new SysEquipment());
        for(SysEquipment equipment:equipmentDtoList){
            String ip=equipment.getIp();
            String pass=equipment.getPassword();
            String data=this.personCreate(person,ip,pass);
            JSONObject json= JSONObject.parseObject(data);
            String admitGuid="";
            String faceGuid="";
            if("1".equals(json.get("result")+"")) {
                JSONObject obj= (JSONObject) json.get("data");
                admitGuid=obj.get("id")+"";
                String datas=this.imageCreateUrl(admitGuid,visitor.getAvatar(),ip,pass);
                JSONObject jsons= JSONObject.parseObject(datas);
                if("1".equals(jsons.get("result")+"")){
                    faceGuid=jsons.get("data")+"";
                }
                //保存到人员设备关联表中
                SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
                sysPeopleEquipment.setGuid(admitGuid);
                sysPeopleEquipment.setFaceGuid(faceGuid);
                sysPeopleEquipment.setVisitorId(visitor.getId());
                sysPeopleEquipment.setEquipmentId(equipment.getId());
                peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
            }
            //人员权限下发设备
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date  endTime=visitor.getEndTime();
            response=this.permissionsCreate(admitGuid,sdf.format(endTime),ip,pass);
            JSONObject obj=new JSONObject();
            obj.put("personId",admitGuid);
            obj.put("passtime",visitor.getInTime()+","+visitor.getOutTime());
            this.createPasstime(obj,ip,pass);
        }
        return response;
    }

    //人像门禁服务-设备销权识别主体
    @Override
    public String authDeviceRevoke(Visitor visitor) {
        String response = "";

        List<SysEquipment> equipmentDtoList = equipmentService.selectSysEquipmentList(new SysEquipment());
        for(SysEquipment eq:equipmentDtoList){
            List<SysPeopleEquipment> list=peopleEquipmentService.selectSysPeopleEquipmentByVisitorId(visitor.getId());
            for(SysPeopleEquipment spe:list){
                if(spe.getEquipmentId().equals(eq.getId())){
                    this.personDelete(spe.getGuid(), eq.getIp(), eq.getPassword());
                }
            }
        }

        return response;
    }

    @Override
    public String setQRCodeCallback(String callbackUrl, String ip, String pass) {
        String url="http://"+ip+":8090/setQRCodeCallback";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("url",callbackUrl+"Ewm");
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String setDeviceHeartBeat(String callbackUrl, String ip, String pass) {
        String url="http://"+ip+":8090/setDeviceHeartBeat";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("url",callbackUrl+"Heart");
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String fingerRegist(String id, String ip, String pass) {
        String url="http://"+ip+":8090/face/fingerRegist";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String featureInfo(String id, String ip, String pass) {
        String url="http://"+ip+":8090/person/featureInfo?pass="+pass+"&personId="+id+"&type="+2;
        String response= HttpUtil.getData(url);
        return response;
    }

    @Override
    public String faceFind(String id, String ip, String pass) {
        String url="http://"+ip+":8090/face/find";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String featureReg(String id,String fingerprint, String ip, String pass) {
        String url="http://"+ip+":8090/face/featureReg";
        Map<String, Object> paramMap=new HashMap<String, Object>();
        paramMap.put("pass",pass);
        paramMap.put("personId",id);
        paramMap.put("faceId","");
        paramMap.put("feature",fingerprint);
        paramMap.put("type",2);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        return response;
    }

    @Override
    public String authDeviceNew(SysRule rule, SysPeople people) {
        String response="";
        String[] pointIds=rule.getPointId().split(",");
        List<SysEquipment> equipList=new ArrayList<>();
        if(pointIds!=null){
            for(String point:pointIds){
                SysEquipment equipment=new SysEquipment();
                equipment.setPointId(Long.parseLong(point));
                equipment.setFlag("0");
                equipment.setIsCj("0");
//                equipment.setProductId(3L);
                List<SysEquipment> equipmentDtoList=equipmentService.selectSysEquipmentList(equipment);
                equipList.addAll(equipmentDtoList);
            }
        }
        //通过规则获取绑定设备信息
        if(equipList!=null){
            for(SysEquipment e:equipList){
                if(3L == e.getProductId()) {
                    //将人员信息下发到设备
                    Person person=new Person();
                    person.setName(people.getName());
                    person.setIdcardNum(people.getDoorNo());
                    person.setiDNumber(people.getIdcard());
                    person.setPhone(people.getPhone());
                    person.setId(people.getGuid());
                    String ip=e.getIp();
                    String pass=e.getPassword();
                    this.personDelete(people.getGuid(),ip,pass);
                    response=this.personCreate(person,ip,pass);
                    if(StringUtils.isNotEmpty(people.getFaceGuid())){//人脸
                        this.imageCreateUrl(people.getGuid(),people.getFaceGuid(),people.getAvatar(), e.getIp(), e.getPassword());
                    }
                }

                //保存下发记录
                SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
                sysPeopleEquipment.setPeopleId(people.getId());
                sysPeopleEquipment.setEquipmentId(e.getId());
                sysPeopleEquipment.setGuid(people.getGuid());
                sysPeopleEquipment.setFaceGuid(people.getFaceGuid());
                peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
                SysEmpowerRecord manageRecordDto=new SysEmpowerRecord();
                manageRecordDto.setPeopleId(people.getId());
                manageRecordDto.setEmpower(rule.getType());
                manageRecordDto.setEquipmentId(e.getId());
                manageRecordDto.setStatus("0");
                manageRecordDto.setInfoDown("0");
                manageRecordDto.setRuleId(rule.getId());
                empowerRecordService.insertSysEmpowerRecord(manageRecordDto);
                /*String data=this.personCreate(person,ip,pass);
                JSONObject json= JSONObject.parseObject(data);
                String admitGuid="";
                String faceGuid="";
                if("1".equals(json.get("result")+"")) {
                    JSONObject obj= (JSONObject) json.get("data");
                    admitGuid=obj.get("id")+"";
                    String datas=this.imageCreateUrl(admitGuid,people.getAvatar(),ip,pass);
                    JSONObject jsons= JSONObject.parseObject(datas);
                    if("1".equals(jsons.get("result")+"")){
                        faceGuid=jsons.get("data")+"";
                    }
                    //保存到人员设备关联表中
                    SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
                    sysPeopleEquipment.setGuid(admitGuid);
                    sysPeopleEquipment.setFaceGuid(faceGuid);
                    sysPeopleEquipment.setPeopleId(people.getId());
                    sysPeopleEquipment.setEquipmentId(e.getId());
                    peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
                }
                //人员权限下发设备
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date  endTime=rule.getEndTime();
                response=this.permissionsCreate(admitGuid,sdf.format(endTime),ip,pass);
                JSONObject obj=new JSONObject();
                obj.put("personId",admitGuid);
                obj.put("passtime",rule.getAdmittanceStart()+","+rule.getAdmittanceEnd());
                this.createPasstime(obj,ip,pass);
                JSONObject jsons= JSONObject.parseObject(response);*/
               /* if("1".equals(jsons.get("result")+"")){//授权记录保存

                }else{
                    SysEmpowerRecord manageRecordDto=new SysEmpowerRecord();
                    manageRecordDto.setPeopleId(people.getId()+"");
                    manageRecordDto.setEmpower(rule.getType());
                    manageRecordDto.setEquipmentId(e.getId());
                    manageRecordDto.setStatus("0");
                    manageRecordDto.setInfoDown("1");
                    manageRecordDto.setRuleId(rule.getId());
                    empowerRecordService.insertSysEmpowerRecord(manageRecordDto);
                }*/
            }
        }
        return response;
    }

    @Override
    public int authDeviceAddUpdate(SysRule rule, SysPeople people, Integer operType) {
        int i = 0;
        String[] pointIds = rule.getPointId().split(",");
        List<SysEquipment> equipList = new ArrayList<>();
        for (String point : pointIds) {
            SysEquipment equipment = new SysEquipment();
            equipment.setPointId(Long.parseLong(point));
            equipment.setFlag("0");
            equipment.setIsCj("0");
            equipment.setProductId(3L);
            List<SysEquipment> equipmentDtoList = equipmentService.selectSysEquipmentList(equipment);
            equipList.addAll(equipmentDtoList);
        }

        List<SysEqDownRecord> downRecordList = new ArrayList<>();
        //通过规则获取绑定设备信息
        for (SysEquipment e : equipList) {
            SysEqDownRecord sysEqDownRecord = new SysEqDownRecord();
            sysEqDownRecord.setEquipmentId(e.getId());
            sysEqDownRecord.setPeopleId(people.getId());
            sysEqDownRecord.setRuleId(rule.getId());
            sysEqDownRecord.setOperType(operType);
            sysEqDownRecord.setDownTime(new Date());
            sysEqDownRecord.setFaceDownResult(1);

            //将人员信息下发到设备
            Person person = new Person();
            person.setName(people.getName());
            person.setIdcardNum(people.getDoorNo());
            person.setiDNumber(people.getIdcard());
            person.setPhone(people.getPhone());
            person.setId(people.getGuid());

            //删除人员信息
            if (operType == 1) {
                String data = this.personDelete(person.getId(), e.getIp(), e.getPassword());
                log.info("authDeviceAddUpdate-宇泛设备删除人员结果：{}", data);
                if (!verifyResult(data, sysEqDownRecord)) {
                    i++;
                    continue;
                }
            }

            //新增人员信息
            String data = this.personCreate(person, e.getIp(), e.getPassword());
            log.info("authDeviceAddUpdate-宇泛设备新增人员结果：{}", data);
            if (!verifyResult(data, sysEqDownRecord)) {
                i++;
                continue;
            }
            if (StringUtils.isNotEmpty(people.getFaceGuid())) {
                String dataImg = this.imageCreateUrl(people.getGuid(), people.getFaceGuid(), people.getAvatar(), e.getIp(), e.getPassword());
                log.info("authDeviceAddUpdate-宇泛设备新增人员人脸结果：{}", dataImg);
                if (!verifyResult(dataImg, sysEqDownRecord)) {
                    i++;
                    sysEqDownRecord.setFaceDownResult(1);
                } else {
                    sysEqDownRecord.setFaceDownResult(0);
                }
            }
            downRecordList.add(sysEqDownRecord);
        }

        //保存下发记录
        if (CollUtil.isNotEmpty(downRecordList)) {
            sysEqDownRecordService.saveBatch(downRecordList);
        }

        return i;
    }

    @Override
    public SysEqDownRecord authDeviceDown(SysPeopleEqDown sysPeopleEqDown) {
        SysEqDownRecord sysEqDownRecord = new SysEqDownRecord();
        sysEqDownRecord.setEquipmentId(sysPeopleEqDown.getEquipmentId());
        sysEqDownRecord.setPeopleId(sysPeopleEqDown.getPeopleId());
        sysEqDownRecord.setRuleId(sysPeopleEqDown.getRuleId());
        sysEqDownRecord.setOperType(2);
        sysEqDownRecord.setDownTime(new Date());
        sysEqDownRecord.setFaceDownResult(1);

        //将人员信息下发到设备
        Person person = new Person();
        person.setName(sysPeopleEqDown.getPeopleName());
        person.setIdcardNum(sysPeopleEqDown.getDoorNo());
        person.setiDNumber(sysPeopleEqDown.getIdcard());
        person.setPhone(sysPeopleEqDown.getPhone());
        person.setId(sysPeopleEqDown.getGuid());

        //删除人员信息
        String data = this.personDelete(person.getId(), sysPeopleEqDown.getIp(), sysPeopleEqDown.getPassword());
        if (!verifyResult(data, sysEqDownRecord)) {
            return sysEqDownRecord;
        }

        //新增人员信息
        String data1 = this.personCreate(person, sysPeopleEqDown.getIp(), sysPeopleEqDown.getPassword());
        if (!verifyResult(data1, sysEqDownRecord)) {
            return sysEqDownRecord;
        }

        if (StringUtils.isNotEmpty(sysPeopleEqDown.getFaceGuid())) {
            String dataImg = this.imageCreateUrl(sysPeopleEqDown.getGuid(), sysPeopleEqDown.getFaceGuid(), sysPeopleEqDown.getAvatar(), sysPeopleEqDown.getIp(), sysPeopleEqDown.getPassword());
            if (!verifyResult(dataImg, sysEqDownRecord)) {
                sysEqDownRecord.setFaceDownResult(1);
                return sysEqDownRecord;
            } else {
                sysEqDownRecord.setFaceDownResult(0);
            }
        }

        return sysEqDownRecord;
    }

    private Boolean verifyResult(String data, SysEqDownRecord eqDownRecord) {
        eqDownRecord.setMsg(data);
        JSONObject jsons = JSONObject.parseObject(data);
        if (jsons != null && jsons.containsKey("code") && StrUtil.equals("LAN_SUS-0", jsons.getString("code"))) {
            eqDownRecord.setDownResult(0);
            return true;
        } else {
            eqDownRecord.setDownResult(1);
            return false;
        }
    }

    @Override
    public String authDeviceNews(SysRule rule, SysPeople people) {
        String response="";
        String[] pointIds=rule.getPointId().split(",");
        List<SysEquipment> equipList=new ArrayList<>();
        if(pointIds!=null){
            for(String point:pointIds){
                SysEquipment equipment=new SysEquipment();
                equipment.setPointId(Long.parseLong(point));
                equipment.setFlag("0");
                equipment.setIsCj("0");
                equipment.setProductId(3L);
                List<SysEquipment> equipmentDtoList=equipmentService.selectSysEquipmentList(equipment);
                equipList.addAll(equipmentDtoList);
            }
        }
        //通过规则获取绑定设备信息
        if(equipList!=null){
            for(SysEquipment e:equipList){
                //将人员信息下发到设备
                Person person=new Person();
                person.setName(people.getName());
                person.setIdcardNum(people.getDoorNo());
                person.setiDNumber(people.getIdcard());
                person.setPhone(people.getPhone());
                person.setId(people.getGuid());
                String ip=e.getIp();
                String pass=e.getPassword();
                this.personDelete(people.getGuid(),ip,pass);
                response=this.personCreate(person,ip,pass);
                if(StringUtils.isNotEmpty(people.getFaceGuid())){//人脸
                    this.imageCreateUrl(people.getGuid(),people.getFaceGuid(),people.getAvatar(), e.getIp(), e.getPassword());
                }
            }
        }
        return response;
    }

    @Override
    public String authDevices(SysPeople people, SysEquipment equipment) {
        String response="";
        //将人员信息下发到设备
        Person person=new Person();
        person.setName(people.getName());
        person.setiDNumber(people.getIdcard());
        person.setIdcardNum(people.getDoorNo());
        person.setPhone(people.getPhone());
        person.setId(people.getGuid());
        String ip=equipment.getIp();
        String pass=equipment.getPassword();
        response=this.personCreate(person,ip,pass);
        this.imageCreateUrl(people.getGuid(),people.getAvatar(),ip,pass);
        return response;
    }
}
