package com.yx.face.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yx.face.boot.restful.RestDTO;
import com.yx.face.boot.restful.ServiceException;
import com.yx.face.boot.uitls.DateUtils;
import com.yx.face.boot.uitls.JsonUtils;
import com.yx.face.boot.uitls.SMSOrIdCardUtils;
import com.yx.face.dao.*;
import com.yx.face.model.entity.*;
import com.yx.face.model.search.UserWhitelistSearch;
import com.yx.face.model.vo.AdminVO;
import com.yx.face.model.vo.UserVisitorListVO;
import com.yx.face.model.vo.UserWhitelistVO;
import com.yx.face.service.AdminService;
import com.yx.face.service.UserInfoService;
import com.yx.face.service.UserVisitorListService;
import com.yx.face.service.feign.TBDeviceFaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description:
 * @ClassName UserVisitorListServiceImpl
 * @Author cui
 * @Date 2021/11/5 14:16
 */
@Slf4j
@Service
public class UserVisitorListServiceImpl implements UserVisitorListService {
    @Resource
    private UserVisitorListDao userVisitorListDao;

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserInfoService userInfoService;
    @Resource
    private UserWhitelistDao userWhitelistDao;

    @Resource
    private UserBlackListDao userBlackListDao;

    @Resource
    private FaceDeviceDao faceDeviceDao;

    @Resource
    private FaceRequestLogDao faceRequestLogDao;

    @Autowired
    private AsyncTriggerRetryImpl asyncTriggerRetryImpl;

    @Resource
    private FacePassDao facePassDao;

    @Resource
    private FaceTaskDao faceTaskDao;

    @Override
    public PageInfo<UserVisitorListVO> getPageList(RestDTO<UserWhitelistSearch> dto) {
        UserWhitelistSearch data = dto.getData();

        if (data.getPhone() != null && !data.getPhone().equals("") && (!SMSOrIdCardUtils.isMobile(data.getPhone()))) {
            throw new ServiceException("手机号查询时须填写完整");
        }
        AdminVO info = adminService.getInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("adminVo", info);
        map.put("uws", dto.getData());

        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<UserVisitorListVO> list = userVisitorListDao.selectListBySearch(map);
        for (UserVisitorListVO userVisitorListVO : list) {
            if (StringUtils.isNotBlank(userVisitorListVO.getPhone()))
                userVisitorListVO.setPhone(SMSOrIdCardUtils.hidePhone(userVisitorListVO.getPhone()));
            if (StringUtils.isNotBlank(userVisitorListVO.getIdNumber()))
                userVisitorListVO.setIdNumber(SMSOrIdCardUtils.hideIdNumber(userVisitorListVO.getIdNumber()));
            if (StringUtils.isNotBlank(userVisitorListVO.getName()))
                userVisitorListVO.setName(SMSOrIdCardUtils.hideName(userVisitorListVO.getName().trim()));
        }
        return new PageInfo<>(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addWhite(Integer id, Integer adminId) throws Exception {
        //数据添加到白名单
        UserVisitorList uvl = userVisitorListDao.selectByPrimaryKey(id);
        //校验是否存在
        UserWhitelist byPhoneAndId = userWhitelistDao.getByPhoneAndId(uvl.getPhone(), null, uvl.getAdminId());
        UserWhitelist addWhite = new UserWhitelist();
        addWhite.setAvatar(uvl.getAvatar());
        if (byPhoneAndId != null) {
            addWhite.setUpdateTime(new Date());
            addWhite.setId(byPhoneAndId.getId());
            userWhitelistDao.updateByPrimaryKeySelective(addWhite);
        } else {
            addWhite.setName(uvl.getName());
            addWhite.setPhone(uvl.getPhone());
            addWhite.setCreateTime(new Date());
            addWhite.setStatus(1);
            addWhite.setType(1);
            addWhite.setAdminId(uvl.getAdminId());
            addWhite.setIdNumber(uvl.getIdNumber());
            //添加
            userWhitelistDao.insert(addWhite);
        }
        //删除访客
        userVisitorListDao.deleteByPrimaryKey(id);
        UserWhitelistVO one = userVisitorListDao.selectListOne(addWhite.getId());
        if (one == null) {
            throw new ServiceException("删除失败");
        }
        String avatarBase64 = userInfoService.getAvatarBase64(one.getId(), one.getAvatar());
        if (StringUtils.isBlank(avatarBase64)) {
            throw new ServiceException("人脸照片不规范请重试哦");
        } else {
            one.setAvatar(avatarBase64);
        }
        List<String> faceDeviceOne = faceDeviceDao.selectList(uvl.getAdminId());
        if (faceDeviceOne.isEmpty()) {
            throw new ServiceException("该账号下没绑定设备，添加失败哦~");
        }
        //人脸下发
        Date now = new Date();
        Date date = DateUtils.addYears(now, 1);
        for (String s : faceDeviceOne) {
            one.setSn(s);
            downFaceByTask(one, DateUtils.addMinutes(now, -10), date, 2, 105);
        }
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addBlack(Integer id, Integer adminId) throws Exception {
        //数据添加到白名单
        UserVisitorList uvl = userVisitorListDao.selectByPrimaryKey(id);
        UserBlackList userBlackListOne = new UserBlackList();
        userBlackListOne.setAdminId(uvl.getAdminId());
        userBlackListOne.setPhone(uvl.getPhone());
        UserBlackList userBlackOne = userBlackListDao.selectOne(userBlackListOne);
        UserBlackList userBlackList = new UserBlackList();
        if (userBlackOne != null) {
            userBlackList.setId(userBlackOne.getId());
            userBlackList.setAvatar(userBlackOne.getAvatar());
            userBlackList.setUpdateTime(new Date());
            userBlackListDao.updateByPrimaryKeySelective(userBlackList);
        } else {
            userBlackList.setAvatar(uvl.getAvatar());
            userBlackList.setName(uvl.getName());
            userBlackList.setPhone(uvl.getPhone());
            userBlackList.setCreateTime(new Date());
            userBlackList.setAdminId(uvl.getAdminId());
            userBlackList.setIdNumber(uvl.getIdNumber());
            //添加
            userBlackListDao.insert(userBlackList);
        }
        //删除访客
        userVisitorListDao.deleteByPrimaryKey(id);
         //获取基本信息
        UserWhitelistVO one = userBlackListDao.selectListOne(userBlackList.getId());
        if (one == null) {
            throw new ServiceException("删除失败");
        }
        //获取base64 照片
        String avatarBase64 = userInfoService.getAvatarBase64(one.getId(), one.getAvatar());
        if (StringUtils.isBlank(avatarBase64)) {
            throw new ServiceException("人脸照片不规范请重试哦");
        } else {
            one.setAvatar(avatarBase64);
        }
        List<String> faceDeviceOne = faceDeviceDao.selectList(uvl.getAdminId());
        if (faceDeviceOne.isEmpty()) {
            throw new ServiceException("该账号下没绑定设备，添加失败哦~");
        }
        //人脸下发
        Date now = new Date();
        Date date = DateUtils.addYears(now, 100);
        for (String s : faceDeviceOne) {
            one.setSn(s);
            downFaceByTask(one, DateUtils.addMinutes(now, -10), date, 1, 101);
        }
        return 1;
    }

    /**
     * @param whitelistVO 对应数据
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param type        类型
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> downFaceByTask(UserWhitelistVO whitelistVO, Date startTime, Date endTime, Integer type, Integer rightno) throws Exception {
        Map<String, Object> result = new HashMap<>();
        //天波人脸服务请求日志表
        FaceRequestLog requestLog;
        Date now = new Date();
        //人脸下发表
        FacePass facePass;
        //唯一id
        Long faceTaskId;
        //人脸清除定时任务
        FaceTask faceTask;
        //信息
        String msg;
        //人脸下发到设备里面
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(1);
        Map<String, Object> dataItem = Maps.newHashMapWithExpectedSize(8);
        FaceDevice faceDeviceBySn = faceDeviceDao.getFaceDeviceBySn(whitelistVO.getSn());
        // 下发参数
        dataItem.put("pin", whitelistVO.getId());
        dataItem.put("name", whitelistVO.getName());
        dataItem.put("validPeriodStart", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime));
        dataItem.put("validPeriodEnd", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime));
        dataItem.put("userType", 0);
        dataItem.put("photo", whitelistVO.getAvatar());
        dataItem.put("rightno", rightno);
        dataItem.put("cardid", whitelistVO.getIdNumber());
        data.add(dataItem);
        params.put("SN", whitelistVO.getSn());
        params.put("Data", data);
        //天波人脸服务请求日志表
        requestLog = new FaceRequestLog();
        requestLog.setName("下发人脸");
        requestLog.setContext("/downUser");
        requestLog.setParams("");
        requestLog.setStatus(1);
        requestLog.setUsedTime(0L);
        requestLog.setUpdateTime(now);
        requestLog.setCreateTime(now);
        //人脸下发记录表
        faceRequestLogDao.insertSelective(requestLog);
        params.put("taskId", requestLog.getId());
        //人脸下发表
        facePass = new FacePass();
        facePass.setUserId(whitelistVO.getId());
        facePass.setDeviceSn(faceDeviceBySn.getSn());
        facePass.setDeviceId(faceDeviceBySn.getId());
        facePass.setStartTime(startTime);
        facePass.setEndTime(endTime);
        facePass.setAdminId(whitelistVO.getAdminId());
        facePass.setStatus(2);
        facePass.setType(type);
        facePass.setTaskId(whitelistVO.getAdminId().toString());
        facePass.setUpdateTime(now);
        facePass.setCreateTime(now);
        facePassDao.insertSelective(facePass);
        asyncTriggerRetryImpl.send(params, facePass);

        faceTaskId = faceTaskDao.getFaceTaskId(whitelistVO.getSn(), whitelistVO.getId());
        faceTask = new FaceTask();
        faceTask.setId(faceTaskId);
        faceTask.setTaskTime(facePass.getEndTime());
        faceTask.setStatus(0);
        faceTask.setUpdateTime(now);
        if (faceTaskId == null) {
            faceTask.setDeviceSn(whitelistVO.getSn());
            faceTask.setUserId(whitelistVO.getId());
            faceTask.setCreateTime(now);
            faceTaskDao.insertSelective(faceTask);
        }
        faceTaskDao.updateByPrimaryKeySelective(faceTask);
        return result;
    }
}