# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
from odoo.addons.roke_mes_three_colour_light.controller.main import RokeMesThreeColourLight
from odoo.addons.roke_workstation_api.controllers.abnormal import RokeWorkstationAbnormal
import os
import math
from datetime import datetime, time
from jinja2 import Environment, FileSystemLoader
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
templateloader = FileSystemLoader(searchpath=BASE_DIR + "/static")
env = Environment(loader=templateloader)

class ThtProject(http.Controller):
    @http.route('/tht/get/equipment/working_time', type='json', auth="none", csrf=False, cors='*')
    def get_equipment_working_time(self, **kwargs):
        """获取车间工作时间"""
        jsonrequest = http.request.jsonrequest
        plant_name = jsonrequest.get("plant_name", False)
        domain = [("code", "!=", False)]
        if plant_name:
            domain.append(("plant_id.name", "=", plant_name))
        equipment_ids = http.request.env['roke.mes.equipment'].sudo().search(domain)
        today = datetime.now()
        start_working_time = {}
        end_working_time = {}
        wait_time = {}
        plant_ids = equipment_ids.mapped("plant_id")
        for plant_id in plant_ids:
            config_id = http.request.env['plant.working.time.config'].sudo().search([("plant_id", "=", plant_id.id)], limit=1)
            for item in equipment_ids.filtered(lambda x: x.plant_id == plant_id):
                start_hour = math.floor(config_id.start_time)
                start_working_time[item.code] = datetime.combine(today, time(start_hour, int((config_id.start_time - start_hour) * 60))).strftime("%Y-%m-%d %H:%M:%S")
                end_hour = math.floor(config_id.end_time)
                end_working_time[item.code] = datetime.combine(today, time(end_hour, int((config_id.end_time - end_hour) * 60))).strftime("%Y-%m-%d %H:%M:%S")
                wait_time[item.code] = config_id.wait_time
        return {"state": "success", "msgs": "获取数据成功！", 
                "start_working_time": start_working_time, 
                "end_working_time": end_working_time,
                "wait_time": wait_time}


class RokeMesThreeColourLightExt(RokeMesThreeColourLight):
    #重写
    @http.route("/roke/three_color_light/device_state_list", type="http", auth='none', cors='*', csrf=False)
    def device_state_list(self, **kwargs):
        # 自定义逻辑
        _self = request
        factory_code = "custom_factory_code_123"  # 自定义 factory_code
        data = {
            "code": 1,
            "message": "请求通过",
            "data": {
                "factory_code": factory_code,
                "override": True  # 添加额外字段
            }
        }
        template = env.get_template('src/view/equipment_status.html')
        return template.render(data)

    @http.route('/roke/equipment/search', type='json', methods=['POST', 'OPTIONS'], auth="none", csrf=False,
                cors='*')
    def search_equipment(self):
        """
        根据 plant_id   category_id 查询设备（JSON POST）
        请求示例:
            {
                "plant_name": ,
                "category_name":
            }
        """
        # 获取请求数据
        data = http.request.jsonrequest
        plant_name = data.get('plant_name')
        category_name = data.get('category_name')

        data_acquisition_code = data.get('data_acquisition_code')



        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))

        if not domain:
            return {
                "state": "error",
                "msgs": "参数不全;车间和 设备类别不能同时为空",
                "data": []
            }

        # 查询设备
        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 {
            'status': 'success',
            'code': 200,
            'data': equipment_list
        }
    

class RokeWorkstationAbnormalExt(RokeWorkstationAbnormal):
    @http.route('/roke/abnormal_alarm/census', type='http', auth='public', csrf=False, cors="*")
    def roke_index_demo_module(self, **kwargs):
        template = env.get_template('html/abnormal_alarm/view/index.html')
        html = template.render({})
        return html
