package com.mortals.xhx.daemon.task;

import cn.hutool.http.HttpUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.utils.ServletUtils;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.module.hik.face.model.req.img.ImgReq;
import com.mortals.xhx.module.hik.face.service.IHikFaceService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 同步员工的证件照片。
 */
@Slf4j
@Service("SyncRegisterUserPicTask")
public class SyncRegisterUserPicTaskImpl implements ITaskExcuteService {

    @Autowired
    private UploadService uploadService;
    @Autowired
    private IHikFaceService hikFaceService;
    @Autowired
    private StaffService staffService;


    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("同步员工照片任务");
        syncRegisterUsersPhotos();
        log.info("同步员工任务照片完成");

    }


    private void syncRegisterUsersPhotos() {
        List<StaffEntity> staffList = staffService.find(new StaffQuery().source(1)).stream()
                .filter(item -> ObjectUtils.isEmpty(item.getPhotoPath()))
                .filter(item -> !ObjectUtils.isEmpty(item.getPicUri())).collect(Collectors.toList());


        for (StaffEntity staff : staffList) {
            ImgReq imgReq = new ImgReq();
            imgReq.setServerIndexCode(staff.getServerIndexCode());
            imgReq.setPicUri(staff.getPicUri());
            try {
                InputStream inputStream = hikFaceService.callPostImgs(imgReq);
                if (!ObjectUtils.isEmpty(inputStream)) {
                    MultipartFile file = ServletUtils.getMultipartFile(inputStream, "photo.jpg");
                    String filePath = uploadService.saveFileUpload(file, "file/fileupload/staff", null);
                    staff.setPhotoPath(filePath);
                    staffService.update(staff);
                } else {
                    log.error("获取图片异常！");
                }
            } catch (Exception e) {
                log.error("下载图片异常", e.getMessage());
            }
        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
