using System;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.UI;
using static DownLoadXRManager;
using System.IO;
using UnityEngine.Android;



#if UNITY_ANDROID || UNITY_IOS
using NativeFilePickerNamespace;
#endif
public class QianZiItem : MonoBehaviour
{
    public string scpath;
    public Texture2D defaultTexture;
    public void showqianzi()
    {
        if(downloadtex!=null)
        {
            Destroy(downloadtex);
        }
        AdvancedDrawingPad.callback = (tex)=>{
            byte[] pngdata=tex.EncodeToPNG();
            int fileSize = pngdata.Length;
            string uuid =  Guid.NewGuid().ToString();
            string fileName = uuid+".png";
            string objecName = "workorder/"+int.Parse(ChuLiItemManager.ChooseData["id"].ToString())+"/";
            scpath = objecName +fileName;
            StartCoroutine(SaveToGalleryAndGetPath(pngdata,fileName,(filePath)=>{
                // 文件预上传
                JsonData jData = new JsonData();
                jData["size"] = fileSize;
                jData["ext"] = "jpg";
                jData["name"] = fileName;

                JsonData fileData = new JsonData();
                fileData["filePath"] = filePath;
                fileData["fileSize"] = fileSize;
                fileData["fileName"] = fileName;
                // project /{ projectId}/ inspection /{ projectInspectionId}/{ taskId}
                fileData["objectName"] = objecName;

                JsonData fildData = fileData;
                // 文件上传
                DownLoadXRManager.PutFile(fildData["filePath"].ToString(), fildData["fileName"].ToString(), fildData["objectName"].ToString() + fildData["fileName"].ToString(),uuid, int.Parse(fildData["fileSize"].ToString()), msg =>
                {
                    Debug.Log(" 文件上传成功 " + msg);
                });

            // 使用方式
              //  string internalPath = CopyToInternalStorage(filePath);
               // OpenFile(internalPath);
              //  "workorder/1/352b97c2-a9ea-49e8-bb6b-39e9a02f7ee5.png";
            }))  ;

            
            downloadtex = tex;
            this.transform.GetComponent<RawImage>().texture = tex;
        };
        TianJiWindowManager.Instance.showPop(3);
    }private string CopyToInternalStorage(string originalPath)
{
    string internalPath = Path.Combine(Application.persistentDataPath, Path.GetFileName(originalPath));
    File.Copy(originalPath, internalPath, true);
    return internalPath;
}
  public void OpenFile(string filePath)
    {
        if (!File.Exists(filePath))
        {
            Debug.LogError("文件不存在: " + filePath);
            return;
        }

#if UNITY_ANDROID && !UNITY_EDITOR
        StartCoroutine(TryOpenFileAndroid(filePath));
#endif
    }

    private IEnumerator TryOpenFileAndroid(string filePath)
    {

            yield return null;
        try
        {
            AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
            AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri");
            AndroidJavaObject currentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer")
                .GetStatic<AndroidJavaObject>("currentActivity");

            // 使用 FileProvider
            AndroidJavaClass fileProvider = new AndroidJavaClass("androidx.core.content.FileProvider");
            AndroidJavaObject fileObj = new AndroidJavaObject("java.io.File", filePath);
            
            string authority = currentActivity.Call<string>("getPackageName") + ".fileprovider";
            AndroidJavaObject uri = fileProvider.CallStatic<AndroidJavaObject>(
                "getUriForFile", 
                currentActivity, 
                authority, 
                fileObj);

            // 创建 Intent
            AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent");
            intent.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_VIEW"));
            intent.Call<AndroidJavaObject>("setDataAndType", uri, GetMimeType(filePath));
            intent.Call<AndroidJavaObject>("addFlags", 
                intentClass.GetStatic<int>("FLAG_GRANT_READ_URI_PERMISSION"));

            // 检查是否有应用可以处理
            AndroidJavaObject pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
            bool canOpen = intent.Call<AndroidJavaObject>("resolveActivity", pm) != null;

            if (canOpen)
            {
                currentActivity.Call("startActivity", intent);
            }
            else
            {
                Debug.LogError("没有应用可以打开此文件类型");
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError("打开文件失败: " + e.Message);
        }
    }

    private string GetMimeType(string filePath)
    {
        string extension = Path.GetExtension(filePath).ToLower();
        switch (extension)
        {
            case ".pdf": return "application/pdf";
            case ".doc": case ".docx": return "application/msword";
            case ".xls": case ".xlsx": return "application/vnd.ms-excel";
            case ".jpg": case ".jpeg": return "image/jpeg";
            case ".png": return "image/png";
            case ".mp4": return "video/mp4";
            case ".avi": return "video/x-msvideo";
            default: return "*/*";
        }
    }
    public IEnumerator SaveToGalleryAndGetPath(byte[] imageData, string filename, System.Action<string> callback)
    {
        string path = null;
        bool done = false;
        
        if (Application.platform == RuntimePlatform.Android || 
            Application.platform == RuntimePlatform.IPhonePlayer)
        {
            NativeGallery.Permission permission = NativeGallery.SaveImageToGallery(
                imageData,
                "MyAppPhotos", // 相册名称
                filename,
                (success, savedPath) => 
                {
                    path = success ? savedPath : null;
                    done = true;
                    
                });
            
            Debug.Log("Permission status: " + permission);
            
            yield return new WaitUntil(() => done);
        }
        else
        {
            // 非移动平台,保存到本地
            string localPath = System.IO.Path.Combine(Application.persistentDataPath, filename);
            System.IO.File.WriteAllBytes(localPath, imageData);
            path = localPath;
        }
        
        callback?.Invoke(path);
    }
    Texture2D downloadtex;
    public void downloadimg(string path)
    {
        if(path==""||path==null)
        {
            return;
        }
        if(downloadtex!=null)
        {
            Destroy(downloadtex);
        }
        Debug.Log("开始下载图片===》"+path);
        DownLoadResources dlr = new DownLoadResources();
        dlr.path = path;
        // 文件上传
        DownLoadXRManager.DownLoadForTexture(dlr, msg =>
        {
            downloadtex=msg;
            this.transform.GetComponent<RawImage>().texture = msg;
        },(f)=>{


        });
    }
}