package jnpf.attendance.controller;

import cn.hutool.json.JSONObject;
import jnpf.attendance.annotation.Machine;
import jnpf.attendance.service.AttenceMachineService;
import jnpf.attendance.service.IsPerfMachineService;
import jnpf.attendance.service.MachineStrategy;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.enums.attendance.ActionEnum;
import jnpf.enums.attendance.MachineEnum;
import jnpf.model.attendance.dto.SecondCheckDto;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.ConstantUtil;
import jnpf.util.CustomTenantUtil;
import jnpf.util.NoDataSourceBind;
import jnpf.util.RedisUtil;
import jnpf.util.TenantUtil;
import jnpf.util.attendance.MachineStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 开架易控制器
 *
 * @author yanwenfu
 * @create 2024-04-01
 */
@RestController
@Slf4j
public class IsPerfMachineController {

    @Resource
    private IsPerfMachineService isPerfMachineService;

    @Resource
    private AttenceMachineService attenceMachineService;

    @Resource
    private MachineStrategyFactory machineStrategyFactory;

    @Autowired
    private CustomTenantUtil tenantUtil;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping(value = "/main")
    public Object welcome() {

        // 初始化netty服务器, 设备登录在 应用设置--其他设置--通信设置 填入服务器 ip:port
        isPerfMachineService.welcome();
        return ActionResult.success("netty绑定成功");
    }

    @PostMapping(value = "/callback")
    @NoDataSourceBind
    public Object callback(@RequestBody Map<String, Object> params) {

        log.error("callback init ...");
        /*String userNo = params.get("userId").toString();
        log.info("callback in : {}", params.toString());
        JSONObject json = new JSONObject(params.get("extra"));
        String tenantId = json.get("tenantId").toString();
        String userId = json.get("userId").toString();
        tenantUtil.checkOutTenant(tenantId, userId);
        String sn = params.get("mac").toString();
        String b = attenceMachineService.clockIn(sn, userId, tenantId);
        // log.error(b);
        json.clear();
        // 将结果保存到redis 0: 打卡失败, 1: 正常, 2: 迟到, 3: 早退
        redisUtil.insert(ConstantUtil.MACHINE_KEY + sn + "-" + userNo, "locked", 5L);*/
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("flag", 1);
        map.put("tips", "");
        return map;
    }

    /**
     * 开架易 - 二次校验
     * @param params 二次校验dto
     * @return java.lang.Object
     */
    @PostMapping(value = "/kips/secondCheck")
    @NoDataSourceBind
    @Machine(dealAction = ActionEnum.DA_KA, factory = MachineEnum.KAI_JIA_YI)
    public Object getClockInResult(@RequestBody Map<String, Object> params) {

        int code = 0;
        int flag = 0;
        log.error("callback in : {}", params.toString());
        Map<String, Object> map = new HashMap<>();
        // 解析入参
        String userNo = params.get("vipID").toString();
        JSONObject json = new JSONObject(params.get("extra"));
        String tenantId = json.get("tenantId").toString();
        String userId = json.get("userId").toString();
        String sn = params.get("mac").toString();
        // 防止重复提交, 查看redis是否还在限制打卡
        String key = ConstantUtil.MACHINE_KEY + sn + "-" + userNo;
        if (redisUtil.exists(key)) {
            map.put("code", code);
            map.put("flag", flag);
            map.put("tips", "");
            return map;
        }
        tenantUtil.checkOutTenant(tenantId, userId);
        String b = attenceMachineService.clockIn(sn, userId, tenantId);
        json.clear();
        // 防重复提交
        redisUtil.insert(key, "locked", 5L);
        String tips = "";
        switch (b) {
            case "0":
                tips =  "打卡失败";
                break;
            case "1":
                tips =  "打卡成功";
                break;
            case "2":
                tips =  "迟到";
                break;
            case "3":
                tips =  "早退";
                break;
            default:
                tips =  b;
                break;
        }
        map.put("code", code);
        map.put("flag", flag);
        map.put("tips", tips);
        return map;
    }

    /**
     * 版本升级
     * @param params 参数
     */
    @PostMapping(value = "/updateApp")
    public void updateApp(@RequestBody Map<String, Object> params) {

        isPerfMachineService.updateApp(params);
    }

    /**
     * 查看netty所有考勤机在线用户
     * @return java.lang.Object
     */
    @GetMapping(value = "/allOnlineClient")
    public Object getAllOnlineClient() {

        List<String> list = isPerfMachineService.getAllOnlineClient();
        return ActionResult.success(list);
    }

    @GetMapping("/kyj/sendMqtt/{type}")
    @NoDataSourceBind
    public String kyjSendMqtt(@PathVariable(value = "type") Integer type) {

        tenantUtil.checkOutTenant("ftb_dev");
        MachineEnum machineEnum = MachineEnum.getMachineEnum(MachineEnum.KAI_JIA_YI.getValue());
        MachineStrategy machineStrategy = machineStrategyFactory.getMachineStrategy(machineEnum);
        UserInfo userInfo = new UserInfo();
        userInfo.setTenantId("ftb_dev");
        PartUserInfoVo user = new PartUserInfoVo();
        user.setRealName("小鄢");
        user.setUserId("471608060058616325");
        user.setUserNo(123);
        user.setGender(1);
        String sn  = "B48F62EEAC7D";
        if (type == 1) {
            machineStrategy.addUserToMachine(userInfo, user, sn);
        } else {
            machineStrategy.deleteUserList(userInfo, Stream.of(user.getUserNo().toString()).collect(Collectors.toList()), sn);
        }
        return "发送结束";
    }
}
