package jnpf.attendance.controller;

import cn.hutool.json.JSONUtil;
import jnpf.attendance.service.AttenceMachineService;
import jnpf.model.attendance.vo.attendance.UserTenantVo;
import jnpf.permission.UserApi;
import jnpf.permission.V2UserApi;
import jnpf.permission.model.user.UserNoInfoVo;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.Base64Util;
import jnpf.util.CustomTenantUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 科密考勤机
 *
 * @author yanwenfu
 * @create 2025-08-22
 */
@Slf4j
@RestController
@RequestMapping(value = "/kemi")
public class KeMiController {

    @Resource
    private CustomTenantUtil customTenantUtil;
    @Resource
    private AttenceMachineService attenceMachineService;
    @Autowired
    private Base64Util base64Util;
    @Autowired
    private V2UserApi v2UserApi;

    @NoDataSourceBind
    @PostMapping(value = "/{tenantId}")
    public ResponseEntity<String> messageFromMachine(@PathVariable(value = "tenantId") String tenantId, @RequestBody Map<String, Object> body, HttpServletRequest request) {

        customTenantUtil.checkOutTenant(tenantId);
        // log.error("科密推送 - {}", JSONUtil.toJsonStr(body));
        // 获取命令内容
        String requestCode = request.getHeader("request_code");
        String transId = request.getHeader("trans_id");
        String devId = request.getHeader("dev_id");
        String token = request.getHeader("token");
        String userId = body.get("userId").toString();
        if (requestCode.equals("realtime_glog")) {
            // 实时打卡记录推送
            if (StringUtil.isNotEmpty(userId)) {
                List<UserBoundVO> list = v2UserApi.userListAndCopy(List.of(userId), null, tenantId);
                String userName = "";
                if (null != list && !list.isEmpty()) {
                    userName = list.get(0).getUserName();
                }
                UserTenantVo userTenant = new UserTenantVo(userId, userId, userName, tenantId, devId);
                attenceMachineService.KeMiClockIn(userTenant, devId, tenantId);
            } else {
                log.error("科密: 陌生人打卡, {}", userId);
            }
        } else if (requestCode.equals("realtime_enroll_data")) {
            // 实时登记数据传输
            Object photo = body.get("photo");
            if (null != photo) {
                String photoUrl = base64Util.convertAndUpload(body.get("photo").toString());
                attenceMachineService.updateKeMiPhoto(userId, photoUrl, tenantId);
            } else {
                log.error("未获取到base64图片, 用户id: {}", userId);
            }
        }
        return ResponseEntity.ok()
                .headers(header -> {
                    header.add("response_code", "OK");
                    header.add("trans_id", transId);
                    header.add("token", token);
                })
                .contentType(MediaType.APPLICATION_JSON).body(null);
    }
}
