package com.izouma.wenlvju.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.izouma.wenlvju.domain.ExamRoom;
import com.izouma.wenlvju.domain.Record;
import com.izouma.wenlvju.dto.ExamRoomDTO;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.ExamRoomRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class ExamRoomService {

    private final ExamRoomRepo      examRoomRepo;
    private final EzvizTokenService ezvizTokenService;
    private final RecordService     recordService;

    public Page<ExamRoom> all(PageQuery pageQuery) {
        return examRoomRepo.findAll(JpaUtils.toSpecification(pageQuery, ExamRoom.class), JpaUtils.toPageRequest(pageQuery));
    }

    /*
    查看设备列表
     */
    public Map<String, Integer> showDevice() {
        String uri = "https://open.ys7.com/api/lapp/device/list";
        String accessToken = ezvizTokenService.getToken();
        String send = "accessToken=" + accessToken + "&pageStart=0&pageSize=50";
        log.info("萤石查看设备--->" + send);

        String body = HttpRequest.post(uri).send(send).body();
        log.info("萤石查看设备返回--->" + body);

        JSONObject json = JSONObject.parseObject(body);
        if (!"200".equals(json.getString("code"))) {
            throw new BusinessException(json.getString("msg"));
        }

        JSONArray data = JSONObject.parseArray(json.getString("data"));
        Map<String, Integer> devices = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = data.getJSONObject(i);
            String name = jsonObject.getString("deviceSerial");
            int status = jsonObject.getInteger("status");
            devices.put(name, status);
        }
        return devices;
    }

    /*
    添加设备
     */
    public void addDevice(String deviceSerial, String validateCode) {
        Set<String> devices = this.showDevice().keySet();
        if (devices.contains(deviceSerial)) {
            return;
        }

        String uri = "https://open.ys7.com/api/lapp/device/add";
        String accessToken = ezvizTokenService.getToken();
        String send = "accessToken=" + accessToken + "&deviceSerial=" + deviceSerial + "&validateCode=" + validateCode;
        log.info("萤石添加设备--->" + send);

        String body = HttpRequest.post(uri).send(send).body();
        log.info("萤石添加设备返回--->" + body);

        JSONObject json = JSONObject.parseObject(body);
        if (!"200".equals(json.getString("code"))) {
            throw new BusinessException(json.getString("msg"));
        }
    }

    /*
    删除设备
     */
    public void delDevice(String deviceSerial) {
        String uri = "https://open.ys7.com/api/lapp/device/delete";

        String accessToken = ezvizTokenService.getToken();

        String send = "accessToken=" + accessToken + "&deviceSerial=" + deviceSerial;
        log.info("萤石删除设备--->" + send);

        String body = HttpRequest.post(uri).send(send).body();
        log.info("萤石删除设备返回--->" + body);

        JSONObject json = JSONObject.parseObject(body);
        if (!"200".equals(json.getString("code"))) {
            throw new BusinessException(json.getString("msg"));
        }
    }

    /*
    开启设备加密
     */
    public void encryptOn(String deviceSerial) {
        String uri = "https://open.ys7.com/api/lapp/device/encrypt/on";

        String accessToken = ezvizTokenService.getToken();

        String send = "accessToken=" + accessToken + "&deviceSerial=" + deviceSerial;
        log.info("萤石开启设备加密--->" + send);

        String body = HttpRequest.post(uri).send(send).body();
        log.info("萤石开启设备加密返回--->" + body);

        JSONObject json = JSONObject.parseObject(body);
        if (!"200".equals(json.getString("code"))) {
            throw new BusinessException(json.getString("msg"));
        }
    }


    /*
    关闭设备加密
     */
    public void encryptOff(String deviceSerial, String validateCode) {

        String uri = "https://open.ys7.com/api/lapp/device/encrypt/off";
        String accessToken = ezvizTokenService.getToken();
        String send = "accessToken=" + accessToken + "&deviceSerial=" + deviceSerial + "&validateCode=" + validateCode;
        log.info("萤石关闭设备加密--->" + send);

        String body = HttpRequest.post(uri).send(send).body();
        log.info("萤石关闭设备加密返回--->" + body);

        JSONObject json = JSONObject.parseObject(body);
        if (!"200".equals(json.getString("code"))) {
            throw new BusinessException(json.getString("msg"));
        }
    }

    /*
    展示今天备案中的所有考场信息
     */
    public List<ExamRoomDTO> byToday(PageQuery pageQuery, Integer status) {

        List<Record> all = recordService.all2(pageQuery).getContent();
        Map<Long, Record> recordMap = all.stream().collect(Collectors.toMap(Record::getId, record -> record));

        List<Long> rids = all.stream().map(Record::getId).collect(Collectors.toList());
        if (CollUtil.isEmpty(rids)) {
            return null;
        }

        List<ExamRoom> examRooms = examRoomRepo.findAllByRecordIdIn(rids);
        if (ObjectUtil.isNotEmpty(status)) {
            Map<String, Integer> device = this.showDevice();
            return examRooms.stream()
                    .filter(examRoom -> status.equals(device.get(examRoom.getDeviceSerial())))
                    .map(examRoom -> new ExamRoomDTO(examRoom, recordMap.get(examRoom.getRecordId())))
                    .collect(Collectors.toList());
        }
        return examRooms.stream()
                .map(examRoom -> new ExamRoomDTO(examRoom, recordMap.get(examRoom.getRecordId())))
                .collect(Collectors.toList());
    }
}
