# -*- coding: utf-8 -*-
from odoo import http, fields,SUPERUSER_ID
from odoo.http import request
from odoo.addons.roke_mes_three_colour_light.controller.main import RokeMesThreeColourLight
import os
import math
from datetime import datetime, time, timedelta
from jinja2 import Environment, FileSystemLoader
import logging
import requests
import json

_logger = logging.getLogger(__name__)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
templateloader = FileSystemLoader(searchpath=BASE_DIR + "/static")
env = Environment(loader=templateloader)

dws_platform_url ='https://dws-platform.xbg.rokeris.com/dev-api/public/device'
# dws_platform_url = 'http://localhost/dev-api/public/device'

headers = {
    'Content-Type': 'application/json',
}


class ResMesBigScreen(http.Controller):
    @http.route('/roke/tht/expected_process', type='http', auth='public', csrf=False, cors="*")
    def roke_expected_process_module(self, **kwargs):
        template = env.get_template('html/big_screen/view/expected_process.html')
        html = template.render({})
        return html

    @http.route('/roke/tht/cook_process', type='http', auth='public', csrf=False, cors="*")
    def roke_cook_process_module(self, **kwargs):
        template = env.get_template('html/big_screen/view/cook_process.html')
        html = template.render({})
        return html

    def search_equipments(self, data_acquisition_code='', plant_name='', category_name=''):
        """查询设备"""
        domain = []
        if data_acquisition_code:
            domain.append(('data_acquisition_code', 'in', data_acquisition_code))
        # 构建查询条件
        if plant_name:
            domain.append(('plant_id.name', '=', plant_name))

        if category_name:
            domain.append(('category_id.name', '=', category_name))

        # 查询设备
        equipments = http.request.env['roke.mes.equipment'].sudo().search(domain)

        # 构造响应数据
        equipment_list = [{
            'id': eq.id,
            'device_name': eq.name,
            'device_code': eq.code,
            'data_acquisition_code': eq.data_acquisition_code,
            'category': eq.category_id.name if eq.category_id else '',
            'plant_name': eq.plant_id.name if eq.plant_id else '',
        } for eq in equipments]

        return equipment_list

    def common_dws_interface(self, body=None, url='', cate=''):
        """获取大屏数据"""
        plant_name = body.get("plant_name", '')
        today = body.get("today", '')
        device_code_list = body.get("device_code_list", [])
        # if not today:
        #     today = fields.Date.today().strftime('%Y-%m-%d')
        category_name = body.get("category_name",'')
        # 构建查询条件
        if device_code_list:
            equipment_list =  device_code_list
        else:
            equipment_list = self.search_equipments(plant_name=plant_name, category_name=category_name)
        try:
            api_path = dws_platform_url + url
            payload = {
                "plant_name": plant_name,
                "today": today,
                "category_name": category_name,
                "device_code_list": equipment_list
            }
            if cate:
                payload.update({"cate": cate})
            res = requests.post(api_path, data=json.dumps(payload), headers=headers, )
            res_json = res.json()

            return res_json


        except Exception as e:
            _logger.error(e)
            return {
                "code": 100,
                "msg": str(e),
                "data": {

                },
                "success": False,
                "time": fields.Datetime.now()
            }

    @http.route('/big_screen_count', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False,
                cors='*')
    def big_screen_count(self):
        """获取大屏数据"""
        body = http.request.jsonrequest
        return self.common_dws_interface(body, '/big_screen_count')

    @http.route('/big_screen_today', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False,
                cors='*')
    def big_screen_today(self):

        body = http.request.jsonrequest
        return self.common_dws_interface(body, '/big_screen_today')

    @http.route('/get_jiedongji_temperature', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False,
                cors="*")
    def get_jiedongji_temperature(self):
        body = http.request.jsonrequest
        return self.common_dws_interface(body, '/get_real_time_device_data', cate="解冻机")

    @http.route('/get_qiekuaiji_data', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False, cors="*")
    def get_qiekuaiji_data(self):
        body = http.request.jsonrequest
        device_code_list = body.get('device_code_list')
        try:
            api_path = dws_platform_url + '/get_qiekuaiji_data'
            payload = {

                "device_code_list": device_code_list
            }
            res = requests.post(api_path, data=json.dumps(payload), headers=headers, )
            res_json = res.json()

            return res_json
        except Exception as e:
            _logger.error(e)
            return {
                "code": 100,
                "msg": str(e),
                "data": {

                },
                "success": False,
                "time": fields.Datetime.now()
            }

    @http.route('/get_yanxunlu_data', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False, cors="*")
    def get_yanxunlu_data(self):
        body = http.request.jsonrequest
        return self.common_dws_interface(body, '/get_real_time_device_data', cate="烟熏炉")

    @http.route('/get_lashengmo_data', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False, cors="*")
    def get_lashengmo_data(self):
        body = http.request.jsonrequest
        return self.common_dws_interface(body, '/get_real_time_device_data', cate="拉伸膜包装机")

    @http.route('/get_lishibaozhuang_data', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False, cors="*")
    def get_lishibaozhuang_data(self):
        body = http.request.jsonrequest
        return self.common_dws_interface(body, '/get_real_time_device_data', cate="制袋包装机")



    @http.route('/roke/tht/get_abnormal_alarm_list', type='json', auth="none", methods=['POST', 'OPTIONS'], csrf=False, cors='*')
    def get_abnormal_alarm_list(self):
        """
        获取异常表单列表
        :return:
        """
        jsonrequest = http.request.jsonrequest
        domain = []
        abnormal_alarm_id = jsonrequest.get('abnormal_alarm_id', False)
        #表单id
        if abnormal_alarm_id:
            domain.append(('id', '=', abnormal_alarm_id))
        abnormal_id = jsonrequest.get('abnormal_id', False)
        #异常类型id
        if abnormal_id:
            domain.append(('abnormal_id', '=', abnormal_id))
        page_size = int(http.request.jsonrequest.get('page_size', 20))
        page_no = int(http.request.jsonrequest.get('page_no', 1))
        abnormal_alarm_ids = http.request.env(user=SUPERUSER_ID)['roke.abnormal.alarm'].search(domain, limit=page_size, offset=(page_no - 1) * page_size, order="originating_time desc")
        abnormal_alarm_list = []
        for item in abnormal_alarm_ids:
            note = ''
            if item.abnormal_id.name == '设备异常':
                note = f"{item.equipment_id.name or ''}发生了故障"
            elif item.abnormal_id.name == '缺料断料':
                note = f"{item.sponsor.name or item.create_uid.name or ''} 发起了缺料申请"
            abnormal_alarm_list.append({
                "id": item.id,  # 异常表单id
                "abnormal_name": item.abnormal_id.name, # 异常类型
                "originating_time": (item.originating_time + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") if item.originating_time else '', #发起时间
                "note": note, #报警表述

            })
        total = http.request.env(user=SUPERUSER_ID)['roke.abnormal.alarm'].search_count(domain)
        return {
            "state": "success",
            "msgs": "获取成功",
            "total": total,
            "abnormal_alarm_list": abnormal_alarm_list
        }
    @http.route('/roke/tht/utilization_rate_top_5', type='json', auth='none', methods=['POST','OPTIONS',], csrf=False,cors="*")
    def get_oee_top5(self):
        try:
            url = "https://dws-platform.xbg.rokeris.com/dev-api/public/device_efficiency/series_utilization_rate_top_5"
            date = fields.Date.today().strftime("%Y-%m-%d")
            eq_ids = http.request.env["roke.mes.equipment"].sudo().search([('code',"!=",'')])
            query_data = [{"device_name": eq_id.name,"device_code": eq_id.code} for eq_id in eq_ids]
            res = requests.post(url, data=json.dumps({
                "device_code_list": query_data,
                "start_date": date,
                "plan_time_list":{}
            }), headers=headers)
            if res.status_code != 200:
                return {"code": 1, "message": "获取数据失败", "data": None}
            res = res.json()
            data = res.get("data", {})
            device_data = data.get("device_data", [])
            return_data = [{"device_name": item.get("device_name"),
                                        "today_utilization_rate": str(item.get("today_utilization_rate",0)) + "%",}
                                        for item in device_data]

            return {"code": "success", "message": "", "data": return_data,"date": date}
        except Exception as e:
            return {"code": "error", "message": f"获取数据失败:{str(e)}", "data": None,"date": date}


