import datetime
import json
import os

from jinja2 import FileSystemLoader, Environment
from odoo import models, fields, api, http, SUPERUSER_ID, _
from odoo.addons.roke_mes_production.controller.work_report import WorkReportKanban
import logging
import math

_logger = logging.getLogger(__name__)


class JzjxRokeRefixAutoWorkOrder(http.Controller):

    @http.route('/roke/mes/work_time/get', type='json', auth="user", csrf=False, cors='*')
    def get_work_time(self):
        """
        获取工时树
        :return:
        """
        uid = http.request.uid or http.request.session.uid
        if not uid:
            return {"code": 1, "message": "当前位置尚未登录，请先登录", "work_hours": 0}
        start_record = http.request.env(user=SUPERUSER_ID)['roke.work.start.record'].search([
            ("user_id", "=", uid),
            ("state", "=", "工作中")
        ], limit=1)
        if not start_record:
            return {"code": 1, "message": "未开工，请先开工。", "work_hours": 0}
        delta = datetime.datetime.now() - start_record.start_time
        work_hours = round(delta.total_seconds() / 3600, 2)
        return {"code": 0, "message": "获取成功！", "work_hours": work_hours}


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


class JzjxRokeWorkReportKanban(WorkReportKanban):

    @http.route('/roke/work/report/work_order_report', type='http', auth='public', csrf=False)
    def work_order_report(self):
        """工单报工"""
        values = {}
        # 修改Jinja2 分隔符
        env.variable_start_string = '[['
        env.variable_end_string = ']]'
        template = env.get_template('zdy_gdbg.html')
        html = template.render(values)
        return html
