from django.utils.timezone import template_localtime
from twisted.mail.alias import handle

from dspt_api.util.general.handle_redis import get_data_from_redis
import time


class ApiSeatUnlock:
    def __init__(self, **kwargs):
        self.member_type = kwargs.get('member_type')
        self.api = kwargs.get('api')
        self.ip = kwargs.get('ip')
        self.env = kwargs.get('env')
        self.cid = kwargs.get('cid')
        self.pid = kwargs.get('pid')
        self.return_data = []

    def get_suggestion(self):
        self.handle()
        return self.return_data

    def get_timestamp(self):
        self.handle()
        temp_timestamp = 0
        for data in self.return_data:
            temp_timestamp = data['timestamp'] if data['timestamp'] > 0 else temp_timestamp
        return temp_timestamp

    def handle(self):
        redis_key_prefix = f'dspt_api_{self.ip}_{self.env}_{self.member_type}_{self.pid}_{self.cid}'
        # 获取 play_id
        request_api_play = {'name': '3.1.5 获取放映计划列表', 'path': 'cinema/plays'}
        redis_key_api_play = f'{redis_key_prefix}_{request_api_play["path"]}'
        result_play, _format_play, data_play, _timestamp_play = get_data_from_redis(redis_key_api_play)
        if not result_play:
            self.add_param('play_id', '请手动输入参数,或先请求接口:3.1.5 获取放映计划列表')
        else:
            self.add_param('play_id', data_play['id'], timestamp=_timestamp_play)

        # 获取 seat_id
        request_api_seat = {'name': '3.1.8 获取某场次座位状态', 'path': 'play/seat-status'}
        redis_key_api_seat = f'{redis_key_prefix}_{request_api_seat["path"]}'
        result_seat, _format_seat, data_seat, _timestamp_seat = get_data_from_redis(redis_key_api_seat)
        if not result_seat:
            self.add_param('seat_id', '请手动输入参数,或先请求接口:3.1.8 获取某场次座位状态')
        else:
            seat_id = ','.join([seat['cineSeatId'] for seat in data_seat])
            self.add_param('seat_id', seat_id, timestamp=_timestamp_seat)

        # 获取 lock_flag
        request_api_lock = {'name': '3.3.1 座位锁定', 'path': 'seat/lock'}
        redis_key_api_lock = f'{redis_key_prefix}_{request_api_lock["path"]}'
        result_lock, _format_lock, data_lock, _timestamp_lock = get_data_from_redis(redis_key_api_lock)
        if not result_lock:
            self.add_param('lock_flag', '请手动输入参数,或先请求接口:3.3.1 座位锁定')
        else:
            self.add_param('lock_flag', data_lock['lockFlag'], timestamp=_timestamp_lock)

    def add_param(self, field, value, is_checked=True, result=True, timestamp=int(time.time() * 1000)):
        self.return_data.append(
            {'param': field, 'value': value, 'is_checked': is_checked, 'result': result, 'timestamp': timestamp})