import json

import redis
import requests

from datacenter import settings
from smartdevice.models import Device

CILENT_ID = "7aab6665696b4027879a55332f001b8f"
CILENT_SECRET = "3a86ce7109734c7480f1d293e5dc01fe"

class HikTools():
    def __init__(self):
        super().__init__()

    # 智慧门店 获取hik校验token
    def get_hik_stoken(self):
        access_token = ""
        rd = redis.StrictRedis(connection_pool=settings.HIk_TOKEN_POOL)
        access_token = rd.get("hik_token")
        if access_token:
            access_token = json.loads(access_token)
            return access_token
        else:

            hik_url = "https://api2.hik-cloud.com/oauth/token"
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            data= {
                    "client_id":CILENT_ID,
                    "client_secret":CILENT_SECRET,
                    "grant_type":"client_credentials",
                    "scope":"all"
            }
            res = requests.post(hik_url, headers=headers,data=data)
            if res.status_code == 200:
                res = res.json()
                rd = redis.StrictRedis(connection_pool=settings.HIk_TOKEN_POOL)
                rd.setex("hik_token",res['expires_in']-100,json.dumps(res))
            else:
                res = ""
            return  res;


    # 根据设备序列号查看设备通道
    def getChannels(self,deviceSerial):
        access_token = self.get_hik_stoken()
        if access_token:
            video_url = "https://api2.hik-cloud.com/v1/customization/devices/channels/actions/listByDevSerial?deviceSerial=" + deviceSerial
            headers = {"Authorization":"bearer "+access_token['access_token']}

            res = requests.get(video_url, headers=headers)
            if res.status_code == 200:
                res = res.json()
            else:
                res = ""
            return res;
        else:
            return {"e":"获取token校验错误"}


    # 根据通道 开启或者关闭标准视频流
    def act_liveVideo(self,deviceSerial,what=None):

        access_token = self.get_hik_stoken()

        if access_token:
            video_url=""
            headers = {'Content-Type': 'application/x-www-form-urlencoded',"Authorization":"Bearer "+access_token['access_token']}
            if what == 'open':
                video_url = "https://api2.hik-cloud.com/v1/customization/liveVideoOpen"
            elif what == 'close':
                video_url = "https://api2.hik-cloud.com/v1/customization/liveVideoClose"
            else:
                pass
            channels = self.getChannels(deviceSerial)
            if channels and 'data' in channels:
                channelId = channels['data'][0]['channelId']
                data = {
                    "channelIds": channelId,
                }
                res = requests.post(video_url, headers=headers, data=data)
                if res.status_code == 200:
                    return res.json()
                else:
                    return {'code': 5200,"message": "操作失败"}
            else:
                return {'code': 5200,"message": "暂未获取通道"}

        else:
            return {'code': 5200,"message":"获取token校验错误"}
