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

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.system.domain.*;
import com.dcsoft.system.kq.domain.*;
import com.dcsoft.system.kq.service.*;
import com.dcsoft.system.ladder.domain.CardInfoVo;
import com.dcsoft.system.ladder.domain.PeopleInfoVo;
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.ParseException;
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 IKqGatherService kqGatherService;

    @Autowired
    private IKqGroupService kqGroupService;

    @Autowired
    private IKqClassesService kqClassesService;

    @Autowired
    private IKqClassesItemService kqClassesItemService;

    @Autowired
    private IKqHolidayGroupService kqHolidayGroupService;

    @Autowired
    private ISysPeopleService sysPeopleService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 卡权限创建接口
     */
    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 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/");
        }
        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/");
        }
        paramMap.put("imgUrl",imgUrl);
        String response= HttpUtil.sendxwwwform(url,paramMap);
        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);
                }

                // 梯控通行
                String s = ladderGeneral(e);
                if("500".equals(s)) {
                    continue;
                }

                response = "200";

                //授权记录保存
                if("200".equals(s) || "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 void insertKqxx(SysPeopleRecord peopleRecord) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        KqGroup group=kqGroupService.selectKqGroupByGroupId(peopleRecord.getGroupId());
        KqClasses classes= kqClassesService.selectKqClassesByClassesId(group.getClassesId());
        //判断是否是考勤时间打卡，不是的话就是加班，累计塞入考勤数据中
        Boolean flag=true;
        try {
            KqHolidayGroup holidayGroup =kqHolidayGroupService.selectKqHolidayGroupByHolidayTimeStamp(sdf.parse(sdf.format(new Date())).getTime(),peopleRecord.getGroupId());
            if(holidayGroup!=null){//周末加班
                flag=false;
                //查看排班情况
                KqGather gather=new KqGather();
                gather.setPeopleId(Long.parseLong(peopleRecord.getPeopleId()));
                SysPeople people=sysPeopleService.selectSysPeopleById(Long.parseLong(peopleRecord.getPeopleId()));
                try {
                    gather.setKqTime(sdf.parse(sdf.format(peopleRecord.getShowDate())));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                List<KqGather> list=kqGatherService.selectKqGatherList(gather);
                if(list.size()>0){//存在考勤结果
                    gather=list.get(0);
                    gather.setOutKqTime(peopleRecord.getShowDate());
                    gather.setOverTime((peopleRecord.getShowDate().getTime()-gather.getWorkKqTime().getTime())/1000/60+"");
                    kqGatherService.updateKqGather(gather);
                }else{
                    gather.setGroupId(peopleRecord.getGroupId());
                    gather.setGroupName(group.getGroupName());
                    gather.setClassesId(group.getClassesId());
                    if(people!=null){
//                        gather.setBranchId(people.getBranchId());
                    }
                    //查看班次
                    //查看打卡时间是否在规定范围内
                    gather.setWorkTime(classes.getMinUpTime());
                    gather.setWorkKqTime(peopleRecord.getShowDate());
                    gather.setWorkPeriod( classes.getMinUpTime()+"-"+classes.getMaxDownTime());
                    gather.setOutTime(classes.getMaxDownTime());
                    gather.setWorkStatus("3");//加班中
                    kqGatherService.insertKqGather(gather);
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if(flag){
            if("1".equals(classes.getIsDay())){//跨天汇总

            }else{//不垮天汇总
                //依据考勤记录进行考勤结果表的的判断
                //1.考勤结果表中没有该数据，判断正常上下班还是迟到早退
                KqGather gather=new KqGather();
                gather.setPeopleId(Long.parseLong(peopleRecord.getPeopleId()));
                try {
                    gather.setKqTime(sdf.parse(sdf.format(peopleRecord.getShowDate())));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                List<KqGather> list=kqGatherService.selectKqGatherList(gather);
                if(list.size()>0){//存在考勤结果
                    //判断是否在下班的时间端中，不在就是误打卡，不用管，在就是依次更新下班状态和上班状态
                    gather=list.get(0);
                    //判断排班考勤次数
                    //查看排班情况
                    if(classes.getClassesNum()==1){
                        gather.setOutKqTime(peopleRecord.getShowDate());
                        gather.setWorkStatus("2");//下班
                        gather.setOutTime(classes.getMaxDownTime());
                        try {
                            Long outKqTime=gather.getOutKqTime().getTime();
                            String outTime= sdf.format(gather.getOutKqTime())+" "+classes.getMaxDownTime();
                            Long ztTime = sdf1.parse(outTime).getTime();
                            if((ztTime-outKqTime)/1000/60>classes.getLaterTime()){
                                gather.setLeaveTime((ztTime-outKqTime)/1000/60+"");
                                gather.setOutStatus("2");//早退
                            }else{
                                gather.setOutStatus("1");//正常下班
                                gather.setLeaveTime("");
                                //判断加班时长（分钟）
                                gather.setOverTime((peopleRecord.getShowDate().getTime()-ztTime)/1000/60+"");
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        kqGatherService.updateKqGather(gather);
                    }
                    if(classes.getClassesNum()==2){
                        KqClassesItem kqClassesItem=new KqClassesItem();
                        kqClassesItem.setClassesId(classes.getClassesId());
                        List<KqClassesItem> itemList=kqClassesItemService.selectKqClassesItemList(kqClassesItem);
                        //判断当前打卡时间是否是第二轮上班前打的卡，如果是就存入第一轮下班打卡时间
                        try {//workStatus 0 初始状态，1上班中，2下班 outStatus 0 初始状态，1正常下班 2早退 itemList.get(1).getUp()
                            String workTime1= sdf.format(gather.getWorkKqTime())+" "+"12:30:00";
                            Long KqTime = sdf1.parse(workTime1).getTime()-classes.getLaterTime()*1000*60;
                            if(peopleRecord.getShowDate().getTime()<KqTime){//第二轮上班前打卡
                                gather.setOutKqTime(peopleRecord.getShowDate());
                                gather.setWorkStatus("2");//第一轮下班
                                try {//第一轮早退
                                    Long outKqTime=gather.getOutKqTime().getTime();
                                    String outTime= sdf.format(gather.getOutKqTime())+" "+itemList.get(0).getDown();
                                    Long ztTime = sdf1.parse(outTime).getTime();
                                    if((ztTime-outKqTime)/1000/60>classes.getLaterTime()){
                                        gather.setLeaveTime((ztTime-outKqTime)/1000/60+"");
                                        gather.setOutStatus("2");//早退
                                    }else{
                                        gather.setOutStatus("1");//正常下班
                                        gather.setWorkStatus("0");//上班状态置为0
                                        gather.setLeaveTime("");
                                    }
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }else{
                                // 如果不是判断当前打卡时间是否就存在第二轮下班时间前，如果是就存入第二轮上班打卡时间中，不是就存入到第二轮下班时间中
                                String workTime11= sdf.format(gather.getWorkKqTime())+" "+itemList.get(1).getDown();
                                Long KqTime1 = sdf1.parse(workTime11).getTime()-classes.getEarlyTime()*1000*60;
                                String isKq = configService.selectConfigByKey("sys_kq_dk");
                                if("true".equals(isKq)){
                                    gather.setOutKqTime1(peopleRecord.getShowDate());
                                    //判断加班时长
                                    String outTime= sdf.format(gather.getOutKqTime1())+" "+itemList.get(1).getDown();
                                    Long ztTime = sdf1.parse(outTime).getTime();
                                    gather.setOverTime((peopleRecord.getShowDate().getTime()-ztTime)/1000/60+"");
                                    gather.setOutStatus("1");//正常下班
                                    gather.setWorkStatus("2");//下班
                                }else{
                                    if(peopleRecord.getShowDate().getTime()<KqTime1){
                                        if(gather.getWorkKqTime1()==null){
                                            gather.setWorkKqTime1(peopleRecord.getShowDate());
                                            //第二轮迟到
                                            try {
                                                Long workKqTime1=gather.getWorkKqTime1().getTime();
                                                String workTime= sdf.format(gather.getWorkKqTime1())+" "+itemList.get(1).getUp();
                                                Long KqTime11 = sdf1.parse(workTime).getTime();
                                                if((workKqTime1-KqTime11)/1000/60>classes.getEarlyTime()){
                                                    gather.setLateTime((workKqTime1-KqTime11)/1000/60+"");
                                                }
                                                gather.setWorkStatus("1");//上班中
                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                            }
                                        }else{
                                            //判断早退时间
                                            gather.setOutKqTime1(peopleRecord.getShowDate());
                                            //第二轮早退
                                            try {
                                                Long outKqTime=gather.getOutKqTime1().getTime();
                                                String outTime= sdf.format(gather.getOutKqTime1())+" "+itemList.get(1).getDown();
                                                Long ztTime = sdf1.parse(outTime).getTime();
                                                if((ztTime-outKqTime)/1000/60>classes.getLaterTime()){
                                                    gather.setLeaveTime((ztTime-outKqTime)/1000/60+"");
                                                    gather.setOutStatus("2");//早退
                                                }else{
                                                    gather.setOutStatus("1");//正常下班
                                                    gather.setWorkStatus("2");//第一轮下班
                                                    gather.setLeaveTime("");
                                                }
                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                            }
                                        }

                                    }else{
                                        gather.setOutKqTime1(peopleRecord.getShowDate());
                                        //判断加班时长
                                        String outTime= sdf.format(gather.getOutKqTime1())+" "+itemList.get(1).getDown();
                                        Long ztTime = sdf1.parse(outTime).getTime();
                                        gather.setOverTime((peopleRecord.getShowDate().getTime()-ztTime)/1000/60+"");
                                        gather.setOutStatus("1");//正常下班
                                        gather.setWorkStatus("2");//下班
                                    }
                                }
                            }
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }

                        kqGatherService.updateKqGather(gather);
                    }
                    /*if(classes.getClassesNum()==3){
                        KqClassesItem kqClassesItem=new KqClassesItem();
                        kqClassesItem.setClassesId(classes.getClassesId());
                        List<KqClassesItem> itemList=kqClassesItemService.selectKqClassesItemList(kqClassesItem);
                        //判断当前打卡时间是否是第一轮上班前打的卡，如果是就存入第一轮下班打卡时间段
                        // 如果不是判断当前打卡时间是否就存在第二轮下班班时间前，如果是就存入第二轮上班打卡时间中
                        try {
                            String workTime1= sdf.format(gather.getWorkKqTime())+" "+itemList.get(1).getUp();
                            Long KqTime = sdf1.parse(workTime1).getTime()-classes.getLaterTime()*1000*60;
                            if(peopleRecord.getShowDate().getTime()<KqTime){//第一次上班前打卡
                                gather.setOutKqTime(peopleRecord.getShowDate());
                                gather.setWorkStatus("2");//第一轮下班
                            }else{
                                // 如果不是判断当前打卡时间是否就存在第二轮下班班时间前，如果是就存入第二轮上班打卡时间中，不是就存入到第二轮下班时间中
                                String workTime11= sdf.format(gather.getWorkKqTime())+" "+itemList.get(1).getDown();
                                Long KqTime1 = sdf1.parse(workTime11).getTime()+classes.getEarlyTime()*1000*60;
                                if(peopleRecord.getShowDate().getTime()<KqTime1){
                                    if(gather.getWorkKqTime1()==null){
                                        gather.setWorkKqTime1(peopleRecord.getShowDate());
                                    }
                                }else{
                                    //如果不是判断当前打卡时间是否就存在第三轮下班时间前，如果是就存入第三轮上班打卡时间中
                                    gather.setOutKqTime1(peopleRecord.getShowDate());
                                    String workTime12= sdf.format(gather.getWorkKqTime())+" "+itemList.get(2).getDown();
                                    Long KqTime2 = sdf1.parse(workTime12).getTime()+classes.getEarlyTime()*1000*60;
                                    if(peopleRecord.getShowDate().getTime()<KqTime2){
                                        if(gather.getWorkKqTime2()==null){
                                            gather.setWorkKqTime2(peopleRecord.getShowDate());
                                        }
                                    }else{
                                        gather.setOutKqTime2(peopleRecord.getShowDate());
                                    }
                                }
                            }
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        kqGatherService.updateKqGather(gather);
                    }*/

                }else{
                    //查看排班情况
                    SysPeople people=sysPeopleService.selectSysPeopleById(Long.parseLong(peopleRecord.getPeopleId()));
                    gather.setGroupId(peopleRecord.getGroupId());
                    gather.setGroupName(group.getGroupName());
                    gather.setClassesId(group.getClassesId());
                    if(people!=null){
//                        gather.setBranchId(people.getBranchId());
                    }
                    //查看班次
                    //查看打卡时间是否在规定范围内
                    gather.setWorkTime(classes.getMinUpTime());
                    gather.setWorkKqTime(peopleRecord.getShowDate());
                    gather.setOutTime(classes.getMaxDownTime());
                    try {
                        Long workKqTime=gather.getWorkKqTime().getTime();
                        String workTime= sdf.format(gather.getWorkKqTime())+" "+classes.getMinUpTime();
                        Long KqTime = sdf1.parse(workTime).getTime();
                        if((workKqTime-KqTime)/1000/60>classes.getEarlyTime()){
                            gather.setLateTime((workKqTime-KqTime)/1000/60+"");
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gather.setWorkPeriod( classes.getMinUpTime()+"-"+classes.getMaxDownTime());
                    gather.setWorkStatus("1");//上班中
                    if(classes.getClassesNum()==2) {
                        KqClassesItem kqClassesItem = new KqClassesItem();
                        kqClassesItem.setClassesId(classes.getClassesId());
                        List<KqClassesItem> itemList = kqClassesItemService.selectKqClassesItemList(kqClassesItem);
                        gather.setOutTime(itemList.get(0).getDown());
                        gather.setWorkTime1(itemList.get(1).getUp());
                        gather.setOutTime1(itemList.get(1).getDown());
                    }
                    kqGatherService.insertKqGather(gather);
                }
            }
        }
    }

    @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());
                    }
                }

               /* // 梯控通行
                String s = ladderGeneral(e);
                if("500".equals(s)) {
                    continue;
                }*/

                //保存下发记录
                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 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;
    }


    /**
     * 梯控通行
     * @param sysEquipment
     */
    private String ladderGeneral(SysEquipment sysEquipment) {
        String response = null;
        if(5L == sysEquipment.getProductId()) {
            try {
                PeopleInfoVo infoVo = new PeopleInfoVo();
                infoVo.setDoorNo(infoVo.getDoorNo());
                deviceDistribute(sysEquipment, infoVo);
                response = "200";
            } catch (Exception exception) {
                log.error("梯控卡权限创建接口异常（设备ip" + sysEquipment.getIp() + "）" + exception);
                 response = "500";
            }
            log.info("梯控卡权限创建接口（设备ip:" + sysEquipment.getIp() + "）");
        }
        return response;
    }

    /**
     * 卡权限创建接口
     */
    private void deviceDistribute(SysEquipment sysEquipment, PeopleInfoVo peopleInfoVo) {
        if(StringUtils.isNotEmpty(peopleInfoVo.getDoorNo())) {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> map = new HashMap<>();
            CardInfoVo infoVo = new CardInfoVo();
            infoVo.setIdcardnum(peopleInfoVo.getDoorNo());
            infoVo.setFloortype(Constants.ZERO);
            infoVo.setFloor("");
            infoVo.setCalltype(Constants.ONE);
            infoVo.setCustomertype(Constants.FIVE);
            infoVo.setStarttime(dateformat.format(new Date()));
            infoVo.setEndtime(Constants.END_TIME);
            infoVo.setStartdaytime(Constants.START_DAY_TIME);
            infoVo.setEnddaytime(Constants.END_DAY_TIME);
            infoVo.setWeek(Constants.WEEK);
            map.put("cardinfo", infoVo);
            map.put("pass", sysEquipment.getPassword());
            String body = cn.hutool.http.HttpUtil.createPost("http://" + sysEquipment.getIp() + ":8090" + create).timeout(1000).body(JSON.toJSONString(map)).execute().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());
            }
        }
    }

}
