//
//  VRPhotoTransformController.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/2/25.
//

import UIKit
import DeviceKit
import SVProgressHUD
import Photos
import CoreImage
import Firebase
class VRPhotoTransformController: BaseController {
    
    //    var heroAsset1:AVAsset?
    let kNowTimeToUserDefaultKey_PhotoTransformController:String = "kNowTimeToUserDefaultKey_PhotoTransformController"
    var sourceImageData:Data?
    var imageAsset:PHAsset?
    
    var sourceImageURL:URL?
    var outputImageURL:URL?
    
    var mTopImgView:UIImageView?
    var mImgView:UIImageView?
    
    var mCenView:UIView?
    var mCenLab1:UILabel?
    var mCenLab2:UILabel?
    var mCenBtn:UIButton?
    
    var mLabel:UILabel?
    var mTabView:CCSpatialPlayView?
    
    var mBottomBtn:UIButton?
    
    lazy var progressView:CCTransformProgressPopView? = {
        let pv = CCTransformProgressPopView.init(frame: view.bounds)
        pv.closeActionBlock = { [weak self] in//返回首页
            self?.navigationController?.popToRootViewController(animated: true)
            pv.removeFromSuperview()
            Analytics.logEvent("result_back_click", parameters: nil)
        }
        pv.transformActionBlock = {//继续转码
            pv.isHidden = true
            Analytics.logEvent("result_continue_click", parameters: nil)
            FeedbackView.show {//好评
                
            } negativeCallback: {//差评
                
            }

        }
        return pv
    }()
    
    //显示进度条
    func showProgress() {
        Analytics.logEvent("process_pv", parameters: nil)
        if self.progressView?.superview == nil {
            self.view.addSubview(self.progressView!)
        }
        //还未处理完毕...
        self.progressView?.resetUI()
        self.progressView?.isHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setNavgationBarColor(color: UIColor.clear)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        let sec:TimeInterval = ZZHHelper.getSecFromUserDefaultByKey(kNowTimeToUserDefaultKey_PhotoTransformController)
        Analytics.logEvent("transcode_pic_pv", parameters: ["refer_page":"图片转码页面","duration":sec])
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ZZHHelper.setNowTimeToUserDefaultWithKey(kNowTimeToUserDefaultKey_PhotoTransformController)
        self.view.backgroundColor = UIColor.black
        self.navLine?.isHidden = true
        self.setNavgaionTitle(string: NSLocalizedString("图片转码", comment: ""))
        
        //393*236
        mTopImgView = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_Width, height: SCREEN_Height * 236/393))
        view.addSubview(mTopImgView!)
        mTopImgView?.image = UIImage.init(named: "BG_Top")
        self.view.bringSubviewToFront(self.navtionBar!)
        
        
        //345*200
        mImgView = UIImageView()
        mImgView?.frame = CGRect(x: 24, y: Int(SafeAreaTop_Height) + 24, width: Int(SCREEN_Width) - 48, height: (Int(SCREEN_Width) - 48) * 200/345)
        self.view.addSubview(mImgView!)
//        mImgView?.backgroundColor = UIColor.hexStringToColor(hexString: "#666666")
        mImgView!.clipsToBounds = true
        mImgView!.layer.cornerRadius = 8
        mImgView!.contentMode = .scaleAspectFit
        mImgView!.backgroundColor = UIColor.clear
        outputImageURL = URL.documentsDirectory.appending(path:"output11114.jpg")
        
        if (sourceImageURL != nil) {
            
            let nsdata = NSData(contentsOf: sourceImageURL!)
            sourceImageData = nsdata as? Data
            mImgView?.image = UIImage(data: sourceImageData!)
            
            //            let isSpatial = isSpatialImage(imageURL: sourceImageURL!)
            let isSpatial = isSpatialImage(originalData: sourceImageData!)
            if !isSpatial {
                print("这不是一张空间图片")
            }
            
        }else if (sourceImageData != nil) {
            
            //            let path = Bundle.main.path(forResource: "img3", ofType: "HEIC")
            //            sourceImageURL = URL.init(filePath: path!)
            //            let nsdata = NSData(contentsOf: sourceImageURL!)
            //            sourceImageData = nsdata as? Data
            mImgView?.image = UIImage(data: sourceImageData!)
            //            let isSpatial = isSpatialImage(imageURL: sourceImageURL!)
            let isSpatial = isSpatialImage(originalData: sourceImageData!)
            if !isSpatial {
                print("这不是一张空间图片")
                return
            }
        }
        let imgWidth:CGFloat = mImgView?.image?.size.width ?? 0.0
        let imgHeight:CGFloat = mImgView?.image?.size.height ?? 0.0
        let imgSize:Int = sourceImageData?.count ?? 0
        // size 表示数据的大小，单位为字节
        let imgMbSize = Double(imgSize) / 1024 / 1024
        
        
        
        
        
        
        
        
        
        mBottomBtn = UIButton.init(type: UIButton.ButtonType.custom)
        self.view.addSubview(mBottomBtn!)
        mBottomBtn!.backgroundColor = UIColor.hexStringToColor(hexString: "#5326D6")
        mBottomBtn?.tag = 10
        mBottomBtn?.isSelected = false
        mBottomBtn?.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        mBottomBtn?.frame = CGRect(x: 24, y: 10, width: SCREEN_Width - 48, height: 54)
        mBottomBtn!.bottom = SCREEN_Height - SafeAreaBottom_Height - 30
        mBottomBtn!.clipsToBounds = true
        mBottomBtn!.layer.cornerRadius = 8
        mBottomBtn!.setTitle(NSLocalizedString("转码导出", comment: ""), for: UIControl.State.normal)
        mBottomBtn!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        mBottomBtn!.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        
        
        mCenView = UIView()
        self.view.addSubview(mCenView!)
        mCenView?.frame = CGRect(x: 24, y: Int(mImgView!.bottom) + 16, width: Int(SCREEN_Width) - 48, height: 70)
        mCenView?.clipsToBounds = true
        mCenView?.layer.cornerRadius = 12
        mCenView?.backgroundColor = UIColor.colorWithRGB(_r: 18, _g: 7, _b: 68)
        
        mCenLab1 = UILabel()
        mCenLab1!.bounds = CGRect(x: 0, y: 0, width: 200, height: 0)
        mCenLab1!.textColor = UIColor.hexStringToColor(hexString: "#ffffff")
        mCenLab1!.font = UIFont.systemFont(ofSize: 14)
        mCenView!.addSubview(mCenLab1!)
        mCenLab1!.text = "--"
        mCenLab1!.sizeToFit()
        if(mCenLab1!.width > mCenView!.width - 140){
            mCenLab1!.width = mCenView!.width - 140
        }
        mCenLab1!.top = 12
        mCenLab1!.left = 16
        imageAsset?.requestContentEditingInput(with: nil) { [self] (contentEditingInput, info) in
            guard let contentEditingInput = contentEditingInput else {
                return
            }

            let fileName = contentEditingInput.fullSizeImageURL?.lastPathComponent
            mCenLab1!.text = fileName
            mCenLab1!.sizeToFit()
        }
        
        mCenLab2 = UILabel()
        mCenLab2!.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
        mCenLab2!.textColor = UIColor.hexStringToColor(hexString: "#67617A")
        mCenLab2!.font = UIFont.systemFont(ofSize: 12)
        mCenView!.addSubview(mCenLab2!)
        mCenLab2!.text = String(format: "%.f x %.f · %.1f MB",imgWidth,imgHeight,imgMbSize)
        mCenLab2!.sizeToFit()
        if(mCenLab2!.width > mCenView!.width - 140){
            mCenLab2!.width = mCenView!.width - 140
        }
        mCenLab2!.top = 38
        mCenLab2!.left = 16
        
        mCenBtn = UIButton.init(type: UIButton.ButtonType.custom)
        mCenView!.addSubview(mCenBtn!)
        mCenBtn!.backgroundColor = UIColor.hexStringToColor(hexString: "#5326D6")
        mCenBtn?.tag = 11
        mCenBtn?.isSelected = false
        mCenBtn?.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        mCenBtn?.frame = CGRect(x: 24, y: 10, width: 84, height: 36)
        mCenBtn!.centerY = mCenView!.height * 0.5
        mCenBtn!.right = mCenView!.width - 16
        mCenBtn!.clipsToBounds = true
        mCenBtn!.layer.cornerRadius = 10
        mCenBtn!.setTitle("Spatial Photo", for: UIControl.State.normal)
        mCenBtn!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        mCenBtn!.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        
        
        mLabel = UILabel()
        mLabel!.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
        mLabel!.textColor = UIColor.hexStringToColor(hexString: "#6A696A")
        mLabel!.font = UIFont.systemFont(ofSize: 14)
        self.view.addSubview(mLabel!)
        mLabel!.text = NSLocalizedString("格式", comment: "")
        mLabel!.sizeToFit()
        mLabel!.top = mCenView!.bottom + 32
        mLabel!.left = 24
        
        let maxHi = mBottomBtn!.top - mCenView!.bottom - 110
        var hi = 62.0
        if(hi > maxHi){hi = maxHi}
        mTabView = CCSpatialPlayView.init(frame: CGRect(x: 24, y: mCenView!.bottom + 70, width: SCREEN_Width - 48, height: hi))
        self.view.addSubview(mTabView!)
        mTabView!.backgroundColor = UIColor.hexStringToColor(hexString: "#1F1E20")
        mTabView?.clipsToBounds = true
        mTabView?.layer.cornerRadius = 12
        mTabView?.mTableView?.isScrollEnabled = false
        mTabView?.handle = {dic in
            print(dic)
            self.selectedCellAction(dic)
        }
        
        setSpatialParametersListData()
    }
    
    func setSpatialParametersListData() {
        let popData = [
            (type:CCTransformParameterType.hsbs_3D,title:NSLocalizedString("3D 格式", comment: ""),name:"3D HSBS")]
        
        mTabView?.setSpatialParametersData(data: popData)
    }
    
    @objc public func navgationButtonClick2(sender:UIButton){
        //侧边栏
        if(sender.tag == 10){
            
            //转码
            //            let isSpatial = isSpatialImage(imageURL: sourceImageURL!)
            let isSpatial = isSpatialImage(originalData: sourceImageData!)
            if !isSpatial {
                print("")
                return SVProgressHUD.showInfo(withStatus: NSLocalizedString("这不是一张空间图片,无法进行转码", comment: ""))
            }
            showProgress()
            DispatchQueue.main.async {
                self.progressView?.updateProgress(value: 1)
                Analytics.logEvent("result_pv", parameters: nil)
            }
            
            //空间图片才能进行3D格式的转换，普通图片没有这些参数
            switch mTabView?.datas.first?.type {
            case .hsbs_3D:
                let result:UIImage = SpatialImageConvertor.convertToHSBS(imageData: sourceImageData!)!
                UIImageWriteToSavedPhotosAlbum(result, self, #selector(completeSaveImg(_:error:contextInfo:)), nil)
                break
            case .fsbs_3D:
                let result:UIImage = SpatialImageConvertor.convertToFSBS(imageData: sourceImageData!)!
                UIImageWriteToSavedPhotosAlbum(result, self, #selector(completeSaveImg(_:error:contextInfo:)), nil)
                break
            case .hou_3d:
                let result:UIImage = SpatialImageConvertor.convertToHOU(imageData: sourceImageData!)!
                UIImageWriteToSavedPhotosAlbum(result, self, #selector(completeSaveImg(_:error:contextInfo:)), nil)
                break
            case .fou_3D:
                let result:UIImage = SpatialImageConvertor.convertToFOU(imageData: sourceImageData!)!
                UIImageWriteToSavedPhotosAlbum(result, self, #selector(completeSaveImg(_:error:contextInfo:)), nil)
                break
                
            default:
                print("不执行...")
            }
            
        }else if(sender.tag == 11){
            
        }
    }
    
   
    @objc func completeSaveImg(_ image: UIImage, error: NSError?, contextInfo: UnsafeRawPointer?) {
        if let error = error {
            print("保存失败：\(error)")
            DispatchQueue.main.async {
                self.progressView?.updateInfo(title:NSLocalizedString( "导出相册失败", comment: ""), desc: NSLocalizedString("请查看相册权限", comment: ""))
            }
        } else {
            DispatchQueue.main.async {
                
                self.progressView?.updateProgress(value: 1)
                self.progressView?.updateInfo(title: NSLocalizedString("转码完成", comment: ""), desc: NSLocalizedString("导出内容已存储到相册中", comment: ""))
            }
        }
    }
    
    //MARK: - action
    func selectedCellAction(_ model:(type:CCTransformParameterType,title:String,name:String)) {
        
        let device = Device.current
        var alert = UIAlertController.init()
        if device.isPhone {
            alert = UIAlertController(title:nil, message: nil, preferredStyle: .actionSheet)
        }else{
            alert = UIAlertController(title:nil, message: nil, preferredStyle: .alert)
        }
        
        switch model.type {
        case .format3D:
            print("3D 格式")
       
        case .hsbs_3D ,.fsbs_3D,.hou_3d,.fou_3D:
            print("3D 格式")
            /*
             3D HSBS（半宽左右格式）
             3D FSBS（全款左右格式）
             3D HOU（半高上下格式）
             3D FOU（全高上下格式）
             */
            
            let action1 = UIAlertAction(title: NSLocalizedString("3D HSBS（半宽左右格式）", comment: "") , style: .default) { [self] (action:UIAlertAction)  in
                print("3D HSBS（半宽左右格式）")
                
                let popData = [
                    (type:CCTransformParameterType.hsbs_3D,title:NSLocalizedString("3D 格式", comment: ""),name:"3D HSBS")]
                mTabView?.setSpatialParametersData(data: popData)
            }
            let action2 = UIAlertAction(title: NSLocalizedString("3D FSBS（全宽左右格式）", comment: "") , style: .default) { [self] (action:UIAlertAction) in
                print("3D FSBS（全宽左右格式）")
                let popData = [
                    (type:CCTransformParameterType.fsbs_3D,title:NSLocalizedString("3D 格式", comment: ""),name:"3D FSBS")]
                mTabView?.setSpatialParametersData(data: popData)
            }
            let action3 = UIAlertAction(title: NSLocalizedString("3D HOU（半高上下格式）" , comment: ""), style: .default) { [self] (action:UIAlertAction) in
                print("3D HOU（半高上下格式）")
                let popData = [
                    (type:CCTransformParameterType.hou_3d,title:NSLocalizedString("3D 格式", comment: ""),name:"3D HOU")]
                mTabView?.setSpatialParametersData(data: popData)
            }
            let action4 = UIAlertAction(title: NSLocalizedString("3D FOU（全高上下格式）", comment: "") , style: .default) { [self] (action:UIAlertAction) in
                print("3D FOU（全高上下格式）")
                let popData = [
                    (type:CCTransformParameterType.fou_3D,title:NSLocalizedString("3D 格式", comment: ""),name:"3D FOU")]
                mTabView?.setSpatialParametersData(data: popData)
            }
            
            
            let cancelAction = UIAlertAction(title: NSLocalizedString("取消", comment: ""), style: .cancel, handler: nil)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.addAction(action3)
            alert.addAction(action4)
            alert.addAction(cancelAction)
            self.present(alert, animated: true, completion: nil)
            
            break
        default:
            print("未知的媒体类型")
            break
        }
        
        
        
        
        
    }
    
    //判断是不是空间照片 非空间照片只有一帧
    //空间照片包含 let makerAppleProperties = imageProperties["{HEIF}"]
    func isSpatialImage(originalData: Data) -> Bool {
        
        //通过data获取
        guard let imageSource = CGImageSourceCreateWithData(originalData as CFData, nil) else {
            return false
        }
        //    func isSpatialImage(imageURL: URL) -> Bool {
        //通过url获取
        //        guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, nil) else {
        //            return false
        //        }
        guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 1, nil) as? [CFString: Any] else {
            return false
        }
        print(properties)
        /*
         [ProfileName: sRGB IEC61966-2.1, {TIFF}: {
         Orientation = 1;
         TileLength = 512;
         TileWidth = 512;
         }, PixelWidth: 4032, PixelHeight: 3024, {HEIF}: {
         CameraExtrinsics =     {
         CoordinateSystemID = 0;
         Position =         (
         "-0.019238",
         0,
         0
         );
         Rotation =         (
         1,
         0,
         0,
         0,
         1,
         0,
         0,
         0,
         1
         );
         };
         }, Depth: 8, Orientation: 1, ColorModel: RGB]
         
         
         判断是否包含：{HEIF} 代表空间图片
         
         */
        
        //这里判断两张图片，gif也可能是两张
        //        let frameCount = CGImageSourceGetCount(imageSource)
        //        if(frameCount == 1){
        //            return false
        //        }
        return true
    }
    
    
   
}
