package com.mortals.xhx.daemon.task;

import cn.hutool.core.date.DateUtil;
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.xhx.base.system.upload.service.UploadService;
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.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

/**
 * 同步注册用户与预约人数。
 */
@Slf4j
@Service("SyncRegisterUserPicTask")
public class SyncRegisterUserPicTaskImpl implements ITaskExcuteService {

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

    @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 = url + personEntity.getSourcePhotoUri();
            //String downUrl = "http://192.168.0.98:11078/file/fileupload/1679215657433.jpg";
            log.info("downUrl:{}",downUrl);
            byte[] bytes = HttpUtil.downloadBytes(downUrl);
            if(bytes.length>0){
                InputStream inputStream = new ByteArrayInputStream(bytes);
                MultipartFile file = getMultipartFile(inputStream, "photo.jpg");
                String filePath = uploadService.saveFileUpload(file, "file/fileupload",null);
                personEntity.setPhoto(filePath);
                personService.update(personEntity);
            }
        }
    }


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

    }


    /**
     * 获取封装得MultipartFile
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return MultipartFile
     */
    public MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
        FileItem fileItem = createFileItem(inputStream, fileName);
        //CommonsMultipartFile是feign对multipartFile的封装，但是要FileItem类对象
        return new CommonsMultipartFile(fileItem);
    }


    /**
     * FileItem类对象创建
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return FileItem
     */
    public FileItem createFileItem(InputStream inputStream, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[10 * 1024 * 1024];
        OutputStream os = null;
        //使用输出流输出输入流的字节
        try {
            os = item.getOutputStream();
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (IOException e) {
            log.error("Stream copy exception", e);
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error("Stream close exception", e);

                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("Stream close exception", e);
                }
            }
        }

        return item;
    }

    public static void main(String[] args) {


        System.out.println(DateUtil.parse("19951071", "yyyyMMdd"));
    }


}
