package cn.iocoder.yudao.module.system.controller.app.face;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.controller.app.face.dto.QueryDto;
import cn.iocoder.yudao.module.system.controller.app.face.dto.SaveDto;
import cn.iocoder.yudao.module.system.dal.dataobject.face.UserFace;
import cn.iocoder.yudao.module.system.service.face.FaceService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/app/face")
@CrossOrigin
@Slf4j
public class FaceController {


    @Autowired
    private FaceService faceService;



    @PostMapping("/register")
    public synchronized CommonResult<Map<String,String>> faceAdd(SaveDto saveDto) {
        Map<String,String> result = new HashMap<>();

        log.info("添加人脸特征值到数据库");
//        生成雪花id
        long nextId = IdUtil.getSnowflake().nextId();
        CommonResult<Map<String,String>> httpResult = new CommonResult<>();
        MultipartFile file = saveDto.getFile();
        if (file.isEmpty()) {
            httpResult.setMsg("文件为空");
            return httpResult;
        }
        //获取用户信息
        Map<String, String> memberUserById = faceService.getMemberUserById(saveDto.getUserId());
        saveDto.setName(memberUserById.get("nickname"));
        saveDto.setPhone(memberUserById.get("mobile"));
        String imagePath = saveFile(file, saveDto.getUserId());
        // 随机生成一个字符串作为用户ID(测试、实际中禁用)
        UserFace userById = faceService.getUserById(saveDto.getUserId());
        if (ObjectUtils.isEmpty(userById)) {
            UserFace user = new UserFace(nextId, saveDto.getUserId(), saveDto.getPhone(), saveDto.getName(), imagePath);
            faceService.getBaseMapper().insert(user);
//                WebServerEndpoint.sendMessage(JSONUtil.toJsonStr(user));
        } else {
            nextId = userById.getUserId();
            userById.setUrl(imagePath);
            faceService.getBaseMapper().updateById(userById);
        }
        result.put("faceId", String.valueOf(nextId));
        result.put("faceUrl", imagePath);
        httpResult.setData(result);
        return httpResult;
    }


    @GetMapping("/getAll")
    public CommonResult<Page<UserFace>> getAll(QueryDto dto) {

        return CommonResult.success(faceService.getList(dto));
    }


    public String saveFile(MultipartFile file, Long userId) {
        try {
            String uploadDirPath = "facedata/";

            // 创建上传文件目录
            File uploadDir = new File(uploadDirPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String suffix = FileNameUtil.getSuffix(file.getOriginalFilename());
            String imagePath = uploadDirPath + IdUtil.getSnowflakeNextIdStr() + "." + suffix;
            // 获取文件字节并保存到指定路径
            byte[] bytes = file.getBytes();
            Path path = Paths.get(imagePath);
            Files.write(path, bytes);
            return imagePath;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
