package com.supervision.web.peopleGateManage.Controller;

import com.supervision.web.peopleGateManage.Service.DeviceService;
import com.supervision.web.peopleGateManage.Service.PeopleDeviceService;
import com.supervision.web.peopleGateManage.Service.PeopleFaceService;
import com.supervision.web.peopleGateManage.Service.PeopleInfoService;
import com.supervision.web.peopleGateManage.enity.PeopleFace;
import com.supervision.web.peopleGateManage.enity.PeopleInfo;
import com.supervision.web.peopleGateManage.mapper.PeopleFaceMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

@RestController
@RequestMapping("/person")
public class PeopleManageController {

    public static final Logger logger = LoggerFactory.getLogger(PeopleManageController.class);

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private PeopleInfoService peopleInfoService;

    @Autowired
    private PeopleFaceService peopleFaceService;

    @Autowired
    private PeopleDeviceService peopleDeviceService;

    // ------------------- 人员管理 -------------------

    /** 获取设备下的人员 */
    @GetMapping("/info/list/{deviceId}")
    public List<PeopleInfo> getPeopleByDevice(@PathVariable Long deviceId) {
        List<String> personIds = peopleDeviceService.getPersonsByDevice(deviceId);
        return peopleInfoService.getByIds(personIds);
    }

    /**  获取所有人员 */
    @GetMapping("/info/list")
    public List<PeopleInfo> getAllPeople() {
        return peopleInfoService.getAll();

//        List<String> personIds = peopleDeviceService.getPersonsByDevice(deviceId);
//        return peopleInfoService.getByIds(personIds);
    }
    @GetMapping("/info/total")
    public int getPeopleTotal() {
        return peopleInfoService.getPeopleTotal();
    }

    /** 新增人员（仅新增人员，不绑定设备） */
    @PostMapping("/info/add")
    public String addPersonInfo(@RequestBody PeopleInfo peopleInfo) {
//        System.out.println("接收到的数据: " + peopleInfo);
//        peopleInfoService.add(peopleInfo);
        System.out.println("接收到的数据: " + peopleInfo);

        // ⚡ personId 不从前端接收，由 Service 自动生成
        peopleInfo.setPersonId(null);

        peopleInfoService.add(peopleInfo);


        System.out.println("绑定设备: " + peopleInfo.getDeviceId());
        peopleDeviceService.addRelation(peopleInfo.getPersonId(), peopleInfo.getDeviceId());
        System.out.println("关系已写入表 new_people_device");

        return "success";
    }



    /** 给人员绑定设备 */
    @PostMapping("/info/bind")
    public String bindPersonToDevice(@RequestParam String personId, @RequestParam Long deviceId) {
        peopleDeviceService.bindPersonToDevice(personId, deviceId);
        return "success";
    }

    /** 修改人员 */
    @PutMapping("/info/update")
    public String updatePersonInfo(@RequestBody PeopleInfo peopleInfo) {
        peopleInfoService.update(peopleInfo);
        return "success";
    }

    /** 删除人员 */
    @DeleteMapping("/info/delete/{id}")
    public String deletePersonInfo(@PathVariable Long id) {
        peopleInfoService.delete(id);
        return "success";
    }

    // ------------------- 人脸库管理（全局） -------------------

    @Value("${faceImgPath}")
    private String uploadDir;

    @PostMapping("face/upload")
    public Map uploadFace(@RequestParam("file") MultipartFile file) {
        Map res = new HashMap();
        if (file.isEmpty()) {
            res.put("message", "文件为空");
            return res;
        }

        try {
            String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
            String suffix = originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String newFileName = UUID.randomUUID().toString() + suffix;

            File uploadFolder = new File(uploadDir);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdirs();
            }

            File dest = new File(uploadFolder, newFileName);
            file.transferTo(dest);

            String url = "E:\\sourceCode\\faceImg\\" + newFileName;
//
            res.put("url", url);

            res.put("fileName", newFileName);
            res.put("message", "上传成功");
            return res;
        } catch (IOException e) {
            logger.error("上传失败", e);
            res.put("message", "上传失败");
            return res;
        }
    }

//    @GetMapping("/face/{personId}")
//    public ResponseEntity<byte[]> getFace(@PathVariable String fileName) {
//        try {
//            File file = new File(uploadDir, fileName);
//            if (!file.exists()) {
//                return ResponseEntity.notFound().build();
//            }
//
//            byte[] imageBytes = Files.readAllBytes(file.toPath());
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.IMAGE_JPEG); // 或 IMAGE_PNG，根据情况
//
//            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
//        } catch (IOException e) {
//            logger.error("读取图片失败", e);
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
//        }
//    }

    @Autowired
    private PeopleFaceMapper peopleFaceMapper;

//    private static final String UPLOAD_DIR = "E:/sourceCode/faceImg/faces/";
    private static final String UPLOAD_DIR = "E:/sourceCode/faceImg/";

    @GetMapping("/face/{id}")
    public ResponseEntity<Map<String, Object>> getPerson(@PathVariable("id") Long id) {
        // 1. 从 DB 查整条记录（实体里包含 faceImgUrl 字段）
        PeopleFace person = peopleFaceMapper.selectById(id);
        if (person == null) {
            return ResponseEntity.notFound().build();
        }

        Map<String, Object> res = new HashMap<>();
        res.put("id", person.getId());
        res.put("personId", person.getPersonId());
        res.put("jobNumber", person.getJobNumber());
        res.put("name", person.getName());
        // 你数据库里存的是 /uploads/faces/xxx.jpg 这种路径
        String faceImgUrl = person.getFaceImgUrl();
        if (faceImgUrl != null && !faceImgUrl.trim().isEmpty()) {
            try {
                String fileName = faceImgUrl.substring(faceImgUrl.lastIndexOf("/") + 1);
                File file = new File(UPLOAD_DIR, fileName);
                if (file.exists()) {
                    byte[] bytes = Files.readAllBytes(file.toPath());
                    String base64 = Base64.getEncoder().encodeToString(bytes);
                    String mime = fileName.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg";
                    // 返回 base64 字符串和 mime 类型
                    res.put("faceImgBase64", base64);
                    res.put("faceImgMime", mime);
                } else {
                    // 文件丢失：返回 null 或者不放该字段
                    res.put("faceImgBase64", null);
                    res.put("faceImgMime", null);
                }
            } catch (IOException e) {
                // 出错时也返回 500 或者返回空图片字段，根据需要调整
                e.printStackTrace();
                res.put("faceImgBase64", null);
                res.put("faceImgMime", null);
            }
        } else {
            res.put("faceImgBase64", null);
            res.put("faceImgMime", null);
        }

        return ResponseEntity.ok(res);
    }


    @GetMapping("/face/list")
    public List<PeopleFace> getAllFaces() {
        return peopleFaceService.getAll();
    }

    @PostMapping("/face/add")
    public String addFace(@RequestBody PeopleFace peopleFace) {
        peopleFaceService.add(peopleFace);
        return "success";
    }

    @PutMapping("/face/update")
    public String updateFace(@RequestBody PeopleFace peopleFace) {
        peopleFaceService.update(peopleFace);
        return "success";
    }

    @DeleteMapping("/face/delete/{id}")
    public String deleteFace(@PathVariable Long id) {
        peopleFaceService.delete(id);
        return "success";
    }
}
