package com.yx.face.service.impl;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
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.RestResult;
import com.yx.face.boot.restful.ServiceException;
import com.yx.face.boot.uitls.DateUtils;
import com.yx.face.boot.uitls.SMSOrIdCardUtils;
import com.yx.face.dao.*;
import com.yx.face.model.entity.*;
import com.yx.face.model.query.FaceDeviceQu;
import com.yx.face.model.query.SysLongTermDocumentsQu;
import com.yx.face.model.vo.SystemLongTermDocumentsVO;
import com.yx.face.model.vo.UserVisitorListVO;
import com.yx.face.model.vo.UserWhitelistVO;
import com.yx.face.service.SystemLongTermDocumentsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class SystemLongTermDocumentsServiceImpl implements SystemLongTermDocumentsService {

    @Resource
    private SystemLongTermDocumentsDao systemLongTermDocumentsDao;
    @Resource
    private FaceDeviceDao faceDeviceDao;
    @Resource
    private FaceRequestLogDao faceRequestLogDao;
    @Resource
    private FacePassDao facePassDao;
    @Autowired
    private AsyncTriggerRetryImpl asyncTriggerRetry;
    @Resource
    private FaceTaskDao faceTaskDao;


    @Override
    public PageInfo<SystemLongTermDocumentsVO> getList(RestDTO<SysLongTermDocumentsQu> dto) {
        if (dto.getData() == null) {
            throw new ServiceException("参数有误");
        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<SystemLongTermDocumentsVO> list = systemLongTermDocumentsDao.getList(dto.getData().getAdminId(), dto.getData().getName());
        for (SystemLongTermDocumentsVO vo : list) {
            if (StringUtils.isNotBlank(vo.getPhone()))
                vo.setPhone(SMSOrIdCardUtils.hidePhone(vo.getPhone()));
            if (StringUtils.isNotBlank(vo.getIdNumber()))
                vo.setIdNumber(SMSOrIdCardUtils.hideIdNumber(vo.getIdNumber()));
        }
        return new PageInfo<>(list);
    }

    @Override
    public Integer add(FaceDeviceQu qu) {
        for (String sn : qu.getSns()) {
            faceDeviceDao.update(sn, 2, qu.getAdminId());
        }
        return 1;
    }

    @Override
    public Integer delete(String sn) {
        Integer update = faceDeviceDao.updateStatus(sn, 0, 0);
        return update;
    }

    @Override
    public RestResult<String> singleIssue(Integer id) {
        RestResult<String> objectRestResult = new RestResult<>();
        //获取员工通道
        List<FaceDevice> faceDeviceList = faceDeviceDao.selectTypeFaceDev(2);
        if (faceDeviceList.isEmpty()) {
            objectRestResult.setCode(401);
            objectRestResult.setMsg("设备不在线下发失败");
            return objectRestResult;
        }
        SystemLongTermDocuments systemLongTermDocuments = systemLongTermDocumentsDao.selectByPrimaryKey(id);
        if (systemLongTermDocuments == null) {
            objectRestResult.setCode(401);
            objectRestResult.setMsg("未查询到要下发的人员信息");
            return objectRestResult;
        }
        for (FaceDevice face : faceDeviceList) {
            faceDeviceList(face, systemLongTermDocuments);
        }
        objectRestResult.setCode(200);
        objectRestResult.setMsg("下发成功");
        return objectRestResult;
    }

    /**
     * 判断身份证是否存在
     * @param idNumber
     * @return
     */
    @Override
    public Boolean getByIdNumber(String idNumber) {
        SystemLongTermDocuments systemLongTermDocuments=systemLongTermDocumentsDao.getByIdNumber(idNumber);
        return systemLongTermDocuments!=null;
    }


    public void faceDeviceList(FaceDevice faceDevice, SystemLongTermDocuments systemLongTermDocuments) {
        //天波人脸服务请求日志表
        FaceRequestLog requestLog;
        Date now = new Date();
        //人脸下发表
        FacePass facePass;
        //唯一id
        Long faceTaskId;
        //人脸清除定时任务
        FaceTask faceTask;
        //人脸下发到设备里面
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
        List<Map<String, Object>> data = Lists.newArrayListWithExpectedSize(1);
        Map<String, Object> dataItem = Maps.newHashMapWithExpectedSize(8);
        // 下发参数
        dataItem.put("pin", systemLongTermDocuments.getCardNo());
        dataItem.put("name", systemLongTermDocuments.getName());
        dataItem.put("validPeriodStart", DateUtil.format(systemLongTermDocuments.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        dataItem.put("validPeriodEnd", DateUtil.format(systemLongTermDocuments.getExpireTime(), "yyyy-MM-dd HH:mm:ss"));
        dataItem.put("userType", 0);
        dataItem.put("photo", systemLongTermDocuments.getPhoto());
        dataItem.put("rightno", 105);
        dataItem.put("cardid", systemLongTermDocuments.getIdNumber());
        data.add(dataItem);
        params.put("SN", faceDevice.getSn());
        params.put("Data", data);
        //天波人脸服务请求日志表
        requestLog = new FaceRequestLog();
        requestLog.setName("下发人脸");
        requestLog.setContext("/downUser");
        requestLog.setParams(JSONObject.toJSONString(params));
        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(Long.valueOf(systemLongTermDocuments.getCardNo()));
        facePass.setDeviceSn(faceDevice.getSn());
        facePass.setDeviceId(faceDevice.getId());
        facePass.setStartTime(systemLongTermDocuments.getCreateTime());
        facePass.setEndTime(systemLongTermDocuments.getExpireTime());
        facePass.setAdminId(systemLongTermDocuments.getAdminId());
        facePass.setStatus(2);
        facePass.setType(2);
        facePass.setTaskId(systemLongTermDocuments.getAdminId().toString());
        facePass.setUpdateTime(now);
        facePass.setCreateTime(now);
        //人脸下发
        facePassDao.insertSelective(facePass);
        //数据同步
        asyncTriggerRetry.send(params, facePass);

        faceTaskId = faceTaskDao.getFaceTaskId(faceDevice.getSn(), Long.valueOf(systemLongTermDocuments.getCardNo()));
        faceTask = new FaceTask();
        faceTask.setId(faceTaskId);
        faceTask.setTaskTime(facePass.getEndTime());
        faceTask.setStatus(0);
        faceTask.setUpdateTime(now);
        if (faceTaskId == null) {
            faceTask.setDeviceSn(faceDevice.getSn());
            faceTask.setUserId(Long.valueOf(systemLongTermDocuments.getCardNo()));
            faceTask.setCreateTime(now);
            faceTaskDao.insertSelective(faceTask);
        }
        faceTaskDao.updateByPrimaryKeySelective(faceTask);
    }
}
