package com.dcsoft.system.visitor.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.CacheConstants;
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.common.core.utils.SpringUtils;
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.redis.service.RedisService;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.common.sms.config.properties.SmsProperties;
import com.dcsoft.common.sms.entity.SmsResult;
import com.dcsoft.common.sms.service.SmsTemplate;
import com.dcsoft.system.api.model.LoginUser;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.service.*;
import com.dcsoft.system.uniubi.domain.DingtalkMsgVo;
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.FileUtils;
import com.dcsoft.system.visitor.domain.CheckCodeVo;
import com.dcsoft.system.visitor.domain.VisVisitorExamine;
import com.dcsoft.system.visitor.domain.Visitor;
import com.dcsoft.system.visitor.domain.VisitorRecordVo;
import com.dcsoft.system.visitor.service.IVisVisitorExamineService;
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 javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 访客信息Controller
 *
 * @author 倪春
 * @date 2023-03-09
 */
@Slf4j
@RestController
@RequestMapping("/visitor")
public class VisitorController extends BaseController {
    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private ISysApiService sysApiService;

    @Autowired
    private IVisVisitorExamineService visVisitorExamineService;

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private ISysBlackListService sysBlackListService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected ISysSdkService sdkService;

    @Autowired
    private ISysEquipmentService equipmentService;

    @Autowired
    private ISysPeopleService sysPeopleService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ISysRuleService sysRuleService;

    @Autowired
    private ISysPeopleEquipmentService peopleEquipmentService;


    @Value("${qd.url}")
    public String qdUrl;

    @Value("${dingTalk.getToken}")
    public String getToken;

    @Value("${dingTalk.asyncsendV2}")
    public String asyncsendV2;

    @Value("${dingTalk.agentId}")
    public String agentId;

    @Value("${weixin.token}")
    public String weixinToken;

    @Value("${weixin.send}")
    public String weixinSend;

    @Value("${system.type}")
    public String systemType;

    @Value("${sdk.saveVisitor}")
    public String saveVisitor;

    @Value("${sdk.updateVisitorExamine}")
    public String updateVisitorExamine;

    @Value("${sdk.saveVisitorAuditing}")
    public String saveVisitorAuditing;

    @Value("${sdk.upload}")
    public String upload;

    @Value("${photo.url}")
    public String url;

    @Value("${property_dep_id}")
    public String propertyDepId;

    @Value("${minio.url}")
    public String minioUrl;

    @Value("${minio.gwurl}")
    public String minioGwurl;

    @Value("${weCom.token}")
    public String qywxToken;

    @Value("${weCom.send}")
    public String qywxSend;

    @Value("${weCom.agentid}")
    public String agentid;


    // 正则表达式匹配大部分国家的手机号码格式
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    /**
     * 查询访客信息列表
     */
//    @RequiresPermissions("visitor:visitor:list")
    @GetMapping("/list")
    public TableDataInfo list(Visitor visitor) {
        startPage();
        List<Visitor> list = visitorService.selectVisitorList(visitor);
        return getDataTable(list);
    }

    /**
     * 导出访客信息列表
     */
    @RequiresPermissions("visitor:visitor:export")
    @Log(title = "访客信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Visitor visitor) {
        List<Visitor> list = visitorService.selectVisitorList(visitor);
        ExcelUtil<Visitor> util = new ExcelUtil<Visitor>(Visitor.class);
        util.exportExcel(response, list, "访客信息数据");
    }

    /**
     * 获取访客信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Visitor visitor = visitorService.selectVisitorById(id);
        if (visitor == null) {
            return success();
        }
        Visitor item = new Visitor();
        item.setParentId(id);
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        visitor.setItemList(itemList);
        return success(visitor);
    }

    @GetMapping(value = "/queryVisitorById")
    public AjaxResult queryVisitorById(Long id) {
        Visitor visitor = visitorService.selectVisitorById(id);
        if (visitor == null) {
            return success();
        }
        Visitor item = new Visitor();
        item.setParentId(id);
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        visitor.setItemList(itemList);
        return success(visitor);
    }

    /**
     * 新增访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Visitor visitor) throws Exception {
        if (visitor.getStartTime().getTime() > visitor.getEndTime().getTime()) {
            throw new ServiceException("您输入的开始时间不能大于结束时间");
        }

        if (visitorService.queryVisitor(visitor) > 0) {
            throw new ServiceException("您已预约");
        }

        // 校验图片
        checkPhoto(visitor.getAvatar());

        visitor.setSource(Constants.ONE);
        log.info("新增访客信息：{}", visitor);
        int i = visitorService.insertVisitor(visitor);
        List<Visitor> itemList = visitor.getItemList();
        // 随访人员
        if (!CollectionUtils.isEmpty(itemList)) {
            for (Visitor item : itemList) {
                if (!validatePhoneNumber(item.getPhone())) {
                    throw new ServiceException("您输入的随访人员手机号格式不正确");
                }
                item.setParentId(visitor.getId());
                item.setSource(Constants.ONE);
                item.setUserId(visitor.getUserId());
                item.setDeptId(visitor.getDeptId());
                item.setCreateTime(visitor.getCreateTime());
                item.setStartTime(visitor.getStartTime());
                item.setEndTime(visitor.getEndTime());
                visitorService.insertVisitor(item);
            }
        }


        /*if ("1".equals(systemType)) {
            if (2L == visitor.getDeptId()) {
                // 数据同步到子园区
                ThreadUtil.execAsync(() -> {
                    try {
                        String body = HttpUtil.createPost(saveVisitor).body(JSON.toJSONString(visitor)).execute().body();
                        log.info("数据同步到子园区结果：{}", body);
                    } catch (HttpException e) {
                        log.error("数据同步到子园区失败", e);
                        throw new RuntimeException(e);
                    }
                });
            }
        }*/

        if ("1".equals(systemType)) {
            SysPeople sysPeople = sysPeopleService.selectSysPeopleByUserId(visitor.getUserId());
            String url = "您有新的访客申请，请查看: https://thzn.chinataiho.com/h5/#/pages/visitor/visitor/examineDetal?id=" + visitor.getId();
            // 工作号消息通知(获取openId然后更具消息发送)
            if (StringUtils.isNotEmpty(sysPeople.getQwid())) {
                String wxToken = getQyWxToken();
                qywxSend(sysPeople.getQwid(), wxToken, url);
            }

        }
        return toAjax(i);
    }

    /**
     * 验证手机号码是否有效
     *
     * @param number 要验证的手机号码
     * @return 如果手机号码有效返回true，否则返回false
     */
    public static boolean validatePhoneNumber(String number) {
        return PHONE_NUMBER_PATTERN.matcher(number).matches();
    }

    /**
     * 钉工牌消息通知
     */
    private void asyncsendV2(String userId, String msgType, String content) {
        DingtalkMsgVo msgVo = new DingtalkMsgVo();
        DingtalkMsgVo.Text text = new DingtalkMsgVo.Text();
        text.setContent(content);
        msgVo.setMsgtype(msgType);
        msgVo.setText(text);
        Map<String, Object> map = new HashMap<>();
        map.put("agent_id", agentId);
        map.put("msg", msgVo);
        map.put("userid_list", userId);
        String body = HttpUtil.createPost(asyncsendV2 + "?access_token=" + getToken())
                .body(JSON.toJSONString(map))
                .execute()
                .body();
        JSONObject object = JSONObject.parseObject(body);
        if (!Constants.ZERO.equals(object.get("errcode").toString())) {
            log.error("钉工牌消息通知接口异常码:" + object.get("errcode").toString());
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "钉工牌消息通知接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }

    }

    /**
     * 获取钉工牌token
     */
    private String getToken() {
        String body = HttpUtil.createGet(getToken).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        return object.get("access_token").toString();

    }

    /**
     * 获取微信公众号token
     *
     * @return
     */
    private String getWxToken() {
        String cacheObject = redisService.getCacheObject(CacheConstants.WEIXIN_TOKEN);
        if (StringUtils.isNotEmpty(cacheObject)) {
            return cacheObject;
        }
        String body = HttpUtil.createGet(weixinToken).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        String string = object.get("access_token").toString();
        redisService.setCacheObject(CacheConstants.LOGIN_TOKEN, string, Long.valueOf(object.get("expires_in").toString()), TimeUnit.SECONDS);
        return string;
    }

    private void weixinSend(String openId, String wxToken, String url) {
        String s = Constants.CONTENT.replaceAll("%", openId);
        String s1 = s.replaceAll("#", url);
        String body = HttpUtil.createPost(weixinSend + wxToken)
                .body(s1)
                .execute()
                .body();
        JSONObject object = JSONObject.parseObject(body);
        if (!"0".equals(object.get("errcode").toString())) {
            log.error("微信公众号消息通知接口异常");
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "微信公众号消息通知接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }

    }


    /**
     * 获取微信公众号token
     *
     * @return
     */
    private String getQyWxToken() {
        String cacheObject = redisService.getCacheObject(CacheConstants.QYWEIXIN_TOKEN);
        if (StringUtils.isNotEmpty(cacheObject)) {
            return cacheObject;
        }
        String body = HttpUtil.createGet(qywxToken).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        String string = object.get("access_token").toString();
        redisService.setCacheObject(CacheConstants.QY_LOGIN_TOKEN, string, Long.valueOf(object.get("expires_in").toString()), TimeUnit.SECONDS);
        return string;
    }

    private void qywxSend(String gh, String wxToken, String content) {

        Map<String, Object> paramMap=new HashMap<>();
        Map<String, Object> paramMap1=new HashMap<>();
        paramMap.put("touser",gh);
        paramMap.put("msgtype","text");
        paramMap.put("agentid",agentid);
        paramMap1.put("content",content);
        paramMap.put("text",paramMap1);
        log.error("企业微信消息请求方法==="+qywxSend+wxToken);
        String body1=JSON.toJSONString(paramMap);
        log.error("企业微信消息请求体==="+body1);
        String body=HttpUtil.post(qywxSend+wxToken,body1);
        JSONObject object = JSONObject.parseObject(body);
        if (!"0".equals(object.get("errcode").toString())) {
            log.error("企业微信消息通知接口异常");
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "企业微信消息通知接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage() + object.get("errcode").toString());
        }

    }


    /**
     * 获取时间
     *
     * @param startDate
     * @param endDate
     */
    private List<Visitor> getTime(String startDate, String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        List<Visitor> list = new ArrayList<>();
        while (!start.isAfter(end)) {
            Visitor gather = new Visitor();
            gather.setCreateTime(sdf.parse(start.toString()));
            list.add(gather);
            start = start.plusDays(1);
        }
        return list;
    }

    /**
     * 新增访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addVis(@RequestBody Visitor visitor) {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
//        if("true".equals(cloud)) {
//            String data = sysApiService.admitCreate(visitor);
//            JSONObject json = JSONObject.parseObject(data);
//            if ("1".equals(json.get("result") + "")) {
//                JSONObject obj = (JSONObject) json.get("data");
//                String admitGuid = obj.get("admitGuid") + "";
//                visitor.setGuid(admitGuid);
//                if (StringUtils.isNotEmpty(visitor.getAvatar())) {
//                    //人像注册，如果注册失败将人像置空
//                    String datas = sysApiService.faceRegister(visitor);
//                    JSONObject jsons = JSONObject.parseObject(datas);
//                    if ("1".equals(jsons.get("result") + "")) {
//                        JSONObject objs = (JSONObject) jsons.get("data");
//                        String faceGuid = objs.get("faceGuid") + "";
//                        visitor.setFaceGuid(faceGuid);
//                    }
//                }
//            } else {
//                return error(json.get("msg") + "");
//            }
//        }else{
//            //判断设备人员是否能注册上设备后再删除掉
//            List<SysEquipment> list=equipmentService.selectSysEquipmentList(new SysEquipment());
//            if(list.size()>0){
//                Person person=new Person();
//                person.setName(visitor.getName());
//                person.setiDNumber(visitor.getIdcard());
//                person.setPhone(visitor.getPhone());
//                String ip=list.get(0).getIp();
//                String pass=list.get(0).getPassword();
//                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")+"";
//                    visitor.setGuid(admitGuid);
//                    if(StringUtils.isNotEmpty(visitor.getAvatar())) {
//                        String datas=sdkService.imageCreateUrl(admitGuid,visitor.getAvatar(),ip,pass);
//                        JSONObject jsons= JSONObject.parseObject(datas);
//                        if("1".equals(jsons.get("result")+"")){
//                            String faceGuid=jsons.get("data")+"";
//                            visitor.setFaceGuid(faceGuid);
//                            sdkService.imageDeletel(faceGuid,ip,pass);
//                        }
//                    }
//
//                    //再删除以上的注册信息
//                    sdkService.personDelete(admitGuid,ip,pass);
//                }else{
//                    return error(json.get("msg")+"");
//                }
//            }
//        }
        int i = visitorService.insertVisitor(visitor);
        List<Visitor> itemList = visitor.getItemList();
        for (Visitor item : itemList) {
            item.setParentId(visitor.getId());
            //随访人员增加人员注册
//            item=admitCreate(item);
            visitorService.insertVisitor(item);
        }
        if ("1".equals(systemType)) {
            SysPeople sysPeople = sysPeopleService.selectSysPeopleByUserId(visitor.getUserId());
            String url = "您有新的访客申请，请查看: https://thzn.chinataiho.com/h5/#/pages/visitor/visitor/examineDetal?id=" + visitor.getId();
            // 工作号消息通知(获取openId然后更具消息发送)
            if (StringUtils.isNotEmpty(sysPeople.getQwid())) {
                String wxToken = getQyWxToken();
                qywxSend(sysPeople.getQwid(), wxToken, url);
            }

        }
        return toAjax(i);
    }

    /*private Visitor admitCreate(Visitor item) {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if ("true".equals(cloud)) {
            String data = sysApiService.admitCreate(item);
            JSONObject json = JSONObject.parseObject(data);
            if ("1".equals(json.get("result") + "")) {
                JSONObject obj = (JSONObject) json.get("data");
                String admitGuid = obj.get("admitGuid") + "";
                item.setGuid(admitGuid);
                //人像注册，如果注册失败将人像置空
                if (StringUtils.isNotEmpty(item.getAvatar())) {
                    String datas = sysApiService.faceRegister(item);
                    JSONObject jsons = JSONObject.parseObject(datas);
                    if ("1".equals(jsons.get("result") + "")) {
                        JSONObject objs = (JSONObject) jsons.get("data");
                        String faceGuid = objs.get("faceGuid") + "";
                        item.setFaceGuid(faceGuid);
                    }
                }
            }
        } else {
            //判断设备人员是否能注册上设备后再删除掉
            List<SysEquipment> list = equipmentService.selectSysEquipmentList(new SysEquipment());
            if (list.size() > 0) {
                Person person = new Person();
                person.setName(item.getName());
                person.setiDNumber(item.getIdcard());
                person.setPhone(item.getPhone());
                String ip = list.get(0).getIp();
                String pass = list.get(0).getPassword();
                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") + "";
                    item.setGuid(admitGuid);
                    String datas = sdkService.imageCreateUrl(admitGuid, item.getAvatar(), ip, pass);
                    JSONObject jsons = JSONObject.parseObject(datas);
                    if ("1".equals(jsons.get("result") + "")) {
                        String faceGuid = jsons.get("data") + "";
                        item.setFaceGuid(faceGuid);
                        sdkService.imageDeletel(faceGuid, ip, pass);
                    }
                    //再删除以上的注册信息
                    sdkService.personDelete(admitGuid, ip, pass);
                }
            }
        }
        return item;
    }
*/
    /**
     * 修改访客信息
     */
    @Log(title = "访客信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Visitor visitor) throws Exception {
//        if(StringUtils.isEmpty(visitor.getGuid())){
//            String cloud = configService.selectConfigByKey("sys.equipment.cloud");
//            if("true".equals(cloud)) {
//                String data = sysApiService.admitUpdate(visitor);
//                JSONObject json = JSONObject.parseObject(data);
//                if ("1".equals(json.get("result") + "")) {
//                    //人像注册，如果注册失败将人像置空
//                    if (StringUtils.isEmpty(visitor.getFaceGuid())) {
//                        if (StringUtils.isNotEmpty(visitor.getAvatar())) {
//                            String datas = sysApiService.faceRegister(visitor);
//                            JSONObject jsons = JSONObject.parseObject(datas);
//                            if ("1".equals(jsons.get("result") + "")) {
//                                JSONObject objs = (JSONObject) jsons.get("data");
//                                String faceGuid = objs.get("faceGuid") + "";
//                                visitor.setFaceGuid(faceGuid);
//                            }
//                        }
//                    }
//                } else {
//                    return error(json.get("msg") + "");
//                }
//            }else{
//                //判断设备人员是否能注册上设备后再删除掉
//                List<SysEquipment> list=equipmentService.selectSysEquipmentList(new SysEquipment());
//                if(list.size()>0){
//                    Person person=new Person();
//                    person.setName(visitor.getName());
//                    person.setiDNumber(visitor.getIdcard());
//                    person.setPhone(visitor.getPhone());
//                    String ip=list.get(0).getIp();
//                    String pass=list.get(0).getPassword();
//                    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")+"";
//                        visitor.setGuid(admitGuid);
//                        String datas=sdkService.imageCreateUrl(admitGuid,visitor.getAvatar(),ip,pass);
//                        JSONObject jsons= JSONObject.parseObject(datas);
//                        if("1".equals(jsons.get("result")+"")){
//                            String faceGuid=jsons.get("data")+"";
//                            visitor.setFaceGuid(faceGuid);
//                            sdkService.imageDeletel(faceGuid,ip,pass);
//                        }
//                        //再删除以上的注册信息
//                        sdkService.personDelete(admitGuid,ip,pass);
//                    }
//                }
//            }
//        }
        //先删除关联子项再进行增加
        //删除子项存在的注册人员信息
//        delVisVisitorItemList(visitor.getId());
        checkPhoto(visitor.getAvatar());
        visitorService.deleteVisitorItemByParentId(visitor.getId());
        List<Visitor> itemList = visitor.getItemList();
        for (Visitor item : itemList) {
            if (!validatePhoneNumber(item.getPhone())) {
                throw new ServiceException("您输入的随访人员手机号格式不正确");
            }
            item.setParentId(visitor.getId());
            item.setSource(Constants.ONE);
            item.setUserId(visitor.getUserId());
            item.setDeptId(visitor.getDeptId());
            item.setCreateTime(visitor.getCreateTime());
            item.setStartTime(visitor.getStartTime());
            item.setEndTime(visitor.getEndTime());
            visitorService.insertVisitor(item);
        }
        if ("1".equals(systemType)) {
            SysPeople sysPeople = sysPeopleService.selectSysPeopleByUserId(visitor.getUserId());
            String url = "您有新的访客申请，请查看: https://thzn.chinataiho.com/h5/#/pages/visitor/visitor/examineDetal?id=" + visitor.getId();
            // 工作号消息通知(获取openId然后更具消息发送)
            if (StringUtils.isNotEmpty(sysPeople.getQwid())) {
                String wxToken = getQyWxToken();
                qywxSend(sysPeople.getQwid(), wxToken, url);
            }

        }
        return toAjax(visitorService.updateVisitor(visitor));
    }

    /**
     * 修改访客信息
     */
    @Log(title = "访客审核", businessType = BusinessType.UPDATE)
    @PostMapping("/updateVisitorExamine")
    public AjaxResult updateVisitorExamine(@RequestBody Visitor visitor) {
        log.info("修改访客信息：{}", visitor);
        VisVisitorExamine examine = visitor.getExamine();
        Visitor item = new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        visitor.setItemList(itemList);
        CheckCodeVo codeVo = new CheckCodeVo();
        Visitor visitor1 = visitorService.selectVisitorById(visitor.getId());
        if ("0".equals(examine.getExamine())) {//审核通过
            //人员存入海康
            addHkVis(visitor);
            if(StringUtils.isNotEmpty(visitor.getCarNo())){ //车辆存入海康
                addHkCar(visitor);
            }




            //判断是否存在黑名单，存在即审核失败
          /*  SysBlackList sysBlackList = new SysBlackList();
            sysBlackList.setPhone(visitor.getPhone());
            List<SysBlackList> list = sysBlackListService.selectSysBlackListList(sysBlackList);
            if (list.size() > 0) {
                return AjaxResult.error("存在黑名单无法审核通过");
            }
            for (Visitor items : itemList) {
                SysBlackList sysBlackLists = new SysBlackList();
                sysBlackLists.setPhone(items.getPhone());
                List<SysBlackList> lists = sysBlackListService.selectSysBlackListList(sysBlackLists);
                if (lists.size() > 0) {
                    return AjaxResult.error("存在黑名单无法审核通过");
                }
            }
*/
            /*//发送到访客人员告知已经经过审核
            if ("1".equals(systemType)) {
                logger.info("发送到访客人员告知已经经过审核" + visitor.getPhone() + qdUrl + visitor.getId());
                AjaxResult msg = sendMessage(visitor.getPhone(), String.valueOf(visitor.getId()), smsProperties.getTemplate5());
                logger.info("发送到短信回调信息" + msg);
                if (!CollectionUtils.isEmpty(itemList)) {
                    for (Visitor visitor2 : itemList) {
                        logger.info("发送到随访人员告知已经经过审核" + visitor.getPhone() + qdUrl + visitor2.getId());
                        AjaxResult message = sendMessage(visitor.getPhone(), String.valueOf(visitor2.getId()), smsProperties.getTemplate5());
                        logger.info("发送到随访人短信回调信息" + message);
                    }
                }
            }
*/
            codeVo.setCode(qdUrl + visitor.getId() + "&time=" + new Date().getTime());
            codeVo.setVisitorId(String.valueOf(visitor.getId()));
            String replace = UUID.randomUUID().toString().replace("-", "");
            codeVo.setId(replace);
            if (StringUtils.isNotEmpty(visitor.getCheckCodeId())) {
                codeVo.setId(visitor.getCheckCodeId());
            }

            if (visitor1 != null) {
                codeVo.setStartTime(visitor1.getStartTime());
                codeVo.setEndTime(visitor1.getEndTime());
            }
            visitorService.saveVisCheckCode(codeVo);

            /*// 园区人脸下发到设备
            if ("2".equals(systemType)) {
                if (2L == visitor.getDeptId() || "0".equals(Objects.requireNonNull(visitor1).getSource())) {
                    List<Visitor> listVisitorId = new ArrayList<>();
                    Visitor s = parkDeviceDistribute(visitor);
                    Visitor visitor3 = new Visitor();
                    visitor3.setGuid(s.getGuid());
                    visitor3.setFaceGuid(s.getFaceGuid());
                    visitor3.setId(visitor.getId());
                    if (!CollectionUtils.isEmpty(visitor.getItemList())) {
                        for (Visitor visitor2 : visitor.getItemList()) {
                            Visitor visitorInfo = new Visitor();
                            visitor2.setUserId(visitor.getUserId());
                            Visitor visitorId = parkDeviceDistribute(visitor2);
                            visitorInfo.setId(visitor2.getId());
                            visitorInfo.setGuid(visitorId.getGuid());
                            visitorInfo.setFaceGuid(visitorId.getFaceGuid());
                            listVisitorId.add(visitorInfo);
                        }
                    }
                    listVisitorId.add(visitor3);
                    log.info("更新访客人员信息到设备：" + listVisitorId);
                    visitorService.updateVisitorInfoGuid(listVisitorId);

                }
            }*/
        }

        /*// 数据同步到子园区
        if ("1".equals(systemType)) {
            if (2L == visitor.getDeptId() || "0".equals(Objects.requireNonNull(visitor1).getSource())) {
                visitor.setCheckCodeId(codeVo.getId());
                ThreadUtil.execAsync(() -> {
                    try {
                        String body = HttpUtil.createPost(updateVisitorExamine).body(JSON.toJSONString(visitor)).execute().body();
                        log.info("数据同步到子园区返回结果：" + body);
                    } catch (HttpException e) {
                        log.error("数据同步到子园区失败", e);
                        throw new RuntimeException(e);
                    }
                });
            }
        }*/

        // 园区审核
        /*if ("2".equals(visitor.getType())) {
            logger.info("发送到访客人员告知已经经过审核" + visitor.getPhone() + qdUrl + visitor.getId());
            AjaxResult msg = sendMessage(visitor.getPhone(), String.valueOf(visitor.getId()), smsProperties.getTemplate5());
            logger.info("发送到短信回调信息" + msg);
            if (!CollectionUtils.isEmpty(itemList)) {
                for (Visitor visitor2 : itemList) {
                    logger.info("发送到随访人员告知已经经过审核" + visitor.getPhone() + qdUrl + visitor2.getId());
                    AjaxResult message = sendMessage(visitor.getPhone(), String.valueOf(visitor2.getId()), smsProperties.getTemplate5());
                    logger.info("发送到随访人短信回调信息" + message);
                }
            }
            visitor.setCheckCodeId(codeVo.getId());
            // 同步给总部
            ThreadUtil.execAsync(() -> {
                try {
                    String body = HttpUtil.createPost(saveVisitorAuditing).body(JSON.toJSONString(visitor)).execute().body();
                    log.info("数据同步给总部返回结果：" + body);
                } catch (HttpException e) {
                    log.error("数据同步给总部失败", e);
                    throw new RuntimeException(e);
                }
            });
        }*/

      /*  Visitor visitor2 = new Visitor();
        visitor2.setId(visitor.getId());
        visitor2.setType("1");
        visitorService.updateVisitor(visitor2);*/
        examine.setVisitorId(visitor.getId());
        LoginUser user = SecurityUtils.getLoginUser();
        visitor.setUserName(user == null ? visitor.getPeopleName() : user.getUsername());
        examine.setCreateBy(visitor.getUserName());
        return toAjax(visVisitorExamineService.insertVisVisitorExamine(examine));
    }

    private void addHkCar(Visitor visitor) {
        visitorService.addHkCar(visitor);
    }

    private void addHkVis(Visitor visitor) {
        visitorService.addHkVis(visitor);
        List<Visitor> itemList=visitor.getItemList();
        if(itemList.size()>0){
            for(Visitor v:itemList){
                visitorService.addHkVis(v);
            }
        }
    }

    /**
     * 园区人脸设备下发
     */
    private Visitor parkDeviceDistribute(Visitor visitor) {
        // 查询被访人授权记录
        List<SysManageRecord> record = visitorService.querySysManageRecord(visitor.getUserId());
        Visitor s = new Visitor();
        if (CollectionUtils.isEmpty(record)) {
            throw new RuntimeException("未查询到被访人授权记录");
        }
        for (SysManageRecord sysManageRecord : record) {
            SysRule rule = sysRuleService.selectSysRuleById(sysManageRecord.getRuleId());
            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);
                }
            }
            String guid = IdUtils.simpleUUID();
            String faceId = IdUtils.simpleUUID();
            s.setGuid(guid);
            s.setFaceGuid(faceId);
            //通过规则获取绑定设备信息
            if (equipList != null) {
                for (SysEquipment e : equipList) {
                    //将人员信息下发到设备
                    Person person = new Person();
                    person.setName(visitor.getName());
                    person.setPhone(visitor.getPhone());
                    person.setId(guid);
                    String ip = e.getIp();
                    String pass = e.getPassword();
                    sdkService.personCreate(person, ip, pass);
                    if (StringUtils.isNotEmpty(visitor.getAvatar())) {
                        sdkService.imageCreateUrl(guid, faceId, visitor.getAvatar(), ip, pass);
                    }
                    //保存下发记录
                    SysPeopleEquipment sysPeopleEquipment = new SysPeopleEquipment();
                    sysPeopleEquipment.setVisitorId(visitor.getId());
                    sysPeopleEquipment.setEquipmentId(e.getId());
                    sysPeopleEquipment.setGuid(guid);
                    sysPeopleEquipment.setFaceGuid(faceId);
                    peopleEquipmentService.insertSysPeopleEquipment(sysPeopleEquipment);
                }
            }
        }

        return s;
    }

    /**
     * 访客签到签退
     */
    @Log(title = "访客签到签退", businessType = BusinessType.UPDATE)
    @PostMapping("/updateVisitorInOut")
    public AjaxResult updateVisitorInOut(@RequestBody Visitor visitor) {
        Visitor item = new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        for (Visitor items : itemList) {
            if ("in".equals(visitor.getTabFlag())) {
                items.setInTime(new Date());
            } else {
                items.setOutTime(new Date());
            }
            visitorService.updateVisitor(items);
        }
        if ("in".equals(visitor.getTabFlag())) {
            visitor.setInTime(new Date());
        } else {
            visitor.setOutTime(new Date());
        }
        return toAjax(visitorService.updateVisitor(visitor));
    }


    private void delVisVisitorItemList(Long id) {
        Visitor item = new Visitor();
        item.setParentId(id);
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        String admitGuids = "";
        for (Visitor items : itemList) {
            admitGuids += items.getGuid() + ",";
            visitorService.delHkvisitor(admitGuids);
        }
        /*if (!"".equals(admitGuids)) {
            String cloud = configService.selectConfigByKey("sys.equipment.cloud");
            if ("true".equals(cloud)) {
                *//*admitGuids = admitGuids.substring(0, admitGuids.length() - 1);
                if (!"null".equals(admitGuids)) {
                    String data = sysApiService.admitDelete(admitGuids);
                }*//*
            } else {
                List<SysEquipment> equipmentDtoList = equipmentService.selectSysEquipmentList(new SysEquipment());
                for (SysEquipment eq : equipmentDtoList) {
                    sdkService.personDelete(admitGuids, eq.getIp(), eq.getPassword());
                }
            }
        }*/
    }




    /**
     * 删除访客信息
     */
    @RequiresPermissions("visitor:visitor:remove")
    @Log(title = "访客信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        String admitGuids = "";
//        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
//        if("true".equals(cloud)) {
//            for(Long visitorId:ids){
//                Visitor Visitor=visitorService.selectVisitorById(visitorId);
//                admitGuids+=Visitor.getGuid()+",";
//                if(StringUtils.isNotEmpty(Visitor.getFaceGuid())){
//                    sysApiService.faceDelete(Visitor);
//                }
//                visitorService.deleteVisitorItemByParentId(visitorId);
//                //删除子项存在的注册人员信息
//                delVisVisitorItemList(visitorId);
//            }
//            if(!"".equals(admitGuids)){
//                admitGuids=admitGuids.substring(0,admitGuids.length()-1);
//                if(!"null".equals(admitGuids)){
//                    String data=sysApiService.admitDelete(admitGuids);
//                }
//            }
//        }else{
//            for(Long visitorId:ids){
//                Visitor Visitor=visitorService.selectVisitorById(visitorId);
//                admitGuids+=Visitor.getGuid()+",";
//                visitorService.deleteVisitorItemByParentId(visitorId);
//                //删除子项存在的注册人员信息
//                delVisVisitorItemList(visitorId);
//                if(!"".equals(admitGuids)){
//                    if(!"null".equals(admitGuids)){
//                        List<SysEquipment> equipmentDtoList=equipmentService.selectSysEquipmentList(new SysEquipment());
//                        for(SysEquipment eq:equipmentDtoList){
//                            sdkService.personDelete(admitGuids,eq.getIp(), eq.getPassword());
//                        }
//                    }
//                }
//            }
//        }

        for (Long visitorId : ids) {
            Visitor visitor = visitorService.selectVisitorById(visitorId);
            admitGuids += visitor.getGuid() + ",";
            visitorService.deleteVisitorItemByParentId(visitorId);
            //删除主项人员信息
            visitorService.delHkvisitor(admitGuids);
            if(StringUtils.isNotEmpty(visitor.getCarNo())){
                visitorService.delHkCarVisitor(visitor.getCarNo());
            }
            //删除子项存在的注册人员信息
            delVisVisitorItemList(visitorId);

        }
        return toAjax(visitorService.deleteVisitorByIds(ids));
    }

    @Log(title = "访客信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/canceVisitor/{id}")
    public AjaxResult canceVisitor(@PathVariable Long id) {
        Visitor visitor = visitorService.selectVisitorById(id);
        Visitor item = new Visitor();
        item.setParentId(visitor.getId());
        List<Visitor> itemList = visitorService.selectVisitorItemList(item);
        visitor.setItemList(itemList);
        /*//保存访客通行规则
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        try {
            if ("true".equals(cloud)) {
                //sysApiService.authDeviceRevoke(visitor);
            } else {
                sdkService.authDeviceRevoke(visitor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        return toAjax(visVisitorExamineService.deleteVisVisitorExamineByVisitorId(id));
    }

    public AjaxResult sendMessage(String phone, String code, String templateId) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(phone)) {
            return error("手机号不能为空!");
        }
        if (!smsProperties.getEnabled()) {
            error("当前系统没有开启短信功能！");
        }
        Map<String, String> map = new HashMap<>(1);
        map.put("code", code);
        SmsTemplate smsTemplate = SpringUtils.getBean(SmsTemplate.class);
        SmsResult result = smsTemplate.send(phone, templateId, map);
        if (!result.getIsSuccess()) {
            return error(result.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 查询访客记录列表
     *
     * @param visitor
     * @return
     */
    @GetMapping("/queryVisitorRecordList")
    public TableDataInfo queryVisitorRecordList(VisitorRecordVo visitor) {
        startPage();
        List<VisitorRecordVo> list = visitorService.queryVisitorRecordList(visitor);
        return getDataTable(list);
    }

    /**
     * 删除访客记录
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteVisitorRecordList")
    public AjaxResult deleteVisitorRecordList(@PathVariable Long[] id) {
        visitorService.deleteVisitorRecordList(id);
        return AjaxResult.success();
    }

    /**
     * 新增访客记录
     *
     * @return
     */
    @PostMapping("/saveVisitorRecord")
    public AjaxResult saveVisitorRecord(VisitorRecordVo recordVo) {
        Visitor visitor = new Visitor();
        if ("2".equals(recordVo.getType())) {
            visitorService.updateVisitorRecord(recordVo);
            visitor.setEndTime(recordVo.getEndTime());
            visitorService.updateVisitor(visitor);
            return AjaxResult.success();
        }
        visitor.setStartTime(recordVo.getStartTime());
        visitorService.saveVisitorRecord(recordVo);
        return AjaxResult.success();
    }

    /**
     * 校验头像上传宇泛人脸机是否通过
     *
     * @param avatar
     */
    private void checkPhoto(String avatar) throws Exception {
        if (StringUtils.isNotEmpty(avatar)) {
            String[] split = avatar.split(minioGwurl);
            String s = minioUrl + split[1];
            try {
                File file = FileUtils.urlToFile("111", s);
                String body = HttpUtil.createPost(upload).form("file", file).execute().body();
                if (!file.delete()) {
                    log.info("删除临时文件失败成功");
                }
                JSONObject object = JSONObject.parseObject(body);
                String string = object.get("code").toString();
                if (!"0".equals(string)) {
                    log.info("来访人头像校验失败：{}", avatar);
                    throw new ServiceException("来访人头像校验失败,请重新上传");
                }
            } catch (HttpException e) {
                log.error("来访人头像校验失败", e);
            }
        }
    }

    /**
     * 查询访客数量（今日，本周，本月）
     *
     * @param recordVo
     * @return
     */
    @PostMapping("/queryVisitorCount")
    public AjaxResult queryVisitorCount(VisitorRecordVo recordVo) {
        return success(visitorService.queryVisitorCount(recordVo));
    }

    /**
     * 首页头像展示
     * @param recordVo
     * @return
     */
    @PostMapping("/queryVisitorAvatar")
    public AjaxResult queryVisitorAvatar(VisitorRecordVo recordVo) {
        return success(visitorService.queryVisitorAvatar(recordVo));
    }


    @PostMapping("/personHkDelete")
    public AjaxResult personHkDelete(@PathVariable String guid) {

        return toAjax(visitorService.personHkDelete(guid));
    }

    @PostMapping("/carHkDelete")
    public AjaxResult carHkDelete(@PathVariable String carNo) {
        return toAjax(visitorService.delHkCarVisitor(carNo));
    }


}
