package com.bonus.tcp.smartIdentify.service.impl;

import cn.afterturn.easypoi.cache.manager.IFileLoader;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.bonus.app.entity.DevDetailEntity;
import com.bonus.common.core.utils.DateTimeHelper;
import com.bonus.common.core.utils.FaceCodeUtil;
import com.bonus.common.core.utils.StringHelper;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.bracelet.vo.BraceletVo;
import com.bonus.common.entity.tcp.BraceletImageVo;
import com.bonus.common.entity.tcp.DeviceUseVo;
import com.bonus.common.entity.tcp.HisDataVo;
import com.bonus.tcp.smartIdentify.mapper.BraceletImageMapper;
import com.bonus.tcp.smartIdentify.service.BraceletImageService;
import com.bonus.tcp.smartIdentify.service.FaceInterUtilService2;
import com.bonus.tcp.util.SystemConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class BraceletImageServiceImpl implements BraceletImageService {


    @Autowired
    private BraceletImageMapper mapper;
    @Autowired
    private FaceInterUtilService2 faceInterUtilService2;



    @Override
    public AjaxResult uploadImage(BraceletImageVo vo) {
       try{
           if(StringHelper.isEmpty(vo.getImage())){
               return   AjaxResult.error("请先上传照片");
           }

           BraceletVo dev=mapper.getBraceletVo(vo.getDevCode());
           DeviceUseVo  devUseVo=mapper.getDevLyInfo(dev);

           if(ObjectUtils.isEmpty(dev)){
               log.info("设备编号--->{}",vo.getDevCode());
               return   AjaxResult.error("设备未入库");
           }
           if(ObjectUtils.isEmpty(dev.getShboxId())){
               return   AjaxResult.error("手环箱未领用");
           }
           if(ObjectUtils.isEmpty(devUseVo)){
               return   AjaxResult.error("手环箱未领用");
           }
           if(ObjectUtils.isNotEmpty(dev.getBidId())){
               return   AjaxResult.error("该手环已绑定,请先归还解绑");
           }


//           AjaxResult ajax2=faceInterUtilService2.addFace(vo.getImage(), FaceCodeUtil.ADD,"ls-123456789000");
           //验证人脸
           Map<String,Object> ajaxResult=faceInterUtilService2.verifyFace(vo.getImage());
           Integer code= (Integer) ajaxResult.get("code");
           if(code==200){
              String userId= (String) ajaxResult.get("userId");
              if (userId.contains("bz-")){//正式员工
                  dev.setShPersonType(0);
                  devUseVo.setPeopleType(0);
              }else  if (userId.contains("ls-")){
                  dev.setShPersonType(1);
                  devUseVo.setPeopleType(1);
                  //获取人员id
              }else {
                  return   AjaxResult.error(ajaxResult.get("msg").toString());
              }
               userId=userId.split("-")[1];
              System.err.println("userId======"+userId);
               List<String> us=mapper.getTeamUser(vo.getDevCode(),userId);
               if(StringUtils.isEmpty(us)){
                   return   AjaxResult.error("该班组没有此人员!");
               }
              //绑定人
               dev.setBidId(userId);
               dev.setBidTime(DateTimeHelper.getNowTime());
               dev.setShStatus(1);
               dev.setFaceStatus("0");
               //更新手环记录信息
               mapper.updateBraceletData(dev);
                //插入手环领用记录
               devUseVo.setBidId(userId);
               //设备类型 1手环 2其他-绑定类型
               devUseVo.setDevType(1);
               //设备
               devUseVo.setBindDevId(dev.getShId());
               devUseVo.setBidTime(dev.getBidTime());
               mapper.insertShUseData(devUseVo);
               return   AjaxResult.success("绑定成功");
           }else{
               return   AjaxResult.error(ajaxResult.get("msg").toString());
           }
       }catch (Exception e){
           log.error(e.toString(),e);
           return   AjaxResult.error("系统异常");
       }
    }

    /**
     * 数据采集接口推送
     * @param vo
     * @return
     */
    @Override
    public AjaxResult setMessage(BraceletImageVo vo) {
        try{
            ObjectMapper objectMapper=new ObjectMapper();
             String  json  = objectMapper.writeValueAsString(vo);
             String uuid= UuidUtils.generateUuid().toUpperCase().replace("-","");
            //电量
            String time=DateTimeHelper.getNowTime();
            vo.setDataCode(SystemConfig.dl_code);
            String   id=mapper.getDevId(vo);
            DevDetailEntity  vvo=mapper.getDevDetails(vo);
            if(ObjectUtils.isNotEmpty(vvo)){
                //电量
                updateDetailData(vvo.getId(),vo.getQuantity());
            }else{
                vvo=insetDetailData(id,"电量",SystemConfig.dl_code,vo.getQuantity(),"%","double");
            }
            HisDataVo hisDataVo=new HisDataVo(json,vvo.getId(),"电量",vo.getQuantity(),"double",id,uuid,"0",time);
            insertHistoryData(hisDataVo);
            // 纬度
            vo.setDataCode(SystemConfig.lat_code);
            vvo=mapper.getDevDetails(vo);
            if(ObjectUtils.isNotEmpty(vvo)){
                //经度
                updateDetailData(vvo.getId(),vo.getLat());
            }else{
                vvo=insetDetailData(id,"纬度",SystemConfig.lat_code,vo.getLat(),"","double");
            }
            hisDataVo=new HisDataVo(json,vvo.getId(),"纬度",vo.getLat(),"double",id,uuid,"0",time);
            insertHistoryData(hisDataVo);
            //经度
            vo.setDataCode(SystemConfig.lon_code);
            vvo=mapper.getDevDetails(vo);
            if(ObjectUtils.isNotEmpty(vvo)){
                //电量
                updateDetailData(vvo.getId(),vo.getLon());
            }else{
                vvo=insetDetailData(id,"经度",SystemConfig.lon_code,vo.getLon(),"","double");
            }
            hisDataVo=new HisDataVo(json,vvo.getId(),"经度",vo.getLon(),"double",id,uuid,"0",time);
            insertHistoryData(hisDataVo);
            //心率
            vo.setDataCode(SystemConfig.xl_code);
            vvo=mapper.getDevDetails(vo);
            if(ObjectUtils.isNotEmpty(vvo)){
                //电量
                updateDetailData(vvo.getId(),vo.getHeartRate());
            }else{
                vvo=insetDetailData(id,"心率",SystemConfig.xl_code,vo.getHeartRate(),"次/分","double");
            }
            hisDataVo=new HisDataVo(json,vvo.getId(),"心率",vo.getHeartRate(),"double",id,uuid,"0",time);
            insertHistoryData(hisDataVo);
            //血压
            vo.setDataCode(SystemConfig.xy_code);
            vvo=mapper.getDevDetails(vo);
            if(ObjectUtils.isNotEmpty(vvo)){
                //电量
                updateDetailData(vvo.getId(),vo.getBloodPressure());
            }else{
                vvo= insetDetailData(id,"血压",SystemConfig.xy_code,vo.getBloodPressure(),"mmHg","double");
            }
            hisDataVo=new HisDataVo(json,vvo.getId(),"血压",vo.getBloodPressure(),"double",id,uuid,"0",time);
            insertHistoryData(hisDataVo);
            //温度
            vo.setDataCode(SystemConfig.wd_code);
            vvo=mapper.getDevDetails(vo);
            if(ObjectUtils.isNotEmpty(vvo)){
                updateDetailData(vvo.getId(),vo.getTemperature());
            }else{
                vvo= insetDetailData(id,"温度",SystemConfig.wd_code,vo.getTemperature(),"℃","double");
            }
            hisDataVo=new HisDataVo(json,vvo.getId(),"温度",vo.getTemperature(),"double",id,uuid,"0",time);
            insertHistoryData(hisDataVo);
        }catch (Exception e){
            log.error(e.toString(),e);
            return   AjaxResult.error("数据处理失败");
        }
        return   AjaxResult.success("推送成功");
    }



    /**
     * 更新手环 验证状态
     * @param devCode
     */
    @Override
    public void updateVerdateStatus(String devCode) {
        try{
            mapper.updateVerdateStatus(devCode,"0");
        }catch (Exception e){
            log.error(e.toString(),e);
        }
    }


    /**
     * 推送数据历史记录插入
     * @param
     */
    public void insertHistoryData(HisDataVo vo) {
        try{
            mapper.insertHistoryData(vo);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
    }


    @Override
    public AjaxResult userVerification(BraceletImageVo vo) {
        try{
            Map<String,Object> ajaxResult=faceInterUtilService2.verifyFace(vo.getImage());
            Integer code= (Integer) ajaxResult.get("code");
            if(code==200){
                //校验人id 去实际人员校验
                String userId= (String) ajaxResult.get("userId");
                         userId=userId.split("-")[1];
                         String bidId=mapper.getDevBindUser(vo);
                    if(userId.equals(bidId)){
                        mapper.updateVerdateStatus(vo.getDevCode(),"1");
                        return   AjaxResult.success("校验成功");
                    }
            }else{
                mapper.updateVerdateStatus(vo.getDevCode(),"2");
                return   AjaxResult.error(ajaxResult.get("msg").toString());
            }
            mapper.updateVerdateStatus(vo.getDevCode(),"2");

        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return   AjaxResult.error("校验失败");
    }

    /**
     *
     * @param vo
     * @return
     */
    @Override
    public List<String> getShCodeByGt(BraceletImageVo vo) {
     return    mapper.getShCodeByGt(vo);
    }

    @Override
    public List<String> getBdShCode(List<String> list) {
        return    mapper.getBdShCode(list);
    }

    /**
     *
     * @param devId
     * @param dataName
     * @param dataCode
     * @param dataValue
     * @param dataUnit
     * @param dataType
     */
    private DevDetailEntity insetDetailData(String devId, String dataName,String dataCode,String dataValue,String dataUnit, String dataType) {
        DevDetailEntity vo=new DevDetailEntity();
        try{

            vo.setDevId(devId);
            vo.setDataName(dataName);
            vo.setDataCode(dataCode);
            vo.setDataVal(dataValue);
            vo.setDataUnit(dataUnit);
            vo.setDataType(dataType);
            mapper.insetDetailData(vo);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return vo;
    }



    /**
     * 更新 设备属性值
     * @param id
     * @param dataValue
     */
    public  void updateDetailData(String id,String dataValue){
        try{
            DevDetailEntity vo=new DevDetailEntity();
             vo.setId(id);
            vo.setDataVal(dataValue);
            vo.setDataLogo(DateTimeHelper.getNowTime());
            mapper.updateDetails(vo);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
    }



}
