#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 #
# @Time    : 2022/4/1 11:27
# @Author  : ming
# @Email   : zhangdongming@asj6.wecom.work
# @File    : CronDelDataController.py
# @Software: PyCharm
import time

from django.db import connection, connections
from django.views import View

from Object.ResponseObject import ResponseObject
from Object.utils import LocalDateTimeUtil


class CronDelDataView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        response = ResponseObject()
        if operation == 'access-log/del':   # 定时删除访问接口数据
            return self.del_access_log(response)
        elif operation == 'push-info/del':  # 定时删除推送数据
            return self.del_push_info(response)
        else:
            return response.json(404)

    @staticmethod
    def del_access_log(response):
        try:
            cursor = connection.cursor()
            # 删除一个月前的数据
            last_month = LocalDateTimeUtil.get_last_month()
            sql = 'DELETE FROM access_log WHERE time < %s limit %s'
            cursor.execute(sql, [last_month, 10000])
            # 关闭游标
            cursor.close()
            connection.close()
            return response.json(0)
        except Exception as e:
            return response.json(500, repr(e))

    @staticmethod
    def del_push_info(response):
        nowTime = int(time.time())
        cursor = connections['mysql02'].cursor()
        try:
            for i in range(5):
                # 删除7天前的数据
                sql = "DELETE FROM `equipment_info` WHERE addTime<={} LIMIT 10000".format(nowTime - 3600 * 24 * 7)
                cursor.execute(sql)
            # 关闭游标
            cursor.close()
            return response.json(0)
        except Exception as e:
            return response.json(500, repr(e))
