# -*- coding: utf-8 -*-
from odoo import http, fields
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
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="制袋包装机")
