package com.ruoyi.web.controller.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.framework.websocket.WebSocketServer;
import com.ruoyi.framework.websocket.WebsocketConst;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zhdd.domain.GatewayDept;
import com.ruoyi.zhdd.domain.SingleDevice;
import com.ruoyi.zhdd.domain.bo.SingleDeviceBo;
import com.ruoyi.zhdd.service.ISingleDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SysGatewayUserTask {

    @Autowired
    ISysUserService userService;

    @Autowired
    ISysDeptService deptService;

    @Autowired
    private ISingleDeviceService singleDeviceService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @Autowired
    private WebSocketServer webSocketServer;

    /*@KafkaListener(topics = "t_uc_user")
    public void onUserMessage(String message) {
        log.info("kafka用户信息消费：{}", message);
        try {
            GatewaySUser gatewaySUser = JSONUtil.toBean(message, GatewaySUser.class);
            if (gatewaySUser != null) {
                SysUser quser = new SysUser();
                quser.setUserId(gatewaySUser.getUserId());
                List<SysUser> userList = userService.selectUserList(quser);
                if (userList.isEmpty()) {
                    //插入
                    SysUser user = new SysUser();
                    user.setUserId(gatewaySUser.getUserId());
                    *//*{
                        SysDept qdept = new SysDept();
                        qdept.setOtherId(gatewaySUser.getDeptId());
                        List<SysDept> deptList = deptService.selectDeptList(qdept);
                        if (!deptList.isEmpty()) {
                            user.setDeptId(deptList.get(0).getDeptId());
                        } else {
                            //还未有部门暂不设置  //需要先同步部门
                        }
                    }*//*
                    user.setPhonenumber(gatewaySUser.getMobile());
                    user.setNickName(gatewaySUser.getName());
                    user.setUserName(gatewaySUser.getUserName());
                    user.setDeptId(gatewaySUser.getDeptId());
                    user.setUserType(Convert.toStr(gatewaySUser.getUserGroupId()));
                    user.setUpdateBy("kafka");
                    user.setUpdateTime(new Date());
                    user.setCreateBy("kafka");
                    user.setCreateTime(new Date());
                    user.setSex(gatewaySUser.getSex());
                    user.setOrgId(gatewaySUser.getOrgId());
                    user.setSuperior(gatewaySUser.getSuperior());
                    user.setIdNumber(gatewaySUser.getIdNumber());
                    user.setPassword(SecurityUtils.encryptPassword("tocc!suqian"));
                    user.setStatus(gatewaySUser.getStatus());
                    user.setDelFlag(gatewaySUser.getDelFlag());
                    userService.insertUser(user);
                } else {
                    //更新
                    SysUser user = userList.get(0);
                    *//*{
                        SysDept qdept = new SysDept();
                        qdept.setOtherId(gatewaySUser.getDeptId());
                        List<SysDept> deptList = deptService.selectDeptList(qdept);
                        if (!deptList.isEmpty()) {
                            user.setDeptId(deptList.get(0).getDeptId());
                        } else {
                            //还未有部门暂不设置  //需要先同步部门

                        }
                    }*//*
                    user.setPhonenumber(gatewaySUser.getMobile());
                    user.setNickName(gatewaySUser.getName());
                    user.setUserName(gatewaySUser.getUserName());
                    user.setDeptId(gatewaySUser.getDeptId());
                    user.setUserType(Convert.toStr(gatewaySUser.getUserGroupId()));
                    user.setUpdateBy("kafka");
                    user.setUpdateTime(new Date());
                    user.setSex(gatewaySUser.getSex());
                    user.setOrgId(gatewaySUser.getOrgId());
                    user.setSuperior(gatewaySUser.getSuperior());
                    user.setIdNumber(gatewaySUser.getIdNumber());
                    user.setPassword(SecurityUtils.encryptPassword("tocc!suqian"));
                    user.setStatus(gatewaySUser.getStatus());
                    user.setDelFlag(gatewaySUser.getDelFlag());
                    user.setUpdateBy("kafka");
                    user.setUpdateTime(new Date());
                    userService.updateUser(user);
                }
            }
        } catch (Exception e) {
            log.error("t_uc_use的kafka消费异常：{}", e.getMessage());
        }
    }*/

    /**
     * 四维组织部门数据消费
     * {"id":"f124bfe4b43c49c5b7451b11355cc499","name":"市运输服务中心","parentId":null,"parentName":null,"flag":0,"createTime":"2021-10-21 14:02:28","createUser":"admin","updateTime":"2021-10-21 14:02:28","updateUser":"admin","delFlag":"0"}
     *
     * @param message
     */
    @KafkaListener(topics = "t_uc_orgdept")
    public void onDeptMessage(String message) {
        log.info("kafka部门信息消费：{}", message);
        try {
            GatewayDept gatewayDept = JSONUtil.toBean(message, GatewayDept.class);
            if (gatewayDept != null) {
                SysDept qdept = new SysDept();
                qdept.setDeptId(gatewayDept.getId());
                List<SysDept> deptList = deptService.selectDeptList(qdept);
                if (deptList.isEmpty()) {
                    //插入
                    SysDept dept = new SysDept();
                    /*//查询父部门
                    {
                        SysDept qdept1 = new SysDept();
                        if (gatewayDept.getParentId() == null || gatewayDept.getParentId().equals("")) {
                            qdept1.setParentId("0");
                            qdept1.setOtherId(gatewayDept.getOrgId());
                        } else {
                            qdept1.setOtherId(gatewayDept.getParentId());
                        }
                        List<SysDept> deptList1 = deptService.selectDeptList(qdept1);
                        if (!deptList1.isEmpty()) {
                            dept.setParentId(deptList1.get(0).getDeptId());
                        } else {
                            //无父组织或部门 暂不处理吧
                        }
                    }*/
                    qdept.setParentId(StrUtil.emptyToDefault(gatewayDept.getParentId(), "0"));
                    qdept.setDeptName(gatewayDept.getName());
                    qdept.setUpdateBy(gatewayDept.getUpdateUser());
                    qdept.setUpdateTime(DateUtil.parseDateTime(gatewayDept.getUpdateTime()));
                    qdept.setCreateBy(gatewayDept.getCreateUser());
                    qdept.setCreateTime(DateUtil.parseDateTime(gatewayDept.getCreateTime()));
                    qdept.setDelFlag(gatewayDept.getDelFlag());
                    qdept.setFlag(gatewayDept.getFlag());
                    deptService.insertDept(qdept);
                } else {
                    //更新
                    qdept = deptList.get(0);
                    //查询父部门
                    /*{
                        SysDept qdept1 = new SysDept();
                        if (gatewayDept.getParentId() == null || gatewayDept.getParentId().equals("")) {
                            qdept1.setParentId("0");
                            qdept1.setOtherId(gatewayDept.getOrgId());
                        } else {
                            qdept1.setOtherId(gatewayDept.getParentId());
                        }
                        List<SysDept> deptList1 = deptService.selectDeptList(qdept1);
                        if (!deptList1.isEmpty()) {
                            dept.setParentId(deptList1.get(0).getDeptId());
                        } else {
                            //无父组织或部门 暂不处理吧
                        }
                    }*/
                    qdept.setParentId(StrUtil.emptyToDefault(gatewayDept.getParentId(), "0"));
                    qdept.setDeptName(gatewayDept.getName());
                    qdept.setUpdateBy(gatewayDept.getUpdateUser());
                    qdept.setUpdateTime(DateUtil.parseDateTime(gatewayDept.getUpdateTime()));
                    qdept.setCreateBy(gatewayDept.getCreateUser());
                    qdept.setCreateTime(DateUtil.parseDateTime(gatewayDept.getCreateTime()));
                    qdept.setDelFlag(gatewayDept.getDelFlag());
                    qdept.setFlag(gatewayDept.getFlag());
                    deptService.updateDept(qdept);
                }
            }
        } catch (Exception e) {
            log.error("t_uc_orgdept的kafka消费异常：{}", e.getMessage());
        }
    }

    /**
     * 单兵实时位置消费
     *
     * @param message
     */
    @KafkaListener(topics = "gps_executestation_581a2b5cb28e429bb56a3c6b8cbdf5a6")
    public void onDeviceMessage(String message) {
        log.info("kafka单兵设备信息消费：{}", message);
        JSONObject jsonObject = JSONUtil.parseObj(message);
        JSONObject info = jsonObject.getJSONObject("info");
        if (info != null) {
            JSONArray gps = info.getJSONArray("gps");
            if (gps != null && !gps.isEmpty()) {
                for (Object gp : gps) {
                    SingleDeviceBo singleDeviceBo = JSONUtil.toBean(Convert.toStr(gp), SingleDeviceBo.class);
                    // 根据deviceCod删除再新增
                    singleDeviceService.remove(Wrappers.<SingleDevice>lambdaQuery().eq(SingleDevice::getDeviceCode, singleDeviceBo.getDeviceCode()));
                    String utcTime = singleDeviceBo.getTime();
                    if (StrUtil.isNotBlank(utcTime)) {
                        String concat = StrUtil.concat(true, utcTime.substring(0, 4), "-", utcTime.substring(4, 6), "-", utcTime.substring(6, 11), ":", utcTime.substring(11, 13), ":", utcTime.substring(13));
                        singleDeviceBo.setTime(DateUtil.formatDateTime(DateUtil.parseUTC(concat)));
                    }
                    singleDeviceService.insertByBo(singleDeviceBo);
                }
            }
        }
    }

    /**
     * 语音指令
     *
     * @param message
     */
    @KafkaListener(topics = "voice-vcg")
    public void onVoiceMessage(String message) {
        log.info("kafka语音指令消费：{}", message);
        JSONObject jsonObject = JSONUtil.parseObj(message);
        String id = jsonObject.getStr("id");
        String wordValue = jsonObject.getStr("wordValue");
        List<SysDictData> zhdd_voice = sysDictTypeService.selectDictDataByType("zhdd_voice");
        for (SysDictData sysDictData : zhdd_voice) {
            if (sysDictData.getDictLabel().contains(wordValue)) {
                JSONObject obj = new JSONObject();
                obj.set(WebsocketConst.MSG_CMD, sysDictData.getDictValue());
                obj.set(WebsocketConst.MSG_ID, id);
                obj.set(WebsocketConst.MSG_TXT, wordValue);
                webSocketServer.sendAllMessage(obj.toString());
                break;
            }
        }
    }

}
