package com.dcsoft.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.domain.R;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.utils.uuid.IdUtils;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.web.page.TableDataInfo;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.RemoteFileService;
import com.dcsoft.system.api.domain.SysFile;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.domain.vo.JjserInfoVo;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.Person;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import com.dcsoft.system.utils.PictureUtils;
import com.dcsoft.system.visitor.service.IVisitorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 人员管理Controller
 *
 * @author nichun
 * @date 2023-03-08
 */
@RestController
@RequestMapping("/sysPeople")
@Slf4j
public class SysPeopleController extends BaseController
{
    @Autowired
    private ISysPeopleService sysPeopleService;

    @Autowired
    private ISysEqDownRecordService sysEqDownRecordService;

    @Autowired
    protected ISysSdkService sdkService;

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private RemoteFileService fileService;

    @Autowired
    protected ISysPeopleEquipmentService peopleEquipmentService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysBranchService sysBranchService;

    @Autowired
    private ISysRuleService sysRuleService;

    @Autowired
    private ISysPeopleRuleService sysPeopleRuleService;

    @Autowired
    private IVisitorService visitorService;

    @Value("${park.tdGuid}")
    public String tdGuid;

    public static ExecutorService service = Executors.newFixedThreadPool(10);


    /**
     * 查询人员管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysPeople sysPeople)
    {
        List<SysPeople> list = sysPeopleService.selectSysPeopleList(sysPeople);
        return getDataTable(list);
    }

    @GetMapping("/queryPeopleList")
    public AjaxResult queryPeopleList(SysPeople sysPeople) {
        List<SysPeople> list = sysPeopleService.queryPeopleList(sysPeople);
        return success(list);
    }

    /**
     * 导出人员管理列表
     */
    @RequiresPermissions("system:sysPeople:export")
    @Log(title = "人员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPeople sysPeople)
    {
        List<SysPeople> list = sysPeopleService.selectSysPeopleLists(sysPeople);
        ExcelUtil<SysPeople> util = new ExcelUtil<SysPeople>(SysPeople.class);
        util.exportExcel(response, list, "人员管理数据");
    }

    /**
     * 获取人员管理详细信息
     */
    @RequiresPermissions("system:sysPeople:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        SysPeople sysPeople = sysPeopleService.selectSysPeopleById(id);
        if (StrUtil.isNotBlank(sysPeople.getCarryStuffExamine())) {
            sysPeople.setCarryStuffExamineList(Arrays.asList(sysPeople.getCarryStuffExamine().split(",")));
        }
        return success(sysPeople);
    }

    /**
     * 新增人员管理
     */
    @RequiresPermissions("system:sysPeople:add")
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody SysPeople sysPeople) {
        log.info("新增人员管理：{}", JSON.toJSONString(sysPeople));
        SysPeople people = sysPeopleService.selectSysPeopleByGh(sysPeople.getGh());
        if (people != null) {
            return error("该工号已存在");
        }

        if (StringUtils.isNotEmpty(sysPeople.getDoorNo())) {
            SysPeople doorNo = sysPeopleService.selectSysPeopleByDoorNo(sysPeople.getDoorNo());
            if (doorNo != null) {
                return error("该门禁号已存在");
            }
        }

        if (StringUtils.isNotEmpty(sysPeople.getAvatar())) {
            sysPeople.setFaceGuid(IdUtils.simpleUUID());
        }
        sysPeople.setGuid(IdUtils.simpleUUID());

        //携物出门审核人
        if (CollUtil.isNotEmpty(sysPeople.getCarryStuffExamineList())) {
            sysPeople.setCarryStuffExamine(String.join(",", sysPeople.getCarryStuffExamineList()));
        }

        sysPeopleService.insertSysPeople(sysPeople);

        //下发设备
        if (StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            SysBranch branch = sysBranchService.selectSysBranchById(sysPeople.getBranchId());
            if (null != branch.getRuleId()) {
                //添加人员授权信息
                SysRule rule = sysRuleService.selectSysRuleById(branch.getRuleId());
                int i = sdkService.authDeviceAddUpdate(rule, sysPeople, 0);
                if (i > 0) {
                    throw new ServiceException(i + "个设备下发失败！");
                }
                sysPeople.setDown(1L);
            }
        }

        return toAjax(true);
    }


    /**
     * 修改人员管理
     */
    @RequiresPermissions("system:sysPeople:edit")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysPeople sysPeople) {
        log.info("修改人员管理：{}", JSON.toJSONString(sysPeople));
        SysPeople people = sysPeopleService.selectSysPeopleByGh(sysPeople.getGh());
        if (people != null && !people.getId().equals(sysPeople.getId())) {
            return error("该工号已存在");
        }

        if (StringUtils.isNotEmpty(sysPeople.getDoorNo())) {
            SysPeople doorNo = sysPeopleService.selectSysPeopleByDoorNo(sysPeople.getDoorNo());
            if (doorNo != null && !doorNo.getId().equals(sysPeople.getId())) {
                return error("该门禁号已存在");
            }
        }

        SysPeople peopleById = sysPeopleService.selectSysPeopleById(sysPeople.getId());

        if (StringUtils.isBlank(peopleById.getFaceGuid())) {
            sysPeople.setFaceGuid(IdUtils.simpleUUID());
        } else {
            sysPeople.setFaceGuid(peopleById.getFaceGuid());
        }

        sysPeople.setGuid(peopleById.getGuid());

        //下发设备
        if (StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            SysBranch branch = sysBranchService.selectSysBranchById(sysPeople.getBranchId());
            if (null != branch.getRuleId()) {
                //添加人员授权信息
                SysRule rule = sysRuleService.selectSysRuleById(branch.getRuleId());
                int i = sdkService.authDeviceAddUpdate(rule, sysPeople, 1);
                if (i > 0) {
                    return AjaxResult.error(i + "个设备下发失败！");
                }
                sysPeople.setDown(1L);
            }
        }


        if (CollUtil.isNotEmpty(sysPeople.getCarryStuffExamineList())) {
            sysPeople.setCarryStuffExamine(String.join(",", sysPeople.getCarryStuffExamineList()));
        }
        return toAjax(sysPeopleService.updateSysPeople(sysPeople));
    }


    @Log(title = "手机端人员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult update(@RequestBody SysPeople sysPeople) {
        log.info("手机端修改人员管理：{}", JSON.toJSONString(sysPeople));
        SysPeople peopleById = sysPeopleService.selectSysPeopleById(sysPeople.getId());

        if (StringUtils.isBlank(peopleById.getFaceGuid())) {
            sysPeople.setFaceGuid(IdUtils.simpleUUID());
        } else {
            sysPeople.setFaceGuid(peopleById.getFaceGuid());
        }
        sysPeople.setGuid(peopleById.getGuid());

        //下发设备
        if (StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            SysBranch branch = sysBranchService.selectSysBranchById(sysPeople.getBranchId());
            if (null != branch.getRuleId()) {
                //添加人员授权信息
                SysRule rule = sysRuleService.selectSysRuleById(branch.getRuleId());
                int i = sdkService.authDeviceAddUpdate(rule, sysPeople, 1);
                if (i > 0) {
                    return AjaxResult.error(i + "个设备下发失败！");
                }
                sysPeople.setDown(1L);
            }
        }

        return toAjax(sysPeopleService.updateSysPeople(sysPeople));
    }


    /**
     * 删除人员管理
     */
    @RequiresPermissions("system:sysPeople:remove")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<SysPeople> peopleList = sysPeopleService.selectSysPeopleListByIds(Arrays.asList(ids));
        if (CollUtil.isNotEmpty(peopleList)) {
            String admitGuids = peopleList.stream().map(SysPeople::getGuid).collect(Collectors.joining(","));
            if (StringUtils.isNotBlank(admitGuids)) {
                log.info("设备删除人员：{}", admitGuids);
                SysEquipment equipment = new SysEquipment();
                equipment.setFlag("0");
                equipment.setProductId(3L);
                List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
                for (SysEquipment e : list) {
                    String data = sdkService.personDelete(admitGuids, e.getIp(), e.getPassword());
                    log.info("remove-宇泛设备删除人员结果：{}", data);
                    JSONObject jsons = JSONObject.parseObject(data);
                    if (jsons == null || !jsons.containsKey("code") || !StrUtil.equals("LAN_SUS-0", jsons.getString("code"))) {
                        throw new ServiceException("人员删除失败：设备" + e.getIp() + "删除异常");
                    }
                }
            }
        }

        //删除下发记录
        sysEqDownRecordService.deleteByPeopleIds(Arrays.asList(ids));

        //暂未处理离线设备人员数据删除
        return toAjax(sysPeopleService.deleteSysPeopleByIds(ids));
    }

    /**
     * 获取人员管理详细信息
     */
    @GetMapping(value = "/getUser/{userId}")
    public AjaxResult getUser(@PathVariable("userId") Long userId)
    {
        return success(sysPeopleService.selectSysPeopleByUserId(userId));
    }

    /**
     * 获取人员管理详细信息
     */
    @GetMapping(value = "/queryPeopleById")
    public AjaxResult queryPeopleById(String id)
    {
        return success(sysPeopleService.queryPeopleById(id));
    }

    /**
     * 获取人员管理详细信息
     */
    @GetMapping(value = "/getUserName/{branchName}/{userName}")
    public AjaxResult getUserName(@PathVariable("branchName") String branchName,@PathVariable("userName") String userName)
    {
        return success(sysPeopleService.selectSysPeopleByBranchUser(branchName,userName));
    }

    /**
     * 指纹采集
     */
    @PutMapping(value = "/dactylogram")
    public AjaxResult dactylogram(@RequestBody SysPeople sysPeople) {
        SysEquipment equipment=new SysEquipment();
        equipment.setIsCj("1");
        List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
        if (list.size() > 0) {
            String ip = list.get(0).getIp();
            String pass = list.get(0).getPassword();
            String flag = list.get(0).getFlag();
            if("0".equals(flag)){
                if (StringUtils.isEmpty(sysPeople.getGuid())) {
                    //判断设备人员是否能注册上设备后再删除掉
                    Person person = new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    String data = sdkService.personCreate(person, ip, pass);
                    JSONObject json = JSONObject.parseObject(data);
                    if ("1".equals(json.get("result") + "")) {
                        JSONObject obj = (JSONObject) json.get("data");
                        String admitGuid = obj.get("id") + "";
                        sysPeople.setGuid(admitGuid);
                        //注册指纹
                        String datas = sdkService.fingerRegist(admitGuid, ip, pass);
                    } else {
                        return error(json.get("msg") + "");
                    }
                }else {//只注册指纹
                    String data = sdkService.fingerRegist(sysPeople.getGuid(), ip, pass);
                }
            }else {
                return error("采集设备已离线");
            }
        }

        return success(sysPeople);
    }

    /**
     * 人脸采集
     */
    @PutMapping(value = "/faceCollect")
    public AjaxResult faceCollect(@RequestBody SysPeople sysPeople) {
        //查询当前用户默认的采集端
        Long userId=SecurityUtils.getUserId();
        SysUser user=userService.selectUserById(userId);
        if(user.getEquipmentId()!=null){
            SysEquipment equipment = equipmentService.selectSysEquipmentById(user.getEquipmentId());
            String ip = equipment.getIp();
            String pass = equipment.getPassword();
            String flag = equipment.getFlag();
            if("0".equals(flag)){
                if (StringUtils.isEmpty(sysPeople.getGuid())) {
                    //判断设备人员是否能注册上设备后再删除掉
                    Person person = new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    String data = sdkService.personCreate(person, ip, pass);
                    JSONObject json = JSONObject.parseObject(data);
                    if ("1".equals(json.get("result") + "")) {
                        JSONObject obj = (JSONObject) json.get("data");
                        String admitGuid = obj.get("id") + "";
                        sysPeople.setGuid(admitGuid);
                        //注册人脸
                        String datas = sdkService.takeImg(admitGuid, ip, pass);
                    } else {
                        return error(json.get("msg") + "");
                    }
                }else {//只注册人脸
                    //删除采集设备已有人脸
                    Person person = new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    person.setId(sysPeople.getGuid());
                    sdkService.personCreate(person, ip, pass);
                    try{
                        SysPeople people = sysPeopleService.selectByGuid(sysPeople);
                        if(StringUtils.isNotEmpty(people.getFaceGuid())){
                            sdkService.imageDeletel(people.getFaceGuid(),ip,pass);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    String data = sdkService.takeImg(sysPeople.getGuid(), ip, pass);
                }
            }else {
                return error("采集设备已离线");
            }
        }else{
            SysEquipment equipment=new SysEquipment();
            equipment.setIsCj("1");
            List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
            if (list.size() > 0) {
                String ip = list.get(0).getIp();
                String pass = list.get(0).getPassword();
                String flag = list.get(0).getFlag();
                if("0".equals(flag)){
                    if (StringUtils.isEmpty(sysPeople.getGuid())) {
                        //判断设备人员是否能注册上设备后再删除掉
                        Person person = new Person();
                        person.setName(sysPeople.getName());
                        person.setiDNumber(sysPeople.getIdcard());
                        person.setPhone(sysPeople.getPhone());
                        String data = sdkService.personCreate(person, ip, pass);
                        JSONObject json = JSONObject.parseObject(data);
                        if ("1".equals(json.get("result") + "")) {
                            JSONObject obj = (JSONObject) json.get("data");
                            String admitGuid = obj.get("id") + "";
                            sysPeople.setGuid(admitGuid);
                            //注册人脸
                            String datas = sdkService.takeImg(admitGuid, ip, pass);
                        } else {
                            return error(json.get("msg") + "");
                        }
                    }else {//只注册人脸
                        //删除采集设备已有人脸
                        try{
                            SysPeople people = sysPeopleService.selectByGuid(sysPeople);
                            sdkService.imageDeletel(people.getFaceGuid(),ip,pass);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        String data = sdkService.takeImg(sysPeople.getGuid(), ip, pass);
                    }
                }else {
                    return error("采集设备已离线");
                }
            }
        }


        return success(sysPeople);
    }

    /**
     * 注册卡号
     */
    @PutMapping(value = "/icCardRegist")
    public AjaxResult icCardRegist(@RequestBody SysPeople sysPeople) {
        Long userId=SecurityUtils.getUserId();
        SysUser user=userService.selectUserById(userId);
        if(user.getEquipmentId()!=null){
            SysEquipment equipment = equipmentService.selectSysEquipmentById(user.getEquipmentId());
            String ip = equipment.getIp();
            String pass = equipment.getPassword();
            String flag = equipment.getFlag();
            if("0".equals(flag)){
                if (StringUtils.isEmpty(sysPeople.getGuid())) {
                    //判断设备人员是否能注册上设备后再删除掉
                    Person person = new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    String data = sdkService.personCreate(person, ip, pass);
                    JSONObject json = JSONObject.parseObject(data);
                    if ("1".equals(json.get("result") + "")) {
                        JSONObject obj = (JSONObject) json.get("data");
                        String admitGuid = obj.get("id") + "";
                        sysPeople.setGuid(admitGuid);
                        //注册门卡
                        String datas = sdkService.icCardRegist(admitGuid, ip, pass);
                    } else {
                        return error(json.get("msg") + "");
                    }
                }else {//注册门卡
                    sdkService.personDelete(sysPeople.getGuid(), ip, pass);
                    Person person = new Person();
                    person.setName(sysPeople.getName());
                    person.setiDNumber(sysPeople.getIdcard());
                    person.setPhone(sysPeople.getPhone());
                    person.setId(sysPeople.getGuid());
                    person.setIdcardNum("");
                    String data = sdkService.personCreate(person, ip, pass);
                    JSONObject json = JSONObject.parseObject(data);
                    if ("1".equals(json.get("result") + "")) {
                        JSONObject obj = (JSONObject) json.get("data");
                        String admitGuid = obj.get("id") + "";
                        sysPeople.setGuid(admitGuid);
                        //注册门卡
                        String datas = sdkService.icCardRegist(admitGuid, ip, pass);
                    }
                }
            }else {
                return error("采集设备已离线");
            }
        }else{
            SysEquipment equipment=new SysEquipment();
            equipment.setIsCj("1");
            List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
            if (list.size() > 0) {
                String ip = list.get(0).getIp();
                String pass = list.get(0).getPassword();
                String flag = list.get(0).getFlag();
                if("0".equals(flag)){
                    if (StringUtils.isEmpty(sysPeople.getGuid())) {
                        //判断设备人员是否能注册上设备后再删除掉
                        Person person = new Person();
                        person.setName(sysPeople.getName());
                        person.setiDNumber(sysPeople.getIdcard());
                        person.setPhone(sysPeople.getPhone());
                        String data = sdkService.personCreate(person, ip, pass);
                        JSONObject json = JSONObject.parseObject(data);
                        if ("1".equals(json.get("result") + "")) {
                            JSONObject obj = (JSONObject) json.get("data");
                            String admitGuid = obj.get("id") + "";
                            sysPeople.setGuid(admitGuid);
                            //注册门卡
                            String datas = sdkService.icCardRegist(admitGuid, ip, pass);
                        } else {
                            return error(json.get("msg") + "");
                        }
                    }else {//注册门卡
                        //删除门卡
                        Person person = new Person();
                        person.setName(sysPeople.getName());
                        person.setiDNumber(sysPeople.getIdcard());
                        person.setPhone(sysPeople.getPhone());
                        person.setId(sysPeople.getGuid());
                        person.setIdcardNum("");
                        sdkService.personCreate(person, ip, pass);

                        String data = sdkService.icCardRegist(sysPeople.getGuid(), ip, pass);
                    }
                }else {
                    return error("采集设备已离线");
                }
            }
        }
        return success(sysPeople);
    }

    /**
     * 人脸采集
     */
    @PutMapping(value = "/featureInfo")
    public AjaxResult featureInfo(@RequestBody SysPeople sysPeople) {
        SysEquipment equipment=new SysEquipment();
        equipment.setIsCj("1");
        List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
        try{
            if (list.size() > 0) {
                String ip = list.get(0).getIp();
                String pass = list.get(0).getPassword();
                //指纹查询
                String data = sdkService.featureInfo(sysPeople.getGuid(), ip, pass);
                JSONObject json = JSONObject.parseObject(data);
                if (StringUtils.isNotEmpty(json.get("data") + "")) {
                    JSONArray obj = (JSONArray) json.get("data");
                    if(obj!=null){
                        if(obj.get(0)!=null){
                            JSONObject objs = (JSONObject) obj.get(0);
                            String feature=objs.get("feature")+"";
                            sysPeople.setFingerprint(feature);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return success(sysPeople);
    }



    /*
       * 人脸获取
     */
    @PutMapping(value = "/faceFind")
    public AjaxResult faceFind(@RequestBody SysPeople sysPeople) {
        Long userId=SecurityUtils.getUserId();
        SysUser user=userService.selectUserById(userId);
        if(user.getEquipmentId()!=null){
            SysEquipment equipment = equipmentService.selectSysEquipmentById(user.getEquipmentId());
            String ip = equipment.getIp();
            String pass = equipment.getPassword();
            //人脸查询
            String data = sdkService.faceFind(sysPeople.getGuid(), ip, pass);
            JSONObject json = JSONObject.parseObject(data);
            if (StringUtils.isNotEmpty(json.get("data")+"")) {
                JSONArray obj = (JSONArray) json.get("data");
                if(obj!=null){
                    if(StringUtils.isNotEmpty(obj.get(0)+"")){
                        JSONObject objs = (JSONObject) obj.get(0);
                        String path=objs.get("path")+"";
                        String facleId=objs.get("faceId")+"";
                        if(StringUtils.isNotEmpty(path)){
                            //String paths=getImg(path,ip,pass);
                            //http://192.168.1.30:8090/download/image?pass=123123aa&filename=/data/record/RegisterPhoto//2023-07-28/17/173420_310.jpg
                            String urls="http://"+ip+":8090/download/image?pass="+pass+"&filename="+path;
                            MultipartFile file= PictureUtils.createMultipartFile(urls,facleId+".jpg");
                            R<SysFile> datas= fileService.uploadMinio(file,facleId);
                            sysPeople.setAvatar(datas.getData().getUrl());
                            sysPeople.setFaceGuid(facleId);
                        }
                    }
                }
            }
        }else{
            SysEquipment equipment=new SysEquipment();
            equipment.setIsCj("1");
            List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
            try{
                if (list.size() > 0) {
                    String ip = list.get(0).getIp();
                    String pass = list.get(0).getPassword();
                    //人脸查询
                    String data = sdkService.faceFind(sysPeople.getGuid(), ip, pass);
                    JSONObject json = JSONObject.parseObject(data);
                    if (StringUtils.isNotEmpty(json.get("data")+"")) {
                        JSONArray obj = (JSONArray) json.get("data");
                        if(obj!=null){
                            if(StringUtils.isNotEmpty(obj.get(0)+"")){
                                JSONObject objs = (JSONObject) obj.get(0);
                                String path=objs.get("path")+"";
                                String facleId=objs.get("faceId")+"";
                                if(StringUtils.isNotEmpty(path)){
                                    //String paths=getImg(path,ip,pass);
                                    //http://192.168.1.30:8090/download/image?pass=123123aa&filename=/data/record/RegisterPhoto//2023-07-28/17/173420_310.jpg
                                    String urls="http://"+ip+":8090/download/image?pass="+pass+"&filename="+path;
                                    MultipartFile file= PictureUtils.createMultipartFile(urls,facleId+".jpg");
                                    R<SysFile> datas= fileService.uploadMinio(file,facleId);
                                    sysPeople.setAvatar(datas.getData().getUrl());
                                    sysPeople.setFaceGuid(facleId);
                                }
                            }
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return success(sysPeople);
    }

    /*
     * 人脸获取
     */
    @PutMapping(value = "/personFind")
    public AjaxResult personFind(@RequestBody SysPeople sysPeople) {
        Long userId=SecurityUtils.getUserId();
        SysUser user=userService.selectUserById(userId);
        if(user.getEquipmentId()!=null){
            SysEquipment equipment = equipmentService.selectSysEquipmentById(user.getEquipmentId());
            String ip = equipment.getIp();
            String pass = equipment.getPassword();
            //人脸查询
            String data = sdkService.personFind(sysPeople.getGuid(), ip, pass);
            JSONObject json = JSONObject.parseObject(data);
            if ("1".equals(json.get("result") + "")) {
                JSONArray obj = (JSONArray) json.get("data");
                if(obj!=null){
                    if(StringUtils.isNotEmpty(obj.get(0)+"")){
                        JSONObject objs = (JSONObject) obj.get(0);
                        String idcardNum=objs.get("idcardNum")+"";
                        sysPeople.setDoorNo(idcardNum.replaceFirst("^0*",""));
                    }
                }
            }
        }else{
            SysEquipment equipment=new SysEquipment();
            equipment.setIsCj("1");
            List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
            try{
                if (list.size() > 0) {
                    String ip = list.get(0).getIp();
                    String pass = list.get(0).getPassword();
                    //人脸查询
                    String data = sdkService.personFind(sysPeople.getGuid(), ip, pass);
                    JSONObject json = JSONObject.parseObject(data);
                    if ("1".equals(json.get("result") + "")) {
                        JSONArray obj = (JSONArray) json.get("data");
                        if(obj!=null){
                            if(StringUtils.isNotEmpty(obj.get(0)+"")){
                                JSONObject objs = (JSONObject) obj.get(0);
                                String idcardNum=objs.get("idcardNum")+"";
                                sysPeople.setDoorNo(idcardNum.replaceFirst("^0*",""));
                            }
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        return success(sysPeople);
    }


    @GetMapping("/down/{ids}")
    public AjaxResult down(@PathVariable Long[] ids)
    {

        SysEquipment equipment=new SysEquipment();
        equipment.setFlag("0");
        equipment.setProductId(3L);
        List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
        if (CollUtil.isNotEmpty(list)) {
            for (Long id : ids) {//下发到设备上
                SysPeople people = sysPeopleService.selectSysPeopleById(id);
                //下发设备
                if (people.getBranchId() != null) {
                    SysBranch branch = sysBranchService.selectSysBranchById(people.getBranchId());
                    if (branch.getRuleId() != null) {
                        //添加人员授权信息
                        SysRule rule = sysRuleService.selectSysRuleById(branch.getRuleId());
                        String data = sdkService.authDeviceNew(rule, people);
                        people.setDown(1L);
                        if ("".equals(data)) {
                            return AjaxResult.error("该规则未绑定设备!");
                        }
                    }
                }
                sysPeopleService.updateSysPeople(people);
            }
        }
        return toAjax(1);
    }


    @Log(title = "人员信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:sysPeople:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysPeople> util = new ExcelUtil<SysPeople>(SysPeople.class);
        List<SysPeople> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = sysPeopleService.importPeople(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<SysPeople> util = new ExcelUtil<SysPeople>(SysPeople.class);
        util.importTemplateExcel(response, "人员信息数据");
    }

    /**
     * 定时批量下发
     */
    @PostMapping("/batchDistribute")
    public void batchDistribute() {
        List<SysPeople> ids = sysPeopleService.queryPeopleInfo();
        if(!CollectionUtils.isEmpty(ids)) {
            Long[] array = (Long[]) ids.stream().map(SysPeople::getId).toArray();
            down(array);
        }
    }


    /**
     * 同步人员（锦江）
     */
    @PostMapping("/saveUserInfo")
    public void saveUserInfo(SysBranch space) {
        HttpResponse response;
        if(Constants.ZERO.equals(space.getType())) {
            response = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getAccount")
                    .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                    .execute();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            response = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getAccount?ts=" + sdf.format(new Date()))
                    .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                    .execute();
        }
        String body = response.body();
        JSONObject object = JSONObject.parseObject(body);
        if(!Constants.CODE.equals(object.get("code").toString())) {
            throw new ServiceException("人员接口请求异常");
        }
        List<JjserInfoVo> data = JSONObject.parseArray(object.get("data").toString(), JjserInfoVo.class);
        if(CollectionUtils.isEmpty(data)) {
            return;
        }
        List<JjserInfoVo> list = new ArrayList<>();
        for (JjserInfoVo datum : data) {
            datum.setDelFlag(Constants.ZERO);
            if(Constants.FIVE.equals(datum.getStatus())) {
                JjserInfoVo infoVo = new JjserInfoVo();
                infoVo.setWorkcode(datum.getWorkcode());
                list.add(infoVo);
            }
        }
        if(!CollectionUtils.isEmpty(list)) {
            List<String> collectStr = list.stream().map(JjserInfoVo::getWorkcode).collect(Collectors.toList());
            List<SysPeople> ids = sysPeopleService.queryPeople(collectStr);
            if(!CollectionUtils.isEmpty(ids)) {
                Long[] collect = ids.stream().map(SysPeople::getId).toArray(Long[]::new);
                remove(collect);
            }
        }
        List<JjserInfoVo> collect = data.stream().filter(e -> !Constants.FIVE.equals(e.getStatus())).collect(Collectors.toList());
        sysBranchService.saveUserInfo(collect);
    }


    /**
     * 定时批量下发
     */
    @PostMapping("/batchDown")
    public void batchDown() {
        startPage();
        SysPeopleRule sysPeopleRule= new SysPeopleRule();
        sysPeopleRule.setSync(0L);
        List<SysPeopleRule>  List=sysPeopleRuleService.selectSysPeopleRuleList(sysPeopleRule);
        for(SysPeopleRule p:List){
            SysPeople people=sysPeopleService.selectSysPeopleById(p.getPeopleId());
            if(p.getEquipmentId()==null){
                SysRule rule=sysRuleService.selectSysRuleById(p.getRuleId());
                sdkService.authDeviceNews(rule,people);//规则授权
            }else{
                SysEquipment equipment=equipmentService.selectSysEquipmentById(p.getEquipmentId());
                sdkService.authDevices(people,equipment);//设备人员授权恢复
            }
            p.setSync(1L);
            people.setDown(1L);
            sysPeopleService.updateSysPeople(people);
            sysPeopleRuleService.updateSysPeopleRule(p);
        }
    }

    /**
     * 删除离职人员（测试用得）
     */
    @PostMapping("/getAccount")
    public void getAccount() {
        String body = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getAccount")
                .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                .execute().body();
        JSONObject object = JSONObject.parseObject(body);
        List<JjserInfoVo> data = JSONObject.parseArray(object.get("data").toString(), JjserInfoVo.class);
        List<SysPeople> sysPeople = sysPeopleService.queryPeople(new ArrayList<>());
        List<JjserInfoVo> collect = data.stream().filter(e -> Constants.FIVE.equals(e.getStatus())).collect(Collectors.toList());
        for (JjserInfoVo datum : collect) {
            for (SysPeople sysPerson : sysPeople) {
                if(datum.getWorkcode().equals(sysPerson.getGh())) {
                    System.out.println(datum.getWorkcode());
                    SysPeople people = new SysPeople();
                    people.setGh(datum.getWorkcode());
                    sysPeopleService.updatePeople(people);
                }
            }
        }

    }

    /**
     * 通过手机号查找姓名
     * @param phone
     * @return
     */
    @PostMapping("/queryPeopleName")
    public AjaxResult queryPeopleName(String phone, String deptType) {
        List<SysBranch> branch = visitorService.querySysBranch(deptType);
        List<String> collect = branch.stream().map(SysBranch::getId).collect(Collectors.toList());
        SysPeople people = sysPeopleService.queryPeopleName(phone, collect);
        if(people == null) {
            return success();
        }
        return success(people);
    }

    /**
     * 通过职位标签查询人员信息
     * @param position
     * @return
     */
    @PostMapping("/queryPeopleByPosition")
    public AjaxResult queryPeopleByPosition(String position) {
        List<SysPeople> sysPeople = sysPeopleService.queryPeopleByPosition(position);
        return success(sysPeople);
    }

    /**
     * 小程序通过手机号查找姓名
     *
     * @param js
     * @return
     */
    @PostMapping("/app/queryPeopleName")
    public AjaxResult queryAppPeopleName(@RequestBody JSONObject js) {
        if (null == js) {
            throw new ServiceException("请输入查询参数");
        }
        String phone = js.getString("phone");
        String deptType = js.getString("deptType");
        if (StringUtils.isBlank(phone)) {
            throw new ServiceException("手机号不能为空");
        }
        if (StringUtils.isBlank(deptType)) {
            throw new ServiceException("公司/部门不能为空");
        }

        List<SysBranch> branch = sysBranchService.queryJuniorBranch(deptType);
        List<String> collect = branch.stream().map(SysBranch::getId).collect(Collectors.toList());
        collect.add(deptType);
        SysPeople people = sysPeopleService.queryPeopleName(phone, collect);
        if (people == null) {
            return success();
        }
        return success(people);
    }

}
