# -*- coding: utf-8 -*-
from odoo import http, fields
import os
import logging
from jinja2 import FileSystemLoader, Environment
from datetime import datetime, date, timedelta
from odoo import http, tools, SUPERUSER_ID
from odoo.addons.roke_mes_base.tools import http_tool

_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 JnzgProject(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_jnzg.html')
        return template.render(data)
    
    # @http.route('/roke/get/equipment/maintenance_info', type='json', methods=['POST', 'OPTIONS'], auth='none', cors='*', csrf=False)
    # def get_equipment_maintenance_info(self):
    #     """
    #     获取设备点检，保养，维修，更换件记录，设备当天生产合格数
    #     入参: {"equipment_id": 设备ID}
    #     返回: {
    #         "state": "success",
    #         "msgs": "获取成功",
    #         "equipment_maintenance_list": [...]
    #     }
    #     """
    #     req = http.request.jsonrequest
    #     equipment_id = req.get("equipment_id")
    #     domain = [("code", "!=", False)]
    #     if equipment_id:
    #         domain.append(("id", "=", equipment_id))
    #     today = fields.Date.today()
    #     tomorrow = today + timedelta(days=1)
    #     week_start = today - timedelta(days=today.weekday())
    #     week_end = week_start + timedelta(days=7)
    #     equipment_ids = http.request.env["roke.mes.equipment"].sudo().search(domain)
    #     equipment_maintenance_list = []
    #     for equipment_id in equipment_ids:
    #         check_record_id = http.request.env["roke.mes.eqpt.spot.check.record"].sudo().search([
    #             ("equipment_id", "=", equipment_id.id),
    #             ("create_date", ">=", datetime.combine(today, datetime.min.time()) - timedelta(hours=8)),
    #             ("create_date", "<", datetime.combine(tomorrow, datetime.min.time()) - timedelta(hours=8))
    #         ], limit=1)
    #         MaintenanceRecord = http.request.env["roke.mes.maintenance.order"].sudo()
    #         maintain_order_id = MaintenanceRecord.search([
    #             ("equipment_id", "=", equipment_id.id),
    #             ("create_date", ">=", datetime.combine(week_start, datetime.min.time()) - timedelta(hours=8)),
    #             ("create_date", "<", datetime.combine(week_end, datetime.min.time()) - timedelta(hours=8)),
    #             ("type", "=", "maintain")
    #         ], limit=1)
    #         repair_id = MaintenanceRecord.search([
    #             ("equipment_id", "=", equipment_id.id),
    #             ("report_time", ">=", datetime.combine(today, datetime.min.time()) - timedelta(hours=8)),
    #             ("report_time", "<", datetime.combine(tomorrow, datetime.min.time()) - timedelta(hours=8)),
    #             ("type", "=", "repair")
    #         ], limit=1)
    #         ChangeRecord = http.request.env["roke.spare.part.usage.record"].sudo()
    #         change_record_ids = ChangeRecord
    #         if repair_id:
    #             change_record_ids = ChangeRecord.search([
    #                 ("maintenance_order_id", "=", repair_id.id),
    #             ])
    #         equipment_maintenance_list.append({
    #             "equipment_id": equipment_id.id,
    #             "equipment_code": equipment_id.code,
    #             "equipment_name": equipment_id.name,
    #             "check_info": self.get_today_spot_check(check_record_id),
    #             "maintain_info": self.get_this_week_maintenance(maintain_order_id),
    #             "repair_info": self.get_equipment_repair(repair_id, MaintenanceRecord),
    #             "change_info": self.get_equipment_change(change_record_ids, ChangeRecord),
    #             "finish_qty": self.get_equipment_today_finish_qty(equipment_id, today, tomorrow)
    #         })
    #     return {"state": "success", "msgs": "获取成功", "equipment_maintenance_list": equipment_maintenance_list}
    
    # def get_equipment_today_finish_qty(self, equipment_id, today, tomorrow):
    #     """获取设备当天生产合格数"""
    #     finish_qty = sum(http.request.env["roke.work.record"].sudo().search([("work_center_id", "=", equipment_id.work_center_id.id), 
    #                                                         ("work_time", ">=", datetime.combine(today, datetime.min.time())), 
    #                                                         ("work_time", "<", datetime.combine(tomorrow, datetime.min.time()))]).mapped("finish_qty"))
    #     return finish_qty
    
    # def get_equipment_change(self, change_record_ids, ChangeRecord):
    #     """
    #     获取设备更换件记录
    #     """
        
    #     status = "no_task"  # 无更换
    #     detail = {}

    #     if change_record_ids:
    #         # 有任务，判断状态
    #         status = "has_task"  # 已更换
    #         detail = {
    #             "record_date": change_record_ids[0].replacement_time,  # 最近更换时间
    #             "removed_part": ".".join(change_record_ids.mapped("removed_part_id.name")),  # 拆下备件
    #             "installed_part": ".".join(change_record_ids.mapped("spare_part_id.name")),  # 换上备件
    #             "change_time": ChangeRecord.search_count([("equipment_id", "=", change_record_ids[0].equipment_id.id)])  # 更换次数
    #         }
    #     else:
    #         # 无任务时的基本信息
    #         detail = {
    #             "record_date": "",  # 最近更换时间
    #             "removed_part": "",  # 拆下备件
    #             "installed_part": "",  # 换上备件
    #             "change_time": 0  # 更换次数
    #         }

    #     return {
    #             "status": status,
    #             "detail": detail
    #         }
    
    # def get_equipment_repair(self, repair_id, MaintenanceRecord):
    #     """
    #     获取设备维修记录
    #     """
        
    #     status = "no_task"  # 无维修
    #     detail = {}

    #     if repair_id:
    #         # 有任务，判断状态

    #         if repair_id.state == "finish":
    #             status = "finished"  # 已完成
    #         else:
    #             status = "in_progress"  # 维修中

    #         change_record_ids = http.request.env["roke.spare.part.usage.record"].sudo().search([("maintenance_order_id", "=", repair_id.id)])
    #         detail = {
    #             "equipment_name": repair_id.equipment_id.name,  # 设备名称
    #             "last_maintenance_time": repair_id.report_time and str(repair_id.report_time) or "",  # 最近保养时间
    #             "repair_time": MaintenanceRecord.search_count([("equipment_id", "=", repair_id.equipment_id.id)]),  # 维修次数
    #             "repair_user": repair_id.repair_user_id.name if repair_id and repair_id.repair_user_id else "",  # 维修人
    #             "removed_part": ".".join(change_record_ids.mapped("removed_part_id.name")),  # 拆下备件
    #             "installed_part": ".".join(change_record_ids.mapped("spare_part_id.name")),  # 换上备件
    #         }
    #     else:
    #         # 无任务时的基本信息
    #         detail = {
    #             "last_maintenance_time": "",  # 最近保养时间
    #             "repair_time": "",  # 维修次数
    #             "repair_user": "",  # 维修人
    #             "removed_part": "",  # 拆下备件
    #             "installed_part": "",  # 换上备件
    #         }

    #     return {
    #         "status": status,
    #         "detail": detail
    #     }
    
    # def get_this_week_maintenance(self, maintain_order_id):
    #     """
    #     获取指定设备本周的保养记录及状态
    #     """
        
    #     status = "no_task"  # 无任务
    #     detail = {}

    #     if maintain_order_id:
    #         # 有任务，判断状态
    #         now = fields.Datetime.now()
    #         if maintain_order_id.state == "finish":
    #             status = "finished"  # 已完成
    #         elif maintain_order_id.estimated_completion_time and now > maintain_order_id.estimated_completion_time:
    #             status = "timeout"  # 超时
    #         elif maintain_order_id.item_ids.filtered(lambda x: x.state != "wait"):
    #             status = "in_progress"  # 进行中
    #         else:
    #             status = "not_started"  # 未开始

    #         # 组装详细信息
    #         maintenance_items = []
    #         for line in maintain_order_id.item_ids:
    #             maintenance_items.append(line.item_id.name)

    #         detail = {
    #             "last_maintenance_time": maintain_order_id.report_time and str(maintain_order_id.report_time) or "",  # 最近保养时间
    #             "maintenance_plan_name": maintain_order_id.maintenance_scheme_id.name if maintain_order_id.maintenance_scheme_id else "",  # 保养方案名称
    #             "maintenance_items": ",".join(maintenance_items),  # 保养项目
    #             "maintenance_result": "normal",  # 保养结果
    #         }

    #         # 判断是否有异常/故障，需要显示维修相关字段
    #         if maintain_order_id.normal_state == "abnormal":
    #             change_record_ids = http.request.env["roke.spare.part.usage.record"].sudo().search([("maintenance_order_id", "=", maintain_order_id.id)])

    #             # 维修相关字段（只有保养结果异常时才显示）
    #             detail.update({
    #                 "maintenance_result": "abnormal",  # 保养结果
    #                 "repair_status": http_tool.get_selection_field_values(maintain_order_id, "state") if maintain_order_id else "",  # 维修状态
    #                 "repair_user": maintain_order_id.repair_user_id.name if maintain_order_id and maintain_order_id.repair_user_id else "",  # 维修人
    #                 "repair_finish_time": maintain_order_id.finish_time and str(maintain_order_id.finish_time) or "" if maintain_order_id else "",  # 维修完成时间
    #                 "removed_part": ".".join(change_record_ids.mapped("removed_part_id.name")),  # 拆下备件
    #                 "installed_part": ".".join(change_record_ids.mapped("spare_part_id.name")),  # 换上备件
    #             })
    #     else:
    #         # 无任务时的基本信息
    #         detail = {
    #             "last_maintenance_time": "",  # 最近保养时间
    #             "maintenance_plan_name": "",  # 保养方案名称
    #             "maintenance_items": "",  # 保养项目
    #             "maintenance_result": "normal",  # 保养结果
    #         }

    #     return {
    #         "status": status,
    #         "detail": detail
    #     }
    
    # def get_today_spot_check(self, check_record_id):
    #     """
    #     获取设备当天的点检记录及状态
    #     """
        
    #     status = "no_task"  # 无任务
    #     detail = {}
    #     # 有任务，判断状态
    #     if check_record_id.state == "finish":
    #         status = "finished"  # 已完成
    #     else:
    #         # 检查是否超时
    #         now = fields.Datetime.now()
    #         _logger.info(f"get_today_spot_check, now: {now}, estimated_completion_time: {check_record_id.estimated_completion_time}")
    #         if check_record_id.estimated_completion_time and now > check_record_id.estimated_completion_time:
    #             status = "timeout"  # 超时
    #         elif check_record_id.item_record_ids.filtered(lambda x: x.result != False):
    #             status = "in_progress"  # 进行中
    #         else:
    #             status = "not_started"  # 未开始

    #     # 组装详细信息
    #     spot_items = []
    #     for line in check_record_id.item_record_ids:
    #         spot_items.append(line.check_item_id.name)
    #     detail = {
    #         "last_spot_check_time": check_record_id.start_date and str(check_record_id.start_date) or "",  # 最近点检时间
    #         "spot_check_plan": check_record_id.check_plan_id.name if check_record_id.check_plan_id else "",  # 点检方案
    #         "spot_check_items": ",".join(spot_items),  # 点检项目
    #         "spot_check_result": "normal",  # 点检结果
    #     }

    #     # 判断是否有异常/故障
    #     if check_record_id.normal_state == "abnormal":
    #         repair_order_id = http.request.env["roke.mes.maintenance.order"].sudo().search([("spot_check_record_id", "=", check_record_id.id)], limit=1)
    #         change_record_id = http.request.env["roke.spare.part.usage.record"].sudo().search([("maintenance_order_id", "=", repair_order_id.id)], limit=1)
    #         # 维修相关字段
    #         detail.update({
    #             "repair_status": http_tool.get_selection_field_values(repair_order_id, "state"),  # 维修状态
    #             "repair_user": repair_order_id.repair_user_id.name if repair_order_id.repair_user_id else "",  # 维修人
    #             "repair_finish_time": repair_order_id.finish_time and str(repair_order_id.finish_time) or "",  # 维修完成时间
    #             "removed_part": change_record_id.removed_part_id.name or "",  # 拆下备件
    #             "installed_part": change_record_id.spare_part_id.name or "",  # 换上备件
    #             "spot_check_result": "abnormal"  # 点检结果
    #         })
    #     return {
    #             "status": status,
    #             "detail": detail
    #         }
