import os
import datetime
import logging
import requests
from odoo.addons.roke_mes_client.controller import login as mes_login
from odoo import http, tools, SUPERUSER_ID
from jinja2 import FileSystemLoader, Environment
import pytz
from dateutil.relativedelta import relativedelta
_logger = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
templateloader = FileSystemLoader(searchpath=BASE_DIR + "/static/src/view")
env = Environment(loader=templateloader)


class RokeMesThreeColourLight(http.Controller):
    @http.route("/roke/three_color_light/device_state_list", type="http", auth='none', cors='*', csrf=False)
    def device_state_list(self, **kwargs):
        _self = http.request
        factory_code = http.request.env(user=SUPERUSER_ID)['ir.config_parameter'].get_param('database.uuid', default="")
        data = {"code": 1, "message": "请求通过", "data": {"factory_code": factory_code}}
        template = env.get_template('equipment_status_qdry.html')
        return template.render(data)

    @http.route("/roke/three_color_light/device_analysis", type="http", auth='none', cors='*', csrf=False)
    def device_analysis(self, **kwargs):
        _self = http.request
        factory_code = http.request.env(user=SUPERUSER_ID)['ir.config_parameter'].get_param('database.uuid', default="")
        data = {"code": 1, "message": "请求通过", "data": {"factory_code": factory_code}}
        template = env.get_template('oee_analysis.html')
        return template.render(data)
    
    @http.route('/roke/workstation/plant/tree', type='json', auth='none', csrf=False, cors="*")
    def get_roke_workstation_plant(self):
        _self = http.request
        no_icon = _self.jsonrequest.get("no_icon", False)
        data = []

        workshop_ids = http.request.env(user=SUPERUSER_ID)['roke.workshop'].search([
            ("plant_id", "=", False)
        ], order="name asc")

        if len(workshop_ids) > 0:
            data.append({
                "id": 0,
                "name": "未分配至车间",
                "type": "plant",
                "file_list": [],
                "workshops": [
                    {
                        "id": workshop_id.id,
                        "name": workshop_id.name or "",
                        "type": "workshop",
                        "workshop_icon": workshop_id.workshop_icon or "",
                        "classes_id": workshop_id.classes_id.id,
                        "classes_name": workshop_id.classes_id.name or "",
                        "center_count": len(workshop_id.center_ids),
                        "file_list": [{
                            "name": attachment.name,
                            "file_type": attachment.mimetype,
                            "data": f"data:{attachment.mimetype};base64,{attachment.datas.decode('utf-8')}" if
                            not no_icon else "",
                            "url": self._get_attachment_file_url(attachment)
                        } for attachment in workshop_id.attachment_ids]
                    } for workshop_id in workshop_ids
                ]
            })

        plant_ids = http.request.env(user=SUPERUSER_ID)['roke.plant'].search([
        ], order="name asc")

        for plant_id in plant_ids:
            # print("plant_id", plant_id.company_ids)
            data.append({
                "id": plant_id.id,
                "name": plant_id.name or "未分配至车间",
                "type": "plant",
                "file_list": [{
                    "name": attachment.name,
                    "file_type": attachment.mimetype,
                    "data": f"data:{attachment.mimetype};base64,{attachment.datas.decode('utf-8')}" if not no_icon
                    else "",
                    "url": self._get_attachment_file_url(attachment)
                } for attachment in plant_id.attachment_ids],
                "workshops": [
                    {
                        "id": workshop_id.id,
                        "name": workshop_id.name or "",
                        "type": "workshop",
                        "workshop_icon": workshop_id.workshop_icon or "",
                        "classes_id": workshop_id.classes_id.id,
                        "classes_name": workshop_id.classes_id.name or "",
                        "center_count": len(workshop_id.center_ids),
                        "file_list": [{
                            "name": attachment.name,
                            "file_type": attachment.mimetype,
                            "data": f"data:{attachment.mimetype};base64,{attachment.datas.decode('utf-8')}" if
                            not no_icon else "",
                            "url": self._get_attachment_file_url(attachment)
                        } for attachment in workshop_id.attachment_ids]
                    } for workshop_id in plant_id.workshop_ids
                ]
            })

        return {"code": 0, "message": "获取车间列表成功", "data": data}