//
//  CCSpatialPhotoDisplayEx.swift
//  SwiftProject
//
//  Created by aaa on 2024/4/28.
//

import Foundation
import UIKit

extension CCSpatialPhotoDisplayController {
    //点击了player 的maskview
    @objc func tapPlayerMaskView(sender:UITapGestureRecognizer)  {
        if isLandscape {
//            if let mcallback = maskViewTapCallback {
//                mcallback()
//            }
//            self.timeSlider?.isHidden = !self.timeSlider!.isHidden
//            self.edBtn?.isHidden = !self.edBtn!.isHidden
            self.navtionBar?.isHidden = !((self.navtionBar?.isHidden)!)
            edBtn?.isHidden = !((edBtn?.isHidden)!)
        }
        
    }
    
    //缩放手势 正在player的maskview进行缩放
    @objc func pinchPlayerMaskView(sender:UIPinchGestureRecognizer) {
        if sender.state == .began {
            temScale = 1.0
        }
        var ctemS = currentScale - (temScale - sender.scale)
        if abs(currentScale - ctemS) < 0.1 {
            return
        }
        //currentScale - (temScale - sender.scale)
        ctemS = min(ctemS, 1.8)
        ctemS = max(ctemS, 0.3)
        currentScale = ctemS
        temScale = sender.scale
        print("\(sender.scale)    currentScale....\(currentScale)")
    }
    
    @objc func showEDView(sender:UIButton) {
        print("showedview....")
        self.tipsButton.isHidden = true
        CustomParamBoardView.showBoard(scaleCallback: {[weak self] scale in
            self?.currentScale = scale
        }, edCallback: {[weak self] ed in
            self?.currentED = ed
        },resetCallback:{[weak self] in
            self?.currentScale = 1.0
            self?.currentED = 0
        }, dismissCallback:{[weak self] in
            self?.saveParams()
            self?.tipsButton.isHidden = false
        },scale: currentScale, ed: currentED,canChangeED: isPlayingOnExternalScreen)
        
    }
    
    func saveParams(){
        UserDefaults.standard.setValue(currentScale, forKey: userdefaultValueKey_scale )
        UserDefaults.standard.setValue(currentED, forKey: userdefaultValueKey_ed)
        UserDefaults.standard.synchronize()
    }
    
    //单眼2D
    func monocular2DImgWith(drawImg:UIImage,scale:CGFloat, callback:@escaping (_ image:UIImage)->Void) {
        if scale > 1 || scale < 1 {
//            DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async {
                let drawImageSize = drawImg.size
                let newImgSize = CGSizeMake(drawImageSize.width * scale, drawImageSize.height * scale)
                let newRect = CGRect(origin: CGPoint(x: (drawImageSize.width - newImgSize.width) * 0.5, y: (drawImageSize.height - newImgSize.height) * 0.5), size: newImgSize)
                UIGraphicsBeginImageContextWithOptions(drawImageSize, false, 1);
                drawImg.draw(in: newRect)
                let image = UIGraphicsGetImageFromCurrentImageContext()!
                UIGraphicsEndImageContext();
//                DispatchQueue.main.async {
                    callback(image)
//                }
//            }
        }
        else {
            callback(drawImg)
        }
    }
    
    
    
    
    //合成红蓝立体图片
    func joinImages_red_blue(lciImage:CIImage,rciImage:CIImage,scale: CGFloat,rbImage:UIImage?) -> UIImage {
        var lastImg:UIImage? = rbImage
        if lastImg == nil {
            // 创建红色和蓝色滤镜
            let redColorMatrix: [CGFloat] = [
                0.0, 0.0, 0.0, 0.0, 0.0, // 红色通道
                0.0, 0.0, 0.0, 0.0, 0.0, // 绿色通道
                0.0, 0.0, 1.0, 0.0, 0.0, // 蓝色通道
                0.0, 0.0, 0.0, 1.0, 0.0  // 透明通道
            ]
            
            let blueColorMatrix: [CGFloat] = [
                1.0, 0.0, 0.0, 0.0, 0.0, // 红色通道
                0.0, 0.0, 0.0, 0.0, 0.0, // 绿色通道
                0.0, 0.0, 0.0, 0.0, 0.0, // 蓝色通道
                0.0, 0.0, 0.0, 1.0, 0.0  // 透明通道
            ]

            let redFilter = CIFilter(name: "CIColorMatrix")!
            redFilter.setValue(lciImage, forKey: kCIInputImageKey)
            redFilter.setValue(CIVector(values: redColorMatrix, count: redColorMatrix.count), forKey: "inputRVector")
            
            let blueFilter = CIFilter(name: "CIColorMatrix")!
            blueFilter.setValue(rciImage, forKey: kCIInputImageKey)
            blueFilter.setValue(CIVector(values: blueColorMatrix, count: blueColorMatrix.count), forKey: "inputBVector")
            
            // 获取处理后的图像
            if let redOutputImage = redFilter.outputImage,
               let blueOutputImage = blueFilter.outputImage {
                
                let compositeFilter = CIFilter(name: "CIScreenBlendMode")!
                compositeFilter.setValue(redOutputImage, forKey: kCIInputImageKey)
                compositeFilter.setValue(blueOutputImage, forKey: kCIInputBackgroundImageKey)
                
                let sharpenedFilter = CIFilter(name: "CISharpenLuminance")!
                sharpenedFilter.setValue(compositeFilter.outputImage, forKey: kCIInputImageKey)
                sharpenedFilter.setValue(2, forKey: kCIInputSharpnessKey)
                lastImg = UIImage(ciImage: sharpenedFilter.outputImage! )
            }
        }
        
        if scale == 1 {
            return lastImg!
        }
        else {
            let drawImg = lastImg!
            let drawImageSize = drawImg.size
            let newImgSize = CGSizeMake(drawImageSize.width * scale, drawImageSize.height * scale)
            let newRect = CGRect(origin: CGPoint(x: (drawImageSize.width - newImgSize.width) * 0.5, y: (drawImageSize.height - newImgSize.height) * 0.5), size: newImgSize)
            UIGraphicsBeginImageContextWithOptions(drawImageSize, false, 1);
            drawImg.draw(in: newRect)
            let image = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext();
            return image
        }
    }
    
    
    
    
    
    
    //平行眼、交叉眼
    func joinImages( leftImage:CIImage, rightImage:CIImage,scale:CGFloat,ed:Int) -> CIImage {
        
//缩放参数,此处必须大于0.5
//瞳距参数,暂定 瞳距与像素点的比例为1:2,瞳距的值范围为 -30 ~ +30 之间的整数
        let edS = 20 //比列
        
        var left =  UIImage(ciImage: leftImage )
//        left = left.getUpImg(imgOrigOritentation: imgOritentation)

        var right =  UIImage(ciImage: rightImage )
//        right = right.getUpImg(imgOrigOritentation: imgOritentation)

        //获取缩放图片
        let (n_left,n_left_size) = getImgWithScale(image: left, scale: scale)
        let (n_right,n_right_size) = getImgWithScale(image: right, scale: scale)

        //获取调整了瞳距的图片
        let x_offset = CGFloat(abs(ed) * edS) //关于瞳距的x偏移量
        let imageWidth = left.size.width*0.5 - x_offset
        let imageHeight = left.size.height
        let (ed_left,last_left_size) = getImgWithED(image: n_left, drawImgWidth: imageWidth,drawSize: n_left_size)
        let (ed_right,last_right_size) = getImgWithED(image: n_right, drawImgWidth: imageWidth,drawSize: n_right_size)
        let newImageSize = left.size
        UIGraphicsBeginImageContextWithOptions(newImageSize, false, 1)
        
        if (ed > 0) {//左视图宽度减小,同时x点的坐标值为0;右视图宽度减小,同时x点的坐标值增加
            ed_left.draw(in: CGRect(x:0, y:(imageHeight - last_left_size.height) * 0.5, width:last_left_size.width, height:last_left_size.height))
            ed_right.draw(in: CGRect(x:newImageSize.width - last_right_size.width, y:(imageHeight - last_right_size.height) * 0.5, width:last_right_size.width, height:last_right_size.height))
            
        }
        else if (ed  < 0) {
            ed_left.draw(in: CGRect(x:newImageSize.width*0.5 - last_left_size.width, y:(imageHeight - n_left_size.height) * 0.5, width:last_left_size.width, height:last_left_size.height))
            ed_right.draw(in: CGRect(x:newImageSize.width*0.5, y:(imageHeight - n_right_size.height) * 0.5, width:last_right_size.width, height:last_right_size.height))
        }
        else {//瞳距没有改变的情况
            let leftRect = CGRect(x:(imageWidth - n_left_size.width) * 0.5, y:(imageHeight - n_left_size.height) * 0.5 , width:n_left_size.width, height:n_left_size.height)
            ed_left.draw(in:leftRect )
            
            let rightRect = CGRect(x:imageWidth + (imageWidth - n_right_size.width) * 0.5 , y:(imageHeight - n_right_size.height) * 0.5, width:n_right_size.width, height:n_right_size.height)
            ed_right.draw(in:rightRect )
        }
        
        
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        
        let ci = CIImage(cgImage: image.cgImage!)
        return ci
    }
    
    //图像缩放 调整默认scale,默认值应当为1
    func getImgWithScale(image:UIImage,scale:CGFloat) -> (UIImage,CGSize) {
        //获取原始的rect
        let originSize = CGSize(width: image.size.width*0.5, height: image.size.height*0.5)
        
        var newImage = image
        var newSize = originSize//作图的区域
        
        if scale > 1 {//图片会被裁减,但size的宽度不会改变,而高度会随scale发生改变
           //计算放大图片需要用于截取图片的size,
            //本次height在画布上的增量
            let Hs_add = (image.size.height - image.size.height*0.5)*(scale - 1)
            //根据本次在画布上的增量height重新计算画布size
            newSize = CGSizeMake(originSize.width, originSize.height + Hs_add)

            //本次根据scale进行初步计算的裁剪区域size
            let cutSize = CGSizeMake((2 - scale)*(image.size.height * newSize.width/newSize.height),(2 - scale) * image.size.height)

            let cutRect = CGRectMake((image.size.width - cutSize.width)*0.5, (image.size.height - cutSize.height) * 0.5, cutSize.width, cutSize.height)
            newImage = image.imageAtRect(rect: cutRect)!
        }
        else if scale < 1 {//图片不会被裁减,但size会被缩小
            //计算被等比缩小的size
            newSize = CGSizeMake(scale*originSize.width, scale*originSize.height)
        }
        return (newImage,newSize)
    }
    
    //图像瞳距,参数条件必须满足:image能够等比缩放后填充满drawSize,即image的真实size与drawSize预期size并不要求一致,但要求等比
    func getImgWithED(image:UIImage,drawImgWidth:CGFloat,drawSize:CGSize) -> (UIImage,CGSize) {
        if drawSize.width <= drawImgWidth {
            
//            print("瞳距返回,不用处理")
            return (image,drawSize)
        }
//        print("瞳距要处理")
        let newImageWidth = drawImgWidth * image.size.height / drawSize.height
        let dRect = CGRectMake((image.size.width - newImageWidth)  * 0.5, 0, newImageWidth, image.size.height)
        let newImage = image.imageAtRect(rect: dRect)
        return (newImage!,CGSize(width: drawImgWidth, height: drawSize.height))
    }
   
}
