package com.dcsoft.system.controller;

import java.beans.Transient;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
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.enums.CompanyType;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.uuid.IdUtils;
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.api.model.LoginUser;
import com.dcsoft.system.consume.domain.ConsumeRechargeRecord;
import com.dcsoft.system.consume.service.IConsumeRechargeRecordService;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.domain.vo.JjserInfoVo;
import com.dcsoft.system.kq.domain.KqAdjust;
import com.dcsoft.system.ladder.domain.EmpowerManageVo;
import com.dcsoft.system.ladder.domain.TLadderRule;
import com.dcsoft.system.ladder.service.ITEmpowerManageService;
import com.dcsoft.system.ladder.service.ITLadderRuleService;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.Person;
import com.dcsoft.system.uniubi.service.ISysApiService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import com.dcsoft.system.utils.FTPUtil;
import com.dcsoft.system.utils.PictureUtils;
import com.dcsoft.system.vehicle.service.ICarInfoService;
import com.dcsoft.system.visitor.service.IVisitorService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.poi.hpsf.GUID;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

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

    @Autowired
    private ISysApiService sysApiService;

    @Autowired
    private ISysConfigService configService;

    @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 ICarInfoService carInfoService;

    @Autowired
    private ITLadderRuleService tLadderRuleService;

    @Resource
    private ITEmpowerManageService empowerManageService;

    @Autowired
    private ISysSyncRuleService sysSyncRuleService;

    @Autowired
    private IVisitorService visitorService;

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

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

    @Autowired
    private IConsumeRechargeRecordService consumeRechargeRecordService;

    @Autowired
    private ISysPostService postService;

    /**
     * 查询人员管理列表
     */
    @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)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("posts", postService.selectPostAll());
        ajax.put("data", sysPeopleService.selectSysPeopleById(id));
        ajax.put("postIds", postService.selectPostListByPeopleId(id));
        return ajax;
    }

    /**
     * 新增人员管理
     */
    @RequiresPermissions("system:sysPeople:add")
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysPeople sysPeople) throws ExecutionException, InterruptedException {
        //判断设备是否上云
        int i=sysPeopleService.insertSysPeople(sysPeople);
        return toAjax(i);
    }


    /**
     * 修改人员管理
     */
    @RequiresPermissions("system:sysPeople:edit")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysPeople sysPeople)
    {
        return toAjax(sysPeopleService.updateSysPeople(sysPeople));
    }



    @Log(title = "手机端人员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult update(@RequestBody SysPeople sysPeople)
    {
        return toAjax(sysPeopleService.updateSysPeople(sysPeople));
    }


    /**
     * 删除人员管理
     */
    @RequiresPermissions("system:sysPeople:remove")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] 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");
        List<SysEquipment> list = equipmentService.selectSysEquipmentList(equipment);
        for(Long id:ids){//下发到设备上
            SysPeople people=sysPeopleService.selectSysPeopleById(id);
            //保存到考勤组人员表中
            sysPeopleService.insetKqGroupUser(people);
        }

        if(list.size()>0){
            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("该规则未绑定设备!");
                        }
                    }
                }

              /*  // 梯控下发
                if(StringUtils.isNotEmpty(people.getBranchId())) {
                    ThreadUtil.execAsync(() -> {
                        empowerManageService.saveLadderDevice(people);
                    });
                }*/
                /*Long down=0L;
                try {
                    if(StringUtils.isNotEmpty(people.getGuid())){//人员
                        Person person=new Person();
                        person.setId(people.getGuid());
                        person.setName(people.getName());
                        person.setiDNumber(people.getIdcard());
                        person.setPhone(people.getPhone());
                        person.setIdcardNum(people.getDoorNo());

                        for(SysEquipment e:list){
                            String ip=e.getIp();
                            String pass=e.getPassword();
                            sdkService.personDelete(people.getGuid(),ip,pass);
                            sdkService.personCreate(person,ip,pass);
                            if(StringUtils.isNotEmpty(people.getFaceGuid())){//人脸
                                sdkService.imageCreateUrl(people.getGuid(),people.getFaceGuid(),people.getAvatar(), e.getIp(), e.getPassword());
                            }
                            down++;
                            //保存下发记录
                            SysPeopleEquipment sysPeopleEquipment=new SysPeopleEquipment();
                            sysPeopleEquipment.setPeopleId(people.getId());
                            sysPeopleEquipment.setEquipmentId(e.getId());
                            sysPeopleEquipment.setGuid(people.getGuid());
                            sysPeopleEquipment.setFaceGuid(people.getFaceGuid());
                            peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                people.setDown(down);*/
                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) {
        SysPeople people = sysPeopleService.queryPeopleName(phone);
        if(people == null) {
            return success();
        }
        // 园区
        if(CompanyType.TD_PARK.getCode().equals(deptType)) {
            List<SysSyncItem> deptIds = sysSyncRuleService.queryParkDept(tdGuid);
            Map<String, String> collect = deptIds.stream().collect(Collectors.toMap(SysSyncItem::getDept, e -> "1"));

            String s = collect.get(people.getBranchId());
            if(StringUtils.isNotEmpty(s)) {
                return success(people);
            }
        }

        // 总部
        if(CompanyType.HEADQUARTERS.getCode().equals(deptType)) {
            List<SysBranch> branch = visitorService.querySysBranch();
            Map<String, String> collect = branch.stream().collect(Collectors.toMap(SysBranch::getId, SysBranch::getName));
            String s = collect.get(people.getBranchId());
            if(StringUtils.isNotEmpty(s)) {
                return success(people);
            }
        }
        return success();
    }

    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping("/subsidy")
    public AjaxResult subsidy(@RequestBody SysPeople sysPeople)
    {
        String[] ids=sysPeople.getIds();
        Double btje=sysPeople.getBtje()==null?0:sysPeople.getBtje();
        Double czje=sysPeople.getCzje()==null?0:sysPeople.getCzje();
        int i=0;
        for(String id:ids){
            SysPeople people=sysPeopleService.selectSysPeopleById(Long.parseLong(id));
            DecimalFormat df = new DecimalFormat("0.00");
            String btjes=df.format(btje+people.getBtje());
            people.setBtje(Double.parseDouble(btjes));
            String czjes=df.format(czje+people.getCzje());
            people.setCzje(Double.parseDouble(czjes));
            sysPeopleService.updateSysPeopleSubsidy(people);
            //保存充值记录
            ConsumeRechargeRecord crr=new ConsumeRechargeRecord();
            crr.setConsumeMoney(df.format(btje+czje));
            crr.setAccountId(people.getId()+"");
            crr.setEmpId(people.getGh());
            crr.setOrderType("1");//充值
            crr.setRechargeWay("0");//平台
            if (btje==0){
                crr.setRechargeType("1");
                crr.setRechargeMode(sysPeople.getRechargeMode());
            }else{
                crr.setRechargeType("0");
            }
            crr.setCreateBy(SecurityUtils.getUsername());
            consumeRechargeRecordService.insertConsumeRechargeRecord(crr);
            i++;
        }
        return toAjax(i);
    }

    @GetMapping(value = "/gh/{gh}")
    public AjaxResult gh(@PathVariable("gh") String gh)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", sysPeopleService.selectSysPeopleByGh(gh));
        return ajax;
    }

    /**
     * @Description: 导入excel和图片zip包
     * @Param:
     * @return:
     * @Author: nichun
     * @Date: 2023-03-31 13:45:02
     **/
    @ApiOperation(value = "导入excel和图片zip包", notes = "导入excel和图片zip包")
    @PostMapping("/importImage")
    public AjaxResult importExcelPic(MultipartFile file, boolean updateSupport) throws Exception {
        StringBuffer sb = sysPeopleService.importPicture(file,updateSupport);
        if (sb!= null&&sb.length()>0) {
            return AjaxResult.error(sb.toString());
        }else{
            return AjaxResult.success();
        }
    }

}
