package jnpf.attendance.controller;

import com.github.pagehelper.PageInfo;
import jnpf.attendance.service.UserFaceService;
import jnpf.attendance.service.UserFaceTxService;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.exception.QueryException;
import jnpf.model.attendance.dto.FaceChangeQueryDto;
import jnpf.model.attendance.dto.FaceQueryDto;
import jnpf.model.attendance.dto.UserDto;
import jnpf.model.attendance.dto.UserFaceDto;
import jnpf.model.attendance.vo.ChangeLogVo;
import jnpf.model.attendance.vo.FaceMiniVo;
import jnpf.model.attendance.vo.UserFaceDetailVo;
import jnpf.model.attendance.vo.UserFaceVo;
import jnpf.model.common.PageDto;
import jnpf.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 人脸识别
 *
 * @author yanwenfu
 * @create 2025-04-08
 */
@RestController
@Slf4j
@RequestMapping(value = "/attendance/user-face")
public class UserFaceController {

    @Resource
    private UserFaceService userFaceService;
    @Resource
    private UserFaceTxService userFaceTxService;
    @Resource
    private UserProvider userProvider;

    /**
     * 下发用户人脸至考勤机
     * @param userId 用户id列表
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @PutMapping(value = "/sync")
    public ActionResult<Object> syncUserFaceToMachine(@RequestParam String userId) throws Exception {

        Integer result = userFaceTxService.syncUserFaceToMachine(userId);
        return ActionResult.success(result);
    }

    /**
     * 人脸对比
     * @param file 人脸图片
     * @return jnpf.base.ActionResult<java.lang.Boolean>
     */
    @PostMapping(value = "/compare")
    public ActionResult<Boolean> getPhotoCheck(@RequestPart MultipartFile file) throws Exception {

        if (!isImageFile(file)) {
            return ActionResult.fail("请上传图片文件进行比对");
        }
        Boolean result = userFaceService.getPhotoCheck(file, userProvider.get());
        return ActionResult.success(result);
    }

    /**
     * 人脸对比2
     * @return jnpf.base.ActionResult<java.lang.Boolean>
     */
    @PostMapping(value = "/compare-sec")
    public ActionResult<Boolean> getPhotoCheck2() throws Exception {

        List<MultipartFile> list = UpUtil.getFileAll();
        MultipartFile file = list.get(0);
        if (!isImageFile(file)) {
            return ActionResult.fail("请上传图片文件进行比对");
        }
        Boolean result = userFaceService.getPhotoCheck(file, userProvider.get());
        return ActionResult.success(result);
    }

    private boolean isImageFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        String contentType = file.getContentType();
        return contentType != null && ConstantUtil.IMAGE_CONTENT_TYPES.contains(contentType);
    }

    /**
     * 录入人脸
     * @param userId 用户id
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @PostMapping
    public ActionResult<Object> addUserFace(@RequestPart("file") MultipartFile file, @RequestPart("userId") String userId) throws Exception {

        if (!isImageFile(file)) {
            return ActionResult.fail("文件格式错误！");
        }
        Integer result = userFaceTxService.uploadUserFace(file, new UserDto(userId), userProvider.get());
        return ActionResult.success(result);
    }

    /**
     * 录入人脸 - add
     * @param userId 用户id
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @PostMapping(value = "/add/{userId}")
    public ActionResult<Object> addUserFace2(@PathVariable("userId") String userId) throws Exception {

        List<MultipartFile> list = UpUtil.getFileAll();
        MultipartFile file = list.get(0);
        if (!isImageFile(file)) {
            return ActionResult.fail("文件格式错误！");
        }
        Integer result = userFaceTxService.uploadUserFace(file, new UserDto(userId), userProvider.get());
        return ActionResult.success(result);
    }

    /**
     * 清空人脸
     * @param userId 用户id
     * @return jnpf.base.ActionResult<java.lang.Object>
     */
    @DeleteMapping(value = "/{userId}")
    public ActionResult<Object> deleteUserFace(@PathVariable(value = "userId") String userId) throws Exception {

        userFaceService.deleteUserFace(userId, userProvider.get());
        return ActionResult.success();
    }

    /**
     * 查看人脸
     * @param userId 用户id
     * @return jnpf.base.ActionResult<jnpf.model.attendance.vo.UserFaceVo>
     */
    @GetMapping(value = "/{userId}")
    public ActionResult<UserFaceVo> getUserFace(@PathVariable(value = "userId") String userId) {

        UserFaceVo userFace = userFaceService.getUserFace(userId);
        return ActionResult.success(userFace);
    }

    /**
     * 查看人脸详情
     * @param id 人脸记录id
     * @return jnpf.base.ActionResult<jnpf.model.attendance.vo.UserFaceVo>
     */
    @GetMapping(value = "/detail/{id}")
    public ActionResult<UserFaceVo> getUserFaceDetail(@PathVariable(value = "id") String id) {

        UserFaceVo userFace = userFaceService.getUserFaceDetail(id);
        return ActionResult.success(userFace);
    }

    /**
     * 用户人脸信息
     * @param userId 用户id
     * @return jnpf.base.ActionResult<jnpf.model.attendance.vo.UserFaceVo>
     */
    @GetMapping(value = "/info/{userId}")
    public ActionResult<FaceMiniVo> getUserFaceInfo(@PathVariable(value = "userId") String userId) {

        FaceMiniVo userFace = userFaceService.getUserFaceInfo(userId);
        return ActionResult.success(userFace);
    }

    /**
     * 变动记录(分页)
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.attendance.vo.ChangeLogVo>>
     */
    @GetMapping(value = "/change-log/page")
    public ActionResult<PageListVO<ChangeLogVo>> getChangeLog(FaceChangeQueryDto queryDto) {

        PageInfo<ChangeLogVo> page = userFaceService.getChangeLogPage(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }

    /**
     * 人脸记录(分页)
     * @param queryDto 查询条件
     * @return jnpf.base.ActionResult<jnpf.base.vo.PageListVO<jnpf.model.attendance.vo.UserFaceDetailVo>>
     */
    @PostMapping(value = "/page")
    public ActionResult<PageListVO<UserFaceDetailVo>> getUserFacePage(@RequestBody @Valid FaceQueryDto queryDto) throws QueryException {

        if (StringUtil.isEmpty(queryDto.getGroupId()) && StringUtil.isEmpty(queryDto.getTeamId())) {
            throw new QueryException("请选择考勤组或班组");
        }
        PageInfo<UserFaceDetailVo> page = userFaceService.getUserFacePage(queryDto);
        return ActionResult.page(page.getList(), FtbUtil.getPagination(page));
    }

    /**
     * 判断用户是否上传人脸
     * @param userId 用户id
     * @return jnpf.base.ActionResult<java.lang.Boolean>
     */
    @GetMapping(value = "/check/{userId}")
    public ActionResult<Boolean> hasUserFace(@PathVariable(value = "userId") String userId) {

        Boolean b = userFaceService.hasUserFace(userId);
        return ActionResult.success(b);
    }

    /**
     * V1.8.2初始化人脸缩略图
     * @param tenantId 租户id
     */
    @NoDataSourceBind
    @GetMapping(value = "/initializationFace")
    public ActionResult<Boolean> initializationFace(@RequestParam("tenantId") String tenantId) {
        try {
            TenantDataSourceUtil.switchTenant(tenantId);
        } catch (LoginException e) {
            throw new RuntimeException("切换租户失败");
        }
        userFaceService.initializationFace(tenantId);
        return ActionResult.success();
    }

}
