import datetime
import json
import logging
import os
from jinja2 import FileSystemLoader, Environment
import pytz
from odoo import models, fields, api, http, SUPERUSER_ID, _
from odoo.addons.roke_workstation_api.controllers.data_analysis import reduce_pytz_conversion, pytz_conversion
from odoo.addons.roke_workstation_api.controllers.work_order import RokeWorkstationWorkOrder

_logger = logging.getLogger(__name__)


# 设置查找html文件的路径
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
templateloader = FileSystemLoader(searchpath=BASE_DIR + "/static")
env = Environment(loader=templateloader)


class InheritRokeWorkstationWorkOrder(RokeWorkstationWorkOrder):
    @http.route('/roke/workstation/work_order/workstation_work_order', type='json', auth='user', csrf=False, cors="*")
    def workstation_work_order(self):
        """
        继承父级获取工单信息接口，添加返修单/补件单获取上级报工工单的所有工艺信息数据和工艺详情信息数据
        """
        _self = http.request
        res = super(InheritRokeWorkstationWorkOrder, self).workstation_work_order()
        next_work_order = _self.env["roke.work.order"].search([("id", "=", res.get("data", {}).get("id", 0))])
        res.get("data", {}).update({
            "next_process_name": next_work_order.next_wo_id.process_id.name or ""
        })
        return res


class RokeWorkstationWorkOrderModel(http.Controller):

    @http.route('/roke/craft_design/index', type='http', auth='user', csrf=False, cors="*")
    def roke_index_demo_module(self, **kwargs):
        product_id = kwargs.get("product_id", False)
        routing_id = kwargs.get("routing_id", False)
        user_id = http.request.env.user.id
        values = {
            "product_id": product_id,
            "routing_id": routing_id,
            "user_id": user_id
        }
        template = env.get_template('/src/html/view/craft_design.html')
        html = template.render(values)
        return html

    @http.route('/roke/workstation/craft_design/workstation_bom/get', type='json', auth='user', csrf=False,
                cors="*")
    def workstation_bom_get(self):
        """
        获取工艺明细的关键物料
        """
        _self = http.request
        routing_line_id = _self.jsonrequest.get("routing_line_id", 0)
        p_bom_line = _self.env["roke.mes.p_bom.line"].search([("routing_line_id", "=", routing_line_id)],
                                                             order="create_date desc")
        bom_list = []
        for v in p_bom_line:
            bom_list.append({
                "id": v.id,
                "product_id": v.product_id.id,
                "product_name": v.product_id.name,
                "qty": v.qty,
                "must": v.must
            })
        return {"code": 0, "message": f"获取成功！", "data": bom_list}

    @http.route('/roke/workstation/craft_design/workstation_bom/create', type='json', auth='user', csrf=False,
                cors="*")
    def workstation_bom_create(self):
        """
        创建工艺明细的关键物料
        """
        _self = http.request
        routing_line_id = _self.jsonrequest.get("routing_line_id", 0)
        product_id = _self.jsonrequest.get("product_id", 0)
        qty = _self.jsonrequest.get("qty", 0)
        must = _self.jsonrequest.get("must", False)
        product = _self.env["roke.product"].search([("id", "=", product_id)])
        if not product:
            return {"code": 1, "message": "没找到对应的产品！"}
        _self.env["roke.mes.p_bom.line"].create({
            "product_id": product.id,
            "product_routing_id": product.routing_id.id,
            "routing_line_id": routing_line_id,
            "qty": qty,
            "must": must
        })
        return {"code": 0, "message": f"获取成功！"}

    @http.route("/roke/workstation/craft_design/workstation_bom/update", type='json', auth="user", cors='*', csrf=False)
    def workstation_bom_update(self, **kwargs):
        """
        修改工艺明细的关键物料
        """
        _self = http.request
        bom_info = _self.jsonrequest.get("bom_info", [])

        p_bom_line = _self.env["roke.mes.p_bom.line"]
        for item in bom_info:
            bom_id = item.get("id", 0)
            product_id = item.get("product_id", 0)
            product = _self.env["roke.product"].search([("id", "=", product_id)])
            qty = item.get("qty", 0)
            must = item.get("must", False)
            p_bom_line_id = p_bom_line.sudo().search([("id", "=", bom_id)])
            p_bom_line_id.write({
                "product_id": product.id,
                "product_routing_id": product.routing_id.id,
                "qty": qty,
                "must": must
            })
        return {"code": 0, "message": "更新成功"}

    @http.route("/roke/workstation/craft_design/workstation_bom/delete", type='json', auth="user", cors='*', csrf=False)
    def workstation_bom_delete(self, **kwargs):
        """
        删除工艺明细的关键物料
        """
        _self = http.request
        bom_id = _self.jsonrequest.get("id", 0)
        _self.env["roke.mes.p_bom.line"].search([("id", "=", bom_id)]).unlink()
        return {"code": 0, "message": "删除成功"}

    @http.route('/roke/workstation/craft_design/workstation_product/get', type='json', auth='user', csrf=False, cors="*")
    def workstation_product_get(self):
        """
        获取产品的数据，格式和工艺设计树一样
        """
        _self = http.request
        product_id = _self.jsonrequest.get("product_id", 0)
        product = _self.env["roke.product"].sudo().search([("id", "=", product_id)])
        data = {
            "type": "product",
            "parent_id": 0,
            "id": product.id,
            "name": product.name or "",
            "specification": product.specification or "",
            "code": product.code or "",
            "capacity": product.capacity or 0.0,
            "fpy": product.fpy or 0.0,
            "category": {"id": product.category_id.id, "name": product.category_id.name or ""},
            "has_bom": False,
        }
        return {"code": 0, "message": f"获取成功！", "data": data}

    @http.route('/roke/workstation/craft_design/workstation_process/save', type='json', auth="user", cors='*', csrf=False)
    def save_craft_design_workstation_process(self):
        kwargs = http.request.jsonrequest
        routing_id = kwargs.get("routing_id", False)

        lines = kwargs.get("lines", [])

        if not routing_id:
            return {"code": 1, "message": "入参错误，工艺路线ID位必传参数。", "data": None}

        routing_obj = http.request.env(user=SUPERUSER_ID)['roke.routing'].search([
            ("id", "=", int(routing_id))
        ])

        if not routing_obj:
            return {"code": 1, "message": "工艺路线不存在或已删除", "data": None}

        for line in lines:
            if line["type"] == "delete":
                line_id = line["line_id"]
                routing_obj.line_ids.filtered(
                    lambda l: l.id == line_id).unlink()
            elif line["type"] == "add":
                sequence = line["sequence"]
                process_id = line["process_id"]
                routing_obj.write({
                    "line_ids": [(0, 0, {
                        "process_id": process_id,
                        "sequence": sequence
                    })]
                })
            elif line["type"] == "update":
                line_id = line["line_id"]
                sequence = line["sequence"]
                routing_obj.line_ids.filtered(lambda l: l.id == line_id).write({
                    "sequence": sequence
                })
            else:
                pass

        return {"code": 0, "message": "工序信息添加成功", "data": {"routing_id": routing_obj.id}}

    @http.route('/roke/workstation/craft_design/workstation_work_process_check_work_order', type='json', auth='user',
                csrf=False, cors="*")
    def workstation_work_process_check_work_order(self):
        """
        根据工艺路线重新生成工单
        """
        _self = http.request
        routing_id = _self.jsonrequest.get("routing_id", 0)
        routing = _self.env["roke.routing"].search([("id", "=", routing_id)])
        if not routing.routing_task_id:
            return {"code": 0, "message": f"工艺没有相应的任务！"}
        routing.routing_task_id.write({
            "work_order_ids": routing.routing_task_id.change_routing_id_work_order(routing)
        })
        return {"code": 0, "message": f"工艺路线生成工单成功！"}

    @http.route('/roke/workstation/craft_design/workstation_verify_if_editable', type='json', auth='user',
                csrf=False, cors="*")
    def workstation_verify_if_editable(self):
        """
        根据任务报工情况判断工艺设计是否可编辑
        """
        _self = http.request
        routing_id = _self.jsonrequest.get("routing_id", 0)
        routing = _self.env["roke.routing"].search([("id", "=", routing_id)])
        if not routing.routing_task_id:
            return {"code": 0, "message": f"工艺没有相应的任务，不可编辑！", "editable": False}
        if routing.routing_task_id.record_ids:
            return {"code": 0, "message": f"绑定任务已报工，不可编辑！", "editable": False}
        return {"code": 0, "message": f"获取成功！", "editable": True}
