package com.xueyi.system.digitalmans.controller;

import com.alibaba.fastjson.JSONObject;
import com.xueyi.common.cache.utils.SourceUtil;
import com.xueyi.common.core.constant.basic.SecurityConstants;
import com.xueyi.common.core.constant.digitalman.InitConstants;
import com.xueyi.common.core.constant.digitalman.MessageConstants;
import com.xueyi.common.core.utils.core.IdUtil;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.core.web.validate.V_A;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.mqtt.connection.MqttTemplate;
import com.xueyi.common.security.annotation.Logical;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.sms.configure.SmsProperties;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.message.api.transfer.domain.vo.DmActiveVo;
import com.xueyi.message.api.transfer.feign.RemoteTransferService;
import com.xueyi.system.api.device.domain.dto.DmDeviceTenantMergeDto;
import com.xueyi.system.api.digitalmans.domain.dto.DmManDeviceDto;
import com.xueyi.system.api.digitalmans.domain.vo.NumberOfOnlineToChartVo;
import com.xueyi.system.api.digitalmans.feign.RemoteDigitalmanService;
import com.xueyi.system.api.model.Source;
import com.xueyi.system.api.organize.domain.dto.SysEnterpriseDto;
import com.xueyi.system.api.sms.domain.vo.DingdingReqEntity;
import com.xueyi.system.api.sms.feign.RemoteDingdingService;
import com.xueyi.system.api.sms.feign.RemoteSmsService;
import com.xueyi.system.device.service.IDmDeviceTenantMergeService;
import com.xueyi.system.dict.service.ISysDictDataService;
import com.xueyi.system.digitalmans.domain.query.DmManDeviceQuery;
import com.xueyi.system.digitalmans.service.IDmDigitalmanExtService;
import com.xueyi.system.digitalmans.service.IDmDigitalmanService;
import com.xueyi.system.digitalmans.service.IDmManDeviceService;
import com.xueyi.system.emcs.domain.dto.DmExceptionLogDto;
import com.xueyi.system.emcs.domain.query.DmExceptionLogQuery;
import com.xueyi.system.emcs.service.IDmExceptionLogService;
import com.xueyi.system.organize.service.ISysEnterpriseService;
import com.xueyi.system.pass.mapper.DmRecognizedRecordsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.xueyi.common.core.constant.digitalman.InitConstants.DEVICE_ACTIVATE_STATUS_OFFLINE;
import static com.xueyi.common.core.constant.digitalman.RedisDefinitionConstants.GENERAL_CURRENT_NUMBER_OF_ONLINE;

/**
 * 数字人设备管理管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/manDevice")
public class DmManDeviceController extends BaseController<DmManDeviceQuery, DmManDeviceDto, IDmManDeviceService> {

    private static final Logger log = LoggerFactory.getLogger(DmManDeviceController.class);
    @Autowired
    IDmDigitalmanService digitalmanService;

    @Autowired
    IDmDigitalmanExtService digitalmanExtService;

    @Autowired
    RemoteDigitalmanService remoteDigitalmanService;

    @Autowired
    IDmDeviceTenantMergeService deviceTenantMergeService;

    @Autowired
    ISysEnterpriseService enterpriseService;

    @Autowired
    ISysDictDataService sysDictDataService;

    @Autowired
    RemoteTransferService remoteTransferService;

    @Autowired
    RedisTemplate<String,Serializable> redisTemplate;

    @Autowired
    MqttTemplate mqttTemplate;
    @Autowired
    IDmExceptionLogService dmExceptionLogService;

    @Autowired
    RemoteSmsService remoteSmsService;

    @Autowired
    SmsProperties smsProperties;

    @Autowired
    RemoteDingdingService remoteDingdingService;


    /**
     * dingding连接token
     */
    @Value("${notification.dingding.access-token}")
    private String token;



    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "数字人设备管理" ;
    }



    /** 根据设备id获取数字人信息 */
    @GetMapping("/inner/info/{devId}")
    R<DmManDeviceDto> manDeviceInfoInner(@RequestParam(value = "devId") String devId) {
        System.out.println("manDeviceInfoInner:" + devId);
        DmManDeviceDto dto = super.baseService.manDeviceInfoInner(devId);
        System.out.println("manDeviceInfoInner:dto:" + dto.getTId());
        SysEnterpriseDto enterpriseDto = enterpriseService.selectById(dto.getTId());
        dto.setStrategyId(enterpriseDto.getStrategyId());
        return R.ok(dto);
    }

    @PostMapping(value = "/inner/sync")
    R<Integer> manDeviceListInnerSync(@RequestParam(value = "tenantId") Long tenantId) {
        log.info("同步设备信息开始：{}",tenantId);
        DmManDeviceQuery query = new DmManDeviceQuery();
        query.setTId(tenantId);
        //根据租户id获取设备列表
        List<DmManDeviceDto> list = super.baseService.manDeviceListNotNullByTenantId(tenantId);
        SysEnterpriseDto dto = enterpriseService.selectById(tenantId);
        Source source = SourceUtil.getSourceCache(dto.getStrategyId());
        // 同步总体设备信息
        list.stream().filter(item->!item.getOnlineStatus().equalsIgnoreCase("0")).forEach(item->{
            log.info("同步设备信息：{}",item);
            DmManDeviceDto tempDto = (DmManDeviceDto) redisTemplate.opsForHash().get(MessageConstants.REDIS_GROUP_DEVICE_HEADER,item.getDeviceId());
            if (!item.getOnlineStatus().equalsIgnoreCase(tempDto.getOnlineStatus())) {
                item.setOnlineStatus(tempDto.getOnlineStatus());
                super.baseService.update(item);
            }
            if (tempDto.getOnlineStatus().equalsIgnoreCase(DEVICE_ACTIVATE_STATUS_OFFLINE)) {
                // query if the device is in the exception log
                DmExceptionLogQuery logQuery = new DmExceptionLogQuery();
                logQuery.setDevId(tempDto.getDeviceId());
                logQuery.setTId(tenantId);
                logQuery.setAlertStatus(0);
                logQuery.setType("heartbeat_status");
                List<DmExceptionLogDto> logDtos = dmExceptionLogService.selectList(logQuery);
                // if logDtos is not empty, then add a record to the exception log
                if (logDtos != null && logDtos.size() == 0)  {
                    DmExceptionLogDto logDto = new DmExceptionLogDto();
                    logDto.setDevId(item.getDeviceId());
                    logDto.setTId(tenantId);
                    logDto.setAlertStatus(0);
                    logDto.setManCode(item.getManCode());
                    logDto.setLevel(3);
                    logDto.setType("heartbeat_status");
                    logDto.setOccurTime(LocalDateTime.now());
                    dmExceptionLogService.insert(logDto);
                    DingdingReqEntity entity = new DingdingReqEntity();
                    entity.setMsgtype("text");
                    JSONObject jo = new JSONObject();
                    jo.put("content", "【一级预警】客户" + item.getTenantName() + "，设备" + item.getDeviceId() + "离线,请尽快排查原因，并在运维端解除预警状态。");
                    entity.setText(jo);
                    JSONObject dingdingResult = remoteDingdingService.send(token,entity);
                    log.info("dingdingResult:{}",dingdingResult);
                }
            }
        });
        return remoteDigitalmanService.syncExtIsonline(list,tenantId,source.getMaster(), SecurityConstants.INNER);
    }

    @PutMapping(value = "/inner/info")
    R<Integer> manDeviceInfoInnerUpdate(@RequestBody DmActiveVo vo) {
        return R.ok(super.baseService.manDeviceInfoInnerUpdate(vo));
    }
    @PostMapping(value = "/inner/sync_numbers_of_online")
    R<Integer> syncNumbersOfOnline() {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd");
        List<Object> manDeviceDtos = (List<Object>)redisTemplate.opsForHash().values(MessageConstants.REDIS_GROUP_DEVICE_HEADER);
        Long total = manDeviceDtos.stream().filter(item->(!((DmManDeviceDto)item).getOnlineStatus().isEmpty()) &&
                ((DmManDeviceDto)item).getOnlineStatus().equalsIgnoreCase("1")).count();
        NumberOfOnlineToChartVo vo = new NumberOfOnlineToChartVo();
        vo.setNumberOfOnline(total.toString());
        vo.setDate(currentDate.format(formatter));
        vo.setTotal(manDeviceDtos.size());
        // 获取当前日期并将数据同步到redis
        redisTemplate.opsForList().leftPush(GENERAL_CURRENT_NUMBER_OF_ONLINE,vo);
        if (redisTemplate.opsForList().size(GENERAL_CURRENT_NUMBER_OF_ONLINE) > 150) {
            redisTemplate.opsForList().rightPop(GENERAL_CURRENT_NUMBER_OF_ONLINE,1, TimeUnit.MINUTES);
        }

        return R.ok(Integer.parseInt(vo.getNumberOfOnline()));
    }
    /**
     * 查询数字人设备管理列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_MAN_DEVICE_LIST)
    public AjaxResult list(DmManDeviceQuery dmManDevice) {

        return super.list(dmManDevice);
    }

    /**
     * 查询数字人设备管理详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_MAN_DEVICE_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }

    /**
     * 数字人设备管理新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_MAN_DEVICE_ADD)
    @Log(title = "数字人设备管理管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmManDeviceDto dmManDevice) {
        System.out.println("DmManDeviceController：add： " + dmManDevice.toString());
        System.out.println("DmManDeviceController：add： " + dmManDevice.getTenantId());
        String manCode =IdUtil.simpleUUID().substring(0,8);
        dmManDevice.setManCode(manCode);
        dmManDevice.setTId(dmManDevice.getTenantId());
        dmManDevice.setOnlineStatus(InitConstants.DEVICE_ACTIVATE_STATUS_NOT_ACTIVATE);
        dmManDevice.setDelFlag(0L);
        super.add(dmManDevice);
        //创建设备映射表
        DmDeviceTenantMergeDto dmDeviceTenantMergeDto = new DmDeviceTenantMergeDto();
        dmDeviceTenantMergeDto.setTenantId(dmManDevice.getTenantId());
        dmDeviceTenantMergeDto.setDevSn(manCode);
        deviceTenantMergeService.insert(dmDeviceTenantMergeDto);
        SysEnterpriseDto dto = enterpriseService.selectById(dmManDevice.getTenantId());
        Source source = SourceUtil.getSourceCache(dto.getStrategyId());
        // 获取随机数字人id
        remoteDigitalmanService.initInner(manCode,dmManDevice.getTenantId(),source.getMaster(), SecurityConstants.INNER);
        //digitalmanService.initDigitalman(manCode);
        return AjaxResult.success();
    }

    /**
     * 数字人设备管理修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_MAN_DEVICE_EDIT)
    @Log(title = "数字人设备管理管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmManDeviceDto dmManDevice) {
        return super.edit(dmManDevice);
    }

    /**
     * 数字人设备管理修改状态
     */
    @Override
    @PutMapping("/status")
    @RequiresPermissions(value = {Auth.DM_MAN_DEVICE_EDIT, Auth.DM_MAN_DEVICE_ES}, logical = Logical.OR)
    @Log(title = "数字人设备管理管理", businessType = BusinessType.UPDATE_STATUS)
    public AjaxResult editStatus(@RequestBody DmManDeviceDto dmManDevice) {
        return super.editStatus(dmManDevice);
    }

    /**
     * 数字人设备管理批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_MAN_DEVICE_DEL)
    @Log(title = "数字人设备管理管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }


    @GetMapping("/dashboard_data")
    @RequiresPermissions(Auth.DM_MAN_DEVICE_LIST)
    public AjaxResult dashboardData() {
        return AjaxResult.success(super.baseService.dashboardData());
    }

    @GetMapping("/online_devices_to_chart")
    @RequiresPermissions(Auth.DM_MAN_DEVICE_LIST)
    public AjaxResult onlineDevicesToChart() {
        Long total = redisTemplate.opsForList().size(GENERAL_CURRENT_NUMBER_OF_ONLINE);
        if (total == null) {
            total = new Long(0);
        }
        // 从缓存中获取在线信息
        List devices = (List) redisTemplate.opsForList().range(GENERAL_CURRENT_NUMBER_OF_ONLINE, 0, total.longValue());

        if (devices == null) {
            devices = new ArrayList();
        }
        // 获取最近五周的数据
        List<NumberOfOnlineToChartVo> charList = new ArrayList<>();
        int count = 0;
        for (int i = 0; i < devices.size() && i < 35; i++) {
            if (++count % 7 == 0) {
                charList.add((NumberOfOnlineToChartVo) devices.get(i));
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("near5Weeks", charList);
        // 获取最近五个月的数据
        count = 0;
        charList = new ArrayList<>();
        for (int i = 0; i < devices.size(); i++) {
            if (++count % 30 == 0) {
                charList.add((NumberOfOnlineToChartVo) devices.get(i));
            }
        }
        jsonObject.put("near5Months", charList);
        return AjaxResult.success(jsonObject);
    }

    // 软件重启接口，Http为Post请求，用于通过Mqtt向指定设备号发送重启指令，mqtt的Topic为：/digitalman/{devId}/restart,devId为设备号
    @PostMapping("/restart/{type}/{devId}")
    public AjaxResult restart(@PathVariable("type") Integer type,@PathVariable("devId") String devId) {


        return AjaxResult.success(baseService.restartDevice(type,devId));
    }


    @Autowired
    private DmRecognizedRecordsMapper mapper;
    @GetMapping("/delRecognizedRecords")
    public AjaxResult delRecognizedRecords (@RequestParam(value = "day") Integer day){
        mapper.del(day);
        return AjaxResult.success();
    }
    /**
     * 获取数字人设备管理选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }

    interface Auth {
        /** 系统 - 数字人设备管理管理 - 列表 */
        String DM_MAN_DEVICE_LIST = "digitalmans:manDevice:list";
        /** 系统 - 数字人设备管理管理 - 详情 */
        String DM_MAN_DEVICE_SINGLE = "digitalmans:manDevice:single";
        /** 系统 - 数字人设备管理管理 - 新增 */
        String DM_MAN_DEVICE_ADD = "digitalmans:manDevice:add";
        /** 系统 - 数字人设备管理管理 - 修改 */
        String DM_MAN_DEVICE_EDIT = "digitalmans:manDevice:edit";
        /** 系统 - 数字人设备管理管理 - 修改状态 */
        String DM_MAN_DEVICE_ES = "digitalmans:manDevice:es";
        /** 系统 - 数字人设备管理管理 - 删除 */
        String DM_MAN_DEVICE_DEL = "digitalmans:manDevice:delete";
    }

}
