package com.zd.face.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.zd.common.core.domain.R;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.IdUtils;
import com.zd.common.swagger.config.Knife4jConfiguration;
import com.zd.face.config.FaceProperties;
import com.zd.face.handle.FaceEngineFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: zhoupan
 * @Date: 2021/10/13/13:21
 * @Description:
 */
@Api(tags = "【人脸识别服务管理】")
@ApiSupport(author = Knife4jConfiguration.Author.ZP)
@RestController
@RequestMapping("faceManagerApi")
public class FaceManagerApi {
    @Autowired
    FaceEngineFactory faceEngineFactory;

    @Autowired
    FaceProperties faceProperties;


    final static Set<String> libSet = new HashSet<>();
    static {
        libSet.add("libarcsoft_face.dll");
        libSet.add("libarcsoft_face_engine.dll");
        libSet.add("libarcsoft_face_engine_jni.dll");
        libSet.add("libarcsoft_face.so");
        libSet.add("libarcsoft_face_engine.so");
        libSet.add("libarcsoft_face_engine_jni.so");

    }


    @PostMapping()
    @ApiOperation("上传sdk-lib")
    public R uploadLib(@RequestParam("files") MultipartFile [] multipartFiles) throws IOException {

        String path =faceEngineFactory.getPath();

//        final String path = absolutePath+ File.separator+faceProperties.getLib_folder();

        //先删除原来的文件。。如果直接删除，但又没有保存成功还会导致之前的功能异常，所以这里要先保存再删除
        //生成操作ID
        String id= IdUtils.simpleUUID();

        Map<String,MultipartFile> temp = new HashMap<>(multipartFiles.length);

        for (int i = 0; i < multipartFiles.length; i++) {

            String originalFilename = multipartFiles[i].getOriginalFilename();
            if(!libSet.contains(originalFilename))
            {
                return R.fail("上传文件名错误，请确认为:"+libSet.stream().collect(Collectors.joining(",")));
            }
            temp.put( originalFilename,multipartFiles[i]);
        }

        if(CollUtil.isNotEmpty(temp))
        {
            try {
                Map<String,File> tempFile = new HashMap<>(temp.size());
                temp.forEach((k,v)->{
                    //创建文件
                    File touch = FileUtil.touch(path + File.separator + k+id);
                    try {
                        v.transferTo(touch);
                        tempFile.put(k,touch);
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new ServiceException("创建lib文件出错："+e.getMessage());
                    }
                });
                //todo 这里应该先备份一次
                temp.forEach((a,b)->{
                    FileUtil.copy(path + File.separator +a,path + File.separator +a+"_copy",true);
                });
                try {
                    tempFile.forEach((a,b)->{
                        FileUtil.rename(b,path+ File.separator,true);
                    });
                } catch (Exception e) {
                    //出现异常后还原文件
                    tempFile.forEach((a,b)->{
                        FileUtil.copy(path + File.separator +a+"_copy",path + File.separator +a,true);
                    });
                    throw new ServiceException("替换lib文件出错："+e.getMessage());
                }
                //如果是三个lib文件都上传了，则调用激活
                faceEngineFactory.activeOnline();
            } finally {
                //是否成功都要删除
                temp.forEach((k,v)->{
                    FileUtil.del(path + File.separator + k + id);
                    FileUtil.del(path + File.separator + k + "_copy");
                });

            }
        }
        else
        {
            R.fail("没有找到符合的lib文件！");
        }
        return R.ok();

    }


    @PostMapping("activation")
    @ApiOperation("激活")
    public R activation() throws IOException {
        faceEngineFactory.activeOnline();
        return R.ok("激活成功！");
    }

}
