package com.yx.face.service.impl;

import com.beust.jcommander.internal.Maps;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yx.face.boot.restful.RestDTO;
import com.yx.face.boot.restful.ServiceException;
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.FaceRequestLog;
import com.yx.face.model.entity.UserBlackList;
import com.yx.face.model.search.UserWhitelistSearch;
import com.yx.face.model.vo.AdminVO;
import com.yx.face.model.vo.UserBlackListVO;
import com.yx.face.service.AdminService;
import com.yx.face.service.UserBlackListService;
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 javax.persistence.TableGenerator;
import java.util.*;

/**
 * @description:
 * @ClassName UserBlackListServiceImpl
 * @Author cui
 * @Date 2021/11/5 14:16
 */
@Slf4j
@Service
public class UserBlackListServiceImpl implements UserBlackListService {
    @Resource
    private UserBlackListDao userBlackListDao;

    @Resource
    private AdminService adminService;

    @Resource
    private FaceDeviceDao faceDeviceDao;

    @Resource
    private FaceRequestLogDao faceRequestLogDao;

    @Autowired
    private TBDeviceFaceService tbDeviceFaceService;

    @Resource
    private FacePassDao facePassDao;

    @Resource
    private FaceTaskDao faceTaskDao;

    @Autowired
    private AsyncTriggerRetryImpl asyncTriggerRetryImpl;

    @Override
    public PageInfo<UserBlackListVO> 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<UserBlackListVO> list = userBlackListDao.selectListBySearch(map);
        for (UserBlackListVO userBlackListVO : list) {
            if (StringUtils.isNotBlank(userBlackListVO.getPhone()))
                userBlackListVO.setPhone(SMSOrIdCardUtils.hidePhone(userBlackListVO.getPhone()));
            if (StringUtils.isNotBlank(userBlackListVO.getIdNumber()))
                userBlackListVO.setIdNumber(SMSOrIdCardUtils.hideIdNumber(userBlackListVO.getIdNumber()));
        }

        return new PageInfo<>(list);
    }


    @Override
    public Integer delete(Integer id, Integer adminId) throws Exception {
        UserBlackList userBlackList = userBlackListDao.selectByPrimaryKey(id);
        //判断白名单是否存在
        if (userBlackList == null) {
            throw new ServiceException("该数据已不存在，请刷新页面再试哦~");
        }
        //获取 adminId所有设备
        List<String> faceDeviceOne = faceDeviceDao.selectList(userBlackList.getAdminId());
        if (faceDeviceOne.isEmpty()) {
            throw new ServiceException("该设备不存在或离线，请刷新页面再试哦~");
        }
        Long userId = userBlackListDao.setUserId(id, userBlackList.getAdminId());
        //获取设备 删除人脸
        for (String sn : faceDeviceOne) {
            Map<String, Object> result;
            // 1. entrySet遍历，在键和值都需要时使用（最常用）
            Map<String, Object> params = Maps.newHashMap();
            Date now = new Date();
            List<Map<String, Object>> data = new ArrayList<>();
            Map<String, Object> userMap = Maps.newHashMap();
            userMap.put("pin", userId);
            data.add(userMap);
            List<Long> userIds = new ArrayList<>();
            userIds.add(userId);
            params.put("Data", data);
            params.put("SN", sn);
            FaceRequestLog requestLog = new FaceRequestLog();
            requestLog.setName("删除人员人脸信息");
            requestLog.setContext("/delUser");
            requestLog.setParams(JsonUtils.toJson(params));
            requestLog.setStatus(0);
            requestLog.setUsedTime(0L);
            requestLog.setUpdateTime(now);
            requestLog.setCreateTime(now);
            faceRequestLogDao.insertSelective(requestLog);
            params.put("taskId", requestLog.getId());
            try {
                result = tbDeviceFaceService.delUser(params);
                if (!StringUtils.equals("命令下发成功", (String) result.get("msg"))) {
                    //异步下发三次
                    asyncTriggerRetryImpl.delUserRetry(params);
                } else {
                    faceTaskDao.updateFaceTaskStatus(sn, userIds);
                }
                log.info("删除结果={}", result);
            } catch (Exception e) {
                asyncTriggerRetryImpl.delUserRetry(params);
                log.info("删除人脸异常 {}", e.getMessage());
            }
        }
        userBlackListDao.deleteByPrimaryKey(id);
        return 1;
    }
}
