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.common.code.SourceEnum;
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.person.model.PersonEntity;
import com.mortals.xhx.module.person.model.PersonQuery;
import com.mortals.xhx.module.person.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
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")
@ConditionalOnExpression("'${hik.host:}'!=''")
public class SyncRegisterUserPicTaskImpl implements ITaskExcuteService {

    @Autowired
    private PersonService personService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private IHikFaceService hikFaceService;

    @Value("${php.host:''}")
    private String host;


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

    }


    private void syncRegisterUsersPhotos() {
        String url = host.endsWith("/") ? host : host + "/";
        List<PersonEntity> collect = personService.find(new PersonQuery()).stream()
                .filter(item -> ObjectUtils.isEmpty(item.getPhoto()))
                .filter(item -> !ObjectUtils.isEmpty(item.getSourcePhotoUri())).collect(Collectors.toList());
        for (PersonEntity personEntity : collect) {
            //下载图片到本地保存并更新
            //String downUrl = "http://192.168.0.98:11078/file/fileupload/1679215657433.jpg";
            String downUrl = url + personEntity.getSourcePhotoUri();
            log.info("downUrl:{}", downUrl);
            byte[] bytes = HttpUtil.downloadBytes(downUrl);
            if (bytes.length > 0) {
                InputStream inputStream = new ByteArrayInputStream(bytes);
                MultipartFile file = ServletUtils.getMultipartFile(inputStream, "photo.jpg");
                String filePath = uploadService.saveFileUpload(file, "file/fileupload", null);
                personEntity.setPhoto(filePath);
                personService.update(personEntity);
            }
        }

        List<PersonEntity> hikPerson = personService.find(new PersonQuery().source(SourceEnum.海康系统.getValue())).stream().filter(f -> ObjectUtils.isEmpty(f.getPhoto())).collect(Collectors.toList());
        for (PersonEntity person : hikPerson) {
            ImgReq imgReq = new ImgReq();
            imgReq.setSvrIndexCode(person.getServerIndexCode());
            imgReq.setPicUri(person.getPicUrl());
            try {
                InputStream inputStream = hikFaceService.callPostImgs(imgReq);
                if (!ObjectUtils.isEmpty(inputStream)) {
                    MultipartFile file = ServletUtils.getMultipartFile(inputStream, "photo.jpg");
                    String filePath = uploadService.saveFileUpload(file, "file/fileupload", null);
                    person.setPhoto(filePath);
                    personService.update(person);
                } else {
                    log.error("获取图片异常！");
                }
            } catch (Exception e) {
                log.error("下载图片异常", e.getMessage());
            }
        }
    }


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

    }
}
