package jnpf.attendance.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jnpf.SocketApi;
import jnpf.attendance.annotation.Machine;
import jnpf.attendance.service.AttenceMachineService;
import jnpf.attendance.service.AttendanceUserFaceService;
import jnpf.base.ActionResult;
import jnpf.enums.attendance.ActionEnum;
import jnpf.enums.attendance.MachineEnum;
import jnpf.model.attendance.dto.UserFaceDto;
import jnpf.model.attendance.vo.UserFaceVo;
import jnpf.util.CustomTenantUtil;
import jnpf.util.DateDetail;
import jnpf.util.NoDataSourceBind;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 考勤机控制器
 *
 * @author yanwenfu
 * @create 2023-11-08
 */
@Slf4j
@RestController
public class AttenceMachineController {

    @Resource
    private AttenceMachineService attenceMachineService;

    @Resource
    private AttendanceUserFaceService attendanceUserFaceService;

    @Autowired
    private CustomTenantUtil customTenantUtil;

    @Autowired
    private SocketApi socketApi;

    /**
     * 查询用户人脸
     * @param userId 用户id
     * @return java.lang.Object
     */
    @GetMapping(value = "/userface/{userId}")
    public Object getUserFace(@PathVariable(value = "userId") String userId) {

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

    /**
     * 新增人脸
     * @param userFaceDto 人脸数据
     * @return java.lang.Object
     */
    @PostMapping(value = "/userface")
    public Object addUserFace(@RequestBody @Valid UserFaceDto userFaceDto) {

        attendanceUserFaceService.addUserFace(userFaceDto);
        return ActionResult.success();
    }

    /**
     * 修改人脸
     * @param userFaceDto 人脸数据
     * @return java.lang.Object
     */
    @PutMapping(value = "/userface")
    public Object updateUserFace(@RequestBody @Valid UserFaceDto userFaceDto) {

        attendanceUserFaceService.updateUserFace(userFaceDto);
        return ActionResult.success();
    }

    /**
     * 删除人脸
     * @param userId 用户id
     * @return java.lang.Object
     */
    @DeleteMapping(value = "/userface/{userId}")
    public Object deleteUserFace(@PathVariable(value = "userId") String userId) {

        attendanceUserFaceService.deleteUserFace(userId);
        return ActionResult.success();
    }

    /**
     * 上传打卡记录
     * @param params 打卡数据
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @PostMapping(value = "/record/face")
    @NoDataSourceBind
    // @Machine(dealAction = ActionEnum.DA_KA, factory = MachineEnum.MAO_TONG)
    public Map<String, Object> uploadRecordFace(@RequestBody Map<String, Object> params) {

        Map<String, Object> map = new HashMap<>();
        map.put("Result", 0);
        map.put("Msg", "");
        return map;
    }

    /**
     * 识别后在线验证
     * @param params 打卡数据
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @PostMapping(value = "/verify_user")
    @NoDataSourceBind
    @Machine(dealAction = ActionEnum.DA_KA, factory = MachineEnum.MAO_TONG)
    public Map<String, Object> verifyUser(@RequestBody Map<String, Object> params) {

        log.info("MaoTong-Clock: {}", params);
        Map<String, Object> map = new HashMap<>();
        Object sn = params.get("sn");
        if (null == sn) {
            map.put("Result", 3);
            map.put("Msg", "设备id不能为空");
            return map;
        }
        Object userIdObj = params.get("user_id");
        if (null == userIdObj || StringUtils.isEmpty(userIdObj.toString())) {
            map.put("Result", 3);
            map.put("Msg", sn + "打卡用户不能为空");
            return map;
        }
        log.error("开始打卡，设备号：{}，用户：{}", sn, userIdObj);
        String[] split = userIdObj.toString().split("@");
        String tenantId = split[0];
        String userId = split[1];
        customTenantUtil.checkOutTenant(tenantId, userId);
        String b = attenceMachineService.clockIn(sn.toString(), userId, tenantId);
        String message;
        switch (b) {
            case "0":
                message = "已记录";
                break;
            case "1":
                message = "打卡成功";
                break;
            case "2":
                message = "迟到";
                break;
            case "3":
                message = "早退";
                break;
            default:
                message = b;
                break;
        }
        map.put("Result", 0);
        map.put("Msg", message);
        JSONObject json = new JSONObject();
        json.set("voice_code", -2);
        json.set("voice_text", message);
        map.put("Content", json);
        return map;
    }

    /**
     * 陌生人打卡
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @PostMapping(value = "/stranger")
    @NoDataSourceBind
    public Map<String, Object> strangerClockIn(@RequestBody Map<String, Object> params) {

        String sn = params.get("sn").toString();
        log.error("陌生人打卡，设备号：{}，打卡时间：{}", sn, DateDetail.getDateTime2Str(new Date()));
        Map<String, Object> map = new HashMap<>();
        map.put("Result", 0);
        map.put("Msg", "");
        return map;
    }

    /**
     * 设备录入自定义编号判断
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @PostMapping(value = "/addFace")
    @NoDataSourceBind
    public Map<String, Object> addFace(@RequestBody Map<String, Object> params) {

        Map<String, Object> map = new HashMap<>();
        map.put("Result", 0);
        map.put("Msg", "");
        return map;
    }

    /**
     * 更新用户信息
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @PostMapping(value = "/user/inf_photo")
    @NoDataSourceBind
    public Map<String, Object> updateUserInfoPhoto(@RequestBody Map<String, Object> params) {

        log.error("更新用户信息...");
        return attenceMachineService.updateUserInfoPhoto(params);
    }

    @GetMapping(value = "/sendUser")
    public Object testSendUser(@RequestParam(value = "code") String code, @RequestParam(value = "userId") String userId, @RequestParam(value = "sn") String sn) {

        attenceMachineService.sendUserToMachine(code, userId, sn);
        return ActionResult.success();
    }

    @GetMapping(value = "/changeImg")
    public Object testChangeImg() {
        String img = attenceMachineService.changeImg();
        return ActionResult.success(img);
    }

    @GetMapping(value = "/testSendMsg")
    public void testSendMsg() {

        socketApi.sendMsg2Client("kaijiayi", "123", "虚空消息...");
    }
}
