import base64
import datetime
import json
import logging
import os
import urllib
import uuid

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.material import RokeWorkstationMaterial

_logger = logging.getLogger(__name__)

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


EXTENSIONS_2D = [
    "dwg", "dxf"
]
EXTENSIONS_3D = [
    "sldasm", "sldprt", "asm", "par", "pwd", "psm", "prt", "neu", "iam", "ipt",
    "catpart", "catproduct", "catshape", "cgr", "3dxml", "stp", "step", "stpz",
    "stepz", "stpx", "stpxz", "igs", "iges", "stl", "obj", "mtl", "x_t", "xmt_txt",
    "x_b", "xmt_bin", "p_b", "xmp_bin", "xmp_txt", "sat", "sab", "jt", "3dm",
    "fbx", "gltf", "glb", "prc", "u3d"
]


_logger = logging.getLogger(__name__)



class InheritRokeWorkstationWorkOrder(RokeWorkstationMaterial):

    def _get_document_url(self, document_id, file_type=None, ip=""):

        attachment_id = document_id.attachment_id

        if not attachment_id.create_date:
            create_date = ""
        else:
            user_tz = pytz.timezone(http.request.env.context.get('tz', "Asia/Shanghai"))
            date_dt = pytz.utc.localize(attachment_id.create_date).astimezone(user_tz)
            create_date = date_dt.strftime("%Y-%m-%d %H:%M:%S")

        if not attachment_id.access_token:
            attachment_id.generate_access_token()

        if attachment_id.mimetype == "application/pdf":
            code = str(uuid.uuid4())
            url = f"/web/content/{attachment_id.id}/{code}_{attachment_id.name}?access_token={attachment_id.access_token}&unique={str(fields.Datetime.now().timestamp())}"
            return {
                "id": document_id.id,
                "name": document_id.name,
                "mimetype": attachment_id.mimetype,
                "thumbnail": self.get_doc_thumbnail(attachment_id),
                "type": "url",
                # "data": ip + f"/web/static/lib/pdfjs/web/viewer.html?file={content_url}",
                "data": ip + url,
                "is_picture": False,
                "ip_address": document_id.data_sync_ip or '',
                "create_user": attachment_id.create_uid.name or "",
                "create_date": create_date,
                # "preview": "pdf-preview",
                "preview": "kkfileview-preview"
            }
        elif attachment_id.mimetype.startswith('image/') or attachment_id.index_content == 'image':
            url = f"/web/image/{attachment_id.id}?access_token={attachment_id.access_token}&unique={str(fields.Datetime.now().timestamp())}"
            return {
                "id": document_id.id,
                "name": document_id.name,
                "mimetype": attachment_id.mimetype,
                "ip_address": document_id.data_sync_ip or '',
                "thumbnail": self.get_doc_thumbnail(attachment_id),
                "type": "url",
                "data": ip + url,
                "is_picture": True,
                "create_user": attachment_id.create_uid.name or "",
                "create_date": create_date,
                "preview": "img-preview"
            }
        else:
            split_list = document_id.name.split('.')
            if len(split_list) > 1:
                file_extension = split_list[-1]
                if file_extension.lower() in EXTENSIONS_2D + EXTENSIONS_3D:
                    icp = document_id.env['ir.config_parameter'].sudo()
                    transform_service = icp.get_param('p.transform.service')
                    model_url = attachment_id.local_url + ".scs"
                    model_url_base64 = base64.b64encode(model_url.encode()).decode()
                    url = f"{transform_service}/transform2/z3d/?model={urllib.parse.quote(model_url_base64)}"
                    return {
                        "id": document_id.id,
                        "name": document_id.name,
                        "mimetype": attachment_id.mimetype,
                        "ip_address": document_id.data_sync_ip or '',
                        "thumbnail": self.get_doc_thumbnail(attachment_id),
                        "type": "url",
                        "data": url,
                        "is_picture": True,
                        "create_user": attachment_id.create_uid.name or "",
                        "create_date": create_date,
                        "preview": "cad-preview"
                    }
                else:
                    code = str(uuid.uuid4())
                    url = f"/web/content/{attachment_id.id}/{code}_{attachment_id.name}?access_token={attachment_id.access_token}&unique={str(fields.Datetime.now().timestamp())}"
                    return {
                        "id": document_id.id,
                        "name": document_id.name,
                        "ip_address": document_id.data_sync_ip or '',
                        "mimetype": attachment_id.mimetype,
                        "thumbnail": self.get_doc_thumbnail(attachment_id),
                        "type": "url",
                        "data": ip + url,
                        "is_picture": False,
                        "create_user": attachment_id.create_uid.name or "",
                        "create_date": create_date,
                        "preview": "kkfileview-preview"
                    }
            else:
                code = str(uuid.uuid4())
                url = f"/web/content/{attachment_id.id}/{code}_{attachment_id.name}?access_token={attachment_id.access_token}&unique={str(fields.Datetime.now().timestamp())}"
                return {
                    "id": document_id.id,
                    "name": document_id.name,
                    "ip_address": document_id.data_sync_ip or '',
                    "mimetype": attachment_id.mimetype,
                    "thumbnail": self.get_doc_thumbnail(attachment_id),
                    "type": "url",
                    "data": ip + url,
                    "is_picture": False,
                    "create_user": attachment_id.create_uid.name or "",
                    "create_date": create_date,
                    "preview": "kkfileview-preview"
                }
