package com.community.huiju.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.commom.ailiyun.AESDecode;
import com.community.commom.constant.Constant;
import com.community.commom.hk.HKOpenApi;
import com.community.commom.session.UserElement;
import com.community.huiju.common.base.ResponseBean;
import com.community.huiju.dao.*;
import com.community.huiju.enums.ResponseErrorsMessages;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.*;
import com.community.huiju.service.FaceServiceI;
import com.community.huiju.service.IHKService;
import com.community.huiju.service.ImageServiceI;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("faceServicel")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class FaceServicelimpl  extends ServiceImpl<TaFaceMapper, TaFace> implements FaceServiceI {


    @Autowired
    private TaFaceMapper taFaceMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private TaSysRoleMapper taSysRoleMapper;

    @Autowired
    private ImageServiceI imageServiceI;

    @Autowired
    private TaUserVerifyMapper taUserVerifyMapper;

    @Autowired
    private IHKService ihkService;

    @Autowired
    private TpEquipmentMapper tpEquipmentMapper;

    @Autowired
    private TpConfigurationMapper tpConfigurationMapper;

    @Autowired
    private TpEquipmentTreeMapper tpEquipmentTreeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addFace(Integer userId, Integer userVerifyId, MultipartFile uploadFile) {
        ResponseBean responseBean = new ResponseBean();
        // 判断房产是否存在关联关系
        TaUserVerify userVerify = taUserVerifyMapper.selectByUserIdAndUserVerifyId(userId, userVerifyId);
        if (null == userVerify) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_VERIFY.getCode(), ResponseErrorsMessages.NOT_USER_VERIFY.getMsg());
            return responseBean;
        }

        TpEquipmentTree tpEquipmentTree = tpEquipmentTreeMapper.selectByCommunityId(userVerify.getCommunityId());

        // 当前人脸图片url
        String faceImg = img(uploadFile);

        /**
         * 删除的时候，将所有的海康设备的关联关系删除了，需要重新下发一次
         */
        // 下发门禁
        ihkService.pushPerson(userId + "", userVerifyId);

        TaUser user = taUserMapper.selectById(userId);
        TaFace taFace = new TaFace();
        taFace.setFaceImg(faceImg);
        taFace.setCommunityId(user.getCommunityId());
        taFace.setTaUserVerifyId(userVerifyId);
        taFace.setCreateUser(userId);
        taFace.setUpdateUser(userId);
        taFace.setCreateDate(new Date());
        taFace.setUpdateDate(new Date());

        /*验证身份*/
        responseBean = addVerify(userId, userVerifyId, uploadFile, faceImg, taFace, tpEquipmentTree);
        return responseBean;
    }

    /**
     * 修改人脸信息
     *
     * @param userId 登入人ID
     * @param userVerifyId 房产审核id
     * @param uploadFile
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateFace(Integer userId, Integer userVerifyId, MultipartFile uploadFile) {
        ResponseBean responseBean = new ResponseBean();
        // 判断房产是否存在关联关系
        TaUserVerify userVerify = taUserVerifyMapper.selectByUserIdAndUserVerifyId(userId, userVerifyId);
        if (null == userVerify) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_VERIFY.getCode(), ResponseErrorsMessages.NOT_USER_VERIFY.getMsg());
            return responseBean;
        }

        TpEquipmentTree tpEquipmentTree = tpEquipmentTreeMapper.selectByCommunityId(userVerify.getCommunityId());
        // 人脸图片地址url
        String faceImg = img(uploadFile);

        /**
         * 删除的时候，将所有的海康设备的关联关系删除了，需要重新下发一次
         */
        // 下发门禁
        ihkService.pushPerson(userId + "", userVerifyId);

        //当前修改的id否存在
        TaFace face = taFaceMapper.getByUserVerifyId(userVerifyId);
        if (null == face) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_FACE.getCode(), ResponseErrorsMessages.NOT_USER_FACE.getMsg());
            return responseBean;
        }

        face.setTaUserVerifyId(userVerifyId);
        face.setFaceImg(faceImg);
        face.setUpdateUser(userId);
        face.setUpdateDate(new Date());
        ResponseBean resps = checKout(faceImg, face, false, uploadFile, userId, userVerify.getCommunityId(), userVerify.getRoomNoId(), userVerify.getUnitId(), tpEquipmentTree.getAppkey(), tpEquipmentTree.getSecret(), tpEquipmentTree.getHttpServer());
        if (resps.getCode().equals("0")) {
            resps.addSuccess(face);
        } else {
            resps.addError(resps.getCode(), resps.getMessage());
        }
        return resps;
    }

    /**
     * 验证图片是否为人脸，推送海康
     * @param faceImg
     * @param taFace
     * @param isA
     * @param uploadFile
     * @param userId
     * @param communityId
     * @param roomNoId
     * @param unitId
     * @param appkey
     * @param secret
     * @param openapi_ip_port_http 海康服务器地址
     * @return
     */
    public ResponseBean checKout(String faceImg, TaFace taFace, boolean isA, MultipartFile uploadFile, Integer userId, Integer communityId, Integer roomNoId, Integer unitId, String  appkey, String secret, String openapi_ip_port_http) {
        ResponseBean responseBean = new ResponseBean();
        TaUser user = taUserMapper.selectById(userId);
        if (user.getHkUserId() == null) {
            log.error("本地库人员ID：{}  的海康人员ID不存在", userId);
            throw new WisdomException(ResponseErrorsMessages.NOT_PUSH_FACE.getCode(), ResponseErrorsMessages.NOT_PUSH_FACE.getMsg());
        }
        AESDecode aesd = new AESDecode();
        String body = "{\"type\": \"0\", \"image_url\":\"" + faceImg + "\"}";
        try {
            com.community.commom.mode.ResponseBean send = aesd.send(body);
            JSONObject jsonObject = JSONObject.parseObject(send.getMessage());
            Integer type = (Integer) jsonObject.get("errno");
            Integer faceNum = (Integer) jsonObject.get("face_num");

            /*推送海康*/
            String data = HKOpenApi.HKpersonGroupId(uploadFile, user.getHkUserId(), user.getHkPersonNo(), user.getUserName(), user.getHkCardNo(), appkey, secret, openapi_ip_port_http);
            /*boolean isA为true进行添加，为false进行修改*/
            if (0 == type && 1 == faceNum) {
                if (null == data) {
                    log.error("未得到，海康数据反馈！");
                    throw new WisdomException(ResponseErrorsMessages.NOT_PUSH_FACE.getCode(), ResponseErrorsMessages.NOT_PUSH_FACE.getMsg());
                }
                if (isA) {
                    taFaceMapper.insert(taFace);
                } else {
                    taFaceMapper.updateById(taFace);
                }
                responseBean.addSuccess(taFace);

                // 设备树
                TpEquipmentTree tpEquipmentTree = tpEquipmentTreeMapper.selectByCommunityId(communityId);
                // 所有设备
                List<TpEquipment> tpEquipments = tpEquipmentMapper.selectByCommunityIdAndUnitId(communityId, unitId, 4);
                List<Map<String, Object>> equipmentUUID = getEquipmentUUID(tpEquipments);
                StringBuilder doorUuids = new StringBuilder();
                StringBuilder deviceUuids = new StringBuilder();
                equipmentUUID.forEach(e-> {
                    doorUuids.append(e.get("doorUuid"));
                    doorUuids.append(",");
                    deviceUuids.append(e.get("deviceUuid"));
                    deviceUuids.append(",");
                });
                Map<String,Object> map = Maps.newHashMap();
                map.put("appkey", tpEquipmentTree.getAppkey());
                map.put("opUserUuid", tpEquipmentTree.getOpUserUuid());
                map.put("personIds", String.valueOf(user.getHkUserId()));
                map.put("deviceUuids", deviceUuids.substring(0, deviceUuids.lastIndexOf(",")));
                map.put("type", 1);
                map.put("openapi_ip_port_http", tpEquipmentTree.getHttpServer());
                HKOpenApi.downloadFaceAndFingerInfos(map);

                //可视对讲时 指定人员人脸权限下载
                List<Integer> userIdList = new ArrayList<>();
                userIdList.add(user.getHkUserId());
                //临时设备编号
                // TODO 根据期楼栋号，来查询出门口机

                // 单元门口机
                List<TpEquipment> visualEquipments = tpEquipmentMapper.selectByCommunityIdAndUnitId(communityId, unitId, 3);
                List<String> visualList = visualEquipments.stream()
                        .map(e-> tpConfigurationMapper.selectById(e.getUuidId()).getConfigurationValue())
                        .collect(Collectors.toList());
//                List<String> visualList = new ArrayList<>();
//                visualList.add("10010100000");
                HKOpenApi.visualIntercom(tpEquipmentTree.getOpUserUuid(), 1, userIdList, visualList, tpEquipmentTree.getAppkey(), tpEquipmentTree.getSecret(), tpEquipmentTree.getHttpServer());
            } else {
                responseBean.addError(ResponseErrorsMessages.FACE_ERROR.getCode(), ResponseErrorsMessages.FACE_ERROR.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("海康人脸推送失敗！ {}", e);
            throw new WisdomException(ResponseErrorsMessages.NOT_PUSH_FACE.getCode(), ResponseErrorsMessages.NOT_PUSH_FACE.getMsg());
        }
        return responseBean;
    }

    /**
     * 获取设备UUID
     * @param equipmentList
     * @return
     */
    private List<Map<String,Object>> getEquipmentUUID(List<TpEquipment> equipmentList) {
        return equipmentList.stream().map(equipment -> {
            TpConfiguration tpConfiguration = tpConfigurationMapper.selectById(equipment.getUuidId());
            Map<String,Object> map = Maps.newHashMap();
            map.put("doorUuid", tpConfiguration.getDoorUuid());
            map.put("deviceUuid", tpConfiguration.getDeviceUuid());
            return map;
        }).collect(Collectors.toList());
    }

    /**
     * 当前登入人是否有人脸信息
     */
    @Override
    public ResponseBean getTaFaceByUserId(Integer userId, Integer userVerifyId) {
        ResponseBean responseBean = new ResponseBean();

        TaUserVerify userVerify = taUserVerifyMapper.selectByUserIdAndUserVerifyId(userId, userVerifyId);
        if (null == userVerify) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_VERIFY.getCode(), ResponseErrorsMessages.NOT_USER_VERIFY.getMsg());
            return responseBean;
        }


        TaFace face = taFaceMapper.getByUserVerifyId(userVerifyId);
        if (null != face) {
            responseBean.addSuccess(face);
            return responseBean;
        }
        responseBean.addError(ResponseErrorsMessages.NOT_USER_FACE.getCode(), ResponseErrorsMessages.NOT_USER_FACE.getMsg());
        return responseBean;

    }


    /**
     * 得到当前图片
     */
    private String img(MultipartFile uploadFile) {
        String faceImg = null;
        try {
            faceImg = imageServiceI.getImageUrl(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return faceImg;
    }

    /**
     * 各种身份校验
     */
    public ResponseBean addVerify(Integer userid, Integer userVerifyId, MultipartFile uploadFile, String faceImg, TaFace taFace, TpEquipmentTree tpEquipmentTree) {
        ResponseBean response = new ResponseBean();

        TaUserVerify userVerify = taUserVerifyMapper.selectById(userVerifyId);
        if (null == userVerify) {
            response.addError(ResponseErrorsMessages.NOT_VERIFY.getCode(), ResponseErrorsMessages.NOT_VERIFY.getMsg());
            return response;
        }
        TaUser taUser = taUserMapper.selectById(userid);

        //身份为家属租客，状态为已停用
        if (null != taUser && !Constant.EFFECTIVE_STATUS.equals(taUser.getStatus())) {
            response.addError(ResponseErrorsMessages.NOT_IDENTITY_VERIFY.getCode(), ResponseErrorsMessages.NOT_IDENTITY_VERIFY.getMsg());
            return response;
        }

        //查询当前用户是否有人脸记录
        TaFace face = taFaceMapper.getByUserVerifyId(userVerifyId);
        if (null == face) {
            boolean isA = true;
            if (Constant.EFFECTIVE_STATUS.equals(taUser.getStatus())) {
                ResponseBean responseBean = checKout(faceImg, taFace, isA, uploadFile, userid, userVerify.getCommunityId(), userVerify.getRoomNoId(), userVerify.getUnitId(),tpEquipmentTree.getAppkey(), tpEquipmentTree.getSecret(), tpEquipmentTree.getHttpServer());
                if (responseBean.getCode().equals("0")) {
                    responseBean.addSuccess("人脸录入成功");
                } else {
                    responseBean.addError(responseBean.getCode(),responseBean.getMessage());
                }
                return responseBean;
            }
        }
        response.addError(ResponseErrorsMessages.EXIST_FACE.getCode(), ResponseErrorsMessages.EXIST_FACE.getMsg());
        return response;
    }

    @Override
    public ResponseBean deleteFace(Integer userId, Integer userVerifyId) {
        ResponseBean responseBean= new ResponseBean();
        TaUserVerify taUserVerify= infoExist(userVerifyId);
        if (null ==taUserVerify) {
            responseBean.addError(ResponseErrorsMessages.NOT_USER_VERIFY_1.getCode(), ResponseErrorsMessages.NOT_USER_VERIFY_1.getMsg());
            return responseBean;
        }
        TaUser taUser = taUserMapper.selectById(taUserVerify.getUserId());

        // 设备树
        TpEquipmentTree tpEquipmentTree = tpEquipmentTreeMapper.selectByCommunityId(taUserVerify.getCommunityId());
        // 所有设备
        List<TpEquipment> tpEquipments = tpEquipmentMapper.selectByCommunityIdAndUnitId(taUserVerify.getCommunityId(), taUserVerify.getUnitId(), 4);
        if (CollectionUtils.isEmpty(tpEquipments)) {
            responseBean.addError(ResponseErrorsMessages.NOT_EQUIPMENT.getCode(), ResponseErrorsMessages.NOT_EQUIPMENT.getMsg());
            return responseBean;
        }
        List<Map<String, Object>> equipmentUUID = getEquipmentUUID(tpEquipments);
        StringBuilder doorUuids = new StringBuilder();
        StringBuilder deviceUuids = new StringBuilder();
        equipmentUUID.forEach(e-> {
            doorUuids.append(e.get("doorUuid"));
            doorUuids.append(",");
            deviceUuids.append(e.get("deviceUuid"));
            deviceUuids.append(",");
        });


        // TODO 删除人脸，是否删除海康
        // 修改人脸(图片为null时。海康删除人脸)
//        HKOpenApi.HKpersonGroupId(null, taUser.getHkUserId(), taUser.getHkPersonNo(), taUser.getUserName(), taUser.getHkCardNo(), tpEquipmentTree.getAppkey(), tpEquipmentTree.getSecret());
        // 删除 权限
        Map<String,Object> selectUserFaceMap = Maps.newHashMap();
        selectUserFaceMap.put("personIds", taUser.getHkUserId()+"");
        selectUserFaceMap.put("opUserUuid", tpEquipmentTree.getOpUserUuid());
        selectUserFaceMap.put("appkey", tpEquipmentTree.getAppkey());
        selectUserFaceMap.put("secret", tpEquipmentTree.getSecret());
        selectUserFaceMap.put("openapi_ip_port_http", tpEquipmentTree.getHttpServer());
        // 查询人脸信息
        HKOpenApi.selectUserFace(selectUserFaceMap);

        Map<String,Object> deleteUserMap = Maps.newHashMap();
        deleteUserMap.put("personIds", taUser.getHkUserId()+"");
        deleteUserMap.put("opUserUuid", tpEquipmentTree.getOpUserUuid());
        deleteUserMap.put("doorUuids", doorUuids.substring(0, doorUuids.lastIndexOf(",")));
        deleteUserMap.put("appkey", tpEquipmentTree.getAppkey());
        deleteUserMap.put("secret", tpEquipmentTree.getSecret());
        deleteUserMap.put("openapi_ip_port_http", tpEquipmentTree.getHttpServer());
        // 删除当前人脸设备信息
        String data= HKOpenApi.deleteUser(deleteUserMap);
        JSONObject object= JSONObject.parseObject(data);

        if (object.get("errorCode").equals(1)){
            String errorMessage=  object.getString("errorMessage");
            log.info("删除人脸信息异常：{}", data);
            responseBean.addError(ResponseErrorsMessages.DELETE_FACE.getCode(), ResponseErrorsMessages.DELETE_FACE.getMsg());
            return responseBean;
        }

        taFaceMapper.deleteFace(userVerifyId);
        // 异动同步到设备
        Map<String,Object> appointJurisdictionMap = Maps.newHashMap();
        appointJurisdictionMap.put("appkey", tpEquipmentTree.getAppkey());
        appointJurisdictionMap.put("secret", tpEquipmentTree.getSecret());
        appointJurisdictionMap.put("opUserUuid", tpEquipmentTree.getOpUserUuid());
        appointJurisdictionMap.put("personIds", taUser.getHkUserId()+"" );
        appointJurisdictionMap.put("doorUuids", doorUuids.substring(0, doorUuids.lastIndexOf(",")));
        appointJurisdictionMap.put("operateType",3);
        appointJurisdictionMap.put("includeFinger",0);
        appointJurisdictionMap.put("openapi_ip_port_http", tpEquipmentTree.getHttpServer());

         HKOpenApi.appointJurisdiction(appointJurisdictionMap);
        // HKOpenApi.selectUserSynchronization();
        // ihkService.downloadAuthorityByDeviceUuids();
        return responseBean;

    }

    /**
     * 校验房产是否审核通过
     * @param verifyID
     * @return
     */
    public TaUserVerify infoExist(Integer verifyID){
      TaUserVerify taUserVerify = null;
      if (null != verifyID) {
        taUserVerify = taUserVerifyMapper.selectById(verifyID);
      }
      if (null!= taUserVerify && taUserVerify.getVerifyStatus().equals("1")) {
          return taUserVerify;
      }
      return  taUserVerify;
    }
}


