//
//  SHInputController.swift
//  ShorthandMaster
//
//  Created by 张哲 on 2020/9/24.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit
import Photos

class SHInputController: SHBaseViewController
{
    // MARK: - property
    /// 文件夹model
    var folderModel : SHRecordFolderModel!
    
    /// 保存成功回调
    var saveSuccessCallBack:((SHRecordFolderModel)->Void)?
    
    /// 存储数据的model
    var dataModel: SHRecordModel = SHRecordModel()
    
    /// 未填写标题时的默认标题
    private let defaultTitle: String = "新建笔记"
    
    private var shInputView: SHInputView!
    
    private let recorder_mp3: SHMp3RecordManager = SHMp3RecordManager.shared()
    
    // MARK: -
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white

        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy年MM月dd日"
        self.title = dateFormatter.string(from: date)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "record_nav_confirm")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(didSelectedNavRightButton))
        
        self.addSubviews()
        
        self.setUpSubviewsLocation()
    }
    
    // MARK: - UI
    func addSubviews()
    {
        self.shInputView = SHInputView.init()
        self.shInputView.textView.delegate = self;
        self.shInputView.textView.shDelegate = self;
        self.view.addSubview(self.shInputView!)
        
        // 添加点击事件
        self.shInputView.bottomView.imageButton.addTarget(self, action: #selector(didSelectedImageButton(sender:)), for: UIControl.Event.touchUpInside)
        self.shInputView.bottomView.addAudioButton.addTarget(self, action: #selector(didSelectedAddAudioButton(sender:)), for: UIControl.Event.touchUpInside)
        self.shInputView.bottomView.pauseAudioButton.addTarget(self, action: #selector(didSelectedPauseAudioButton(sender:)), for: UIControl.Event.touchUpInside)
        self.shInputView.bottomView.goOnAudioButton.addTarget(self, action: #selector(didSelectedGoOnAudioButton(sender:)), for: UIControl.Event.touchUpInside)
        self.shInputView.bottomView.stopAudioButton.addTarget(self, action: #selector(didSelectedStopAudioButton(sender:)), for: UIControl.Event.touchUpInside)
        self.shInputView.bottomView.keyboardButton.addTarget(self, action: #selector(didSelectedKeyboardButton(sender:)), for: UIControl.Event.touchUpInside)
    
        // 有记录显示记录
        if dataModel.rename.length > 0
        {
            self.shInputView.placeholder.isHidden = true

            let attributeString : NSMutableAttributedString = NSMutableAttributedString()

            let titleString = NSAttributedString(string: self.dataModel.rename, attributes: (SHInputViewModel.titleAttributes() as! [NSAttributedString.Key : Any]))
            attributeString.append(titleString)

            let contentString = NSAttributedString(string: self.dataModel.txt, attributes: SHInputViewModel.contentAttributes() as? [NSAttributedString.Key : Any])
            attributeString.append(contentString)

            let imagesPath : Array = self.dataModel.imagesPath
            let imagesIndex : Array = self.dataModel.imagesIndex
            
            var i = 0
            
            for imagePath : String in imagesPath
            {
                let image : UIImage = UIImage(contentsOfFile: DocumentPath + imagePath) ?? UIImage()
                
                // 调整图片大小, 宽相同, 高随比例变化
                let newWidth = kScreenWidth - 20 * 2
                let newHeight = newWidth * image.size.height / image.size.width
                let newSize = CGSize(width: newWidth, height: newHeight)

                let imageLocation : Int = imagesIndex[i]


                let attachment = NSTextAttachment.init()
                attachment.image = image
                attachment.bounds = CGRect(origin: CGPoint.zero, size: newSize)
                let imageString = NSMutableAttributedString(attachment: attachment)

                // 设置图片文字属性
                imageString.addAttributes((SHInputViewModel.contentAttributes() as? [NSAttributedString.Key : Any])!, range: NSRange(location: 0, length: imageString.length))
                // 设置图片间距
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.lineSpacing = 18
                imageString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: imageString.length))

                attributeString.insert(imageString, at: imageLocation)
                
                i += 1
            }

            self.shInputView.textView.attributedText = attributeString
        }
        else
        {
            // 默认文字样式
            self.shInputView.textView.typingAttributes = SHInputViewModel.titleAttributes() as! [NSAttributedString.Key : Any]
        }
    }
    
    // MARK: 设置控件位置
    func setUpSubviewsLocation()
    {
        self.shInputView?.mas_makeConstraints({ (make) in
            
            make?.top.left()?.right()?.bottom()?.mas_equalTo()(0);
            
        })
    }
    
    // MARK: - Events
    // MARK: 点击navigationBar左侧按钮
    override func goback()
    {
        self.navigationController?.popViewController(animated: true)
        
        UserDefaults.standard.removeObject(forKey: "InputRecord")
    }
    
    // MARK: 点击navigationBar右侧按钮
    @objc func didSelectedNavRightButton()
    {
        self.dataModel.recordingType = 1
        
        self.dataModel.createDate = Date()
        self.dataModel.modifyDate = Date()
        
        let imageArray = SHInputViewModel.setUpImageArrayWithTextView(textView: self.shInputView.textView)
        
        self.dataModel.imagesPath = imageArray.imagesPathArray
        self.dataModel.imagesIndex = imageArray.imagesIndexArray
        
        if self.dataModel.rename.length == 0
        {
            self.dataModel.rename = defaultTitle
        }

        self.dataModel.txt = self.shInputView.textView.text.substring(self.dataModel.rename.length, length: self.shInputView.textView.text.length - self.dataModel.rename.length)!

        
        // 保存到沙盒
        var recordList = CRUserDefaults.recordList
        
        var i = 0;
//        var folderModel = SHRecordFolderModel()
        
        for dict in recordList!
        {
            var model = SHRecordFolderModel()
            model = getDataDictWith(dict: dict)
            
            if model.id == self.folderModel.id
            {
                model.dataSources.append(self.dataModel)
                
                self.folderModel = model
                
                break
            }
            
            i += 1
        }
        
        recordList![i] = getDictWith(obj: self.folderModel!)
        
        CRUserDefaults.recordList = recordList
        
        self.saveSuccessCallBack?(self.folderModel)
        
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: 点击键盘按钮
    @objc func didSelectedKeyboardButton(sender : UIButton)
    {
        if self.shInputView.textView.isFirstResponder
        {
            self.shInputView.textView.resignFirstResponder()
        }
        else
        {
            self.shInputView.textView.becomeFirstResponder()
        }
    }
}

// MARK: - 输入框
extension SHInputController: UITextViewDelegate, SHInputTextViewDelegate
{
    // MARK: - UITextView代理
    // MARK: 文字发生了变化
    func textViewDidChange(_ textView: UITextView)
    {
        self.shInputView.placeholder.isHidden = textView.text.length > 0
    }
    
    // MARK: 文字将要变化
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
    {
        // 获取标题文字位置
        let titleRange = NSRange(location: 0, length: self.dataModel.rename.length)
        
        // 在标题位置输入的内容为标题
        if range.location <= titleRange.location + titleRange.length
        {
            // 使用标题字体
            textView.typingAttributes = SHInputViewModel.titleAttributes() as! [NSAttributedString.Key : Any]
            
            // 输入换行符即表示标题输入完成
            if (text.isEqualTo("\n"))
            {
                // 开始输入内容字体
                textView.typingAttributes = SHInputViewModel.contentAttributes() as! [NSAttributedString.Key : Any]
            }
            else
            {
                // 把将要添加的文字加到输入框文字中
                let textViewString : NSMutableString = NSMutableString(string: textView.text)
                textViewString.insert(text, at: range.location)
                
                // 保存标题文字
                self.dataModel.rename = textViewString.substring(with: NSRange(location: 0, length: range.location + text.length))
            }
        }
        else
        {
            // 使用内容字体
            textView.typingAttributes = SHInputViewModel.contentAttributes() as! [NSAttributedString.Key : Any]
        }
        
        return true
    }
    
    // MARK: 光标位置发生变化
    func textViewDidChangeSelection(_ textView: UITextView) {
        
        print(textView.selectedRange)
        
    }
    
    // MARK: - SHInputTextView代理
    // MARK: 点击删除按钮
    func textViewDidDelete(textView: SHInputTextView)
    {
        
    }
    
    func testIFCANFIND()
    {
        
    }
}


// MARK: - 图片选择器
extension SHInputController: UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    // MARK: - 代理方法
    // MARK: 选中了一张照片/拍了一张照片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if (info[UIImagePickerController.InfoKey.originalImage] != nil)
        {
            let image : UIImage = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage)!
            
            self.insertImageInTextView(image: image)
            
            picker.dismiss(animated: true, completion: nil)
        }
        else
        {
            let imageAssetUrl : URL = info[UIImagePickerController.InfoKey.referenceURL] as! URL
            
            let result : PHFetchResult = PHAsset.fetchAssets(withALAssetURLs: [imageAssetUrl], options: nil)
            
            let asset : PHAsset = result.firstObject!
            
            let options = PHImageRequestOptions()
            options.isNetworkAccessAllowed = true
            
            weak var weakSelf = self
            
            PHImageManager.default().requestImageData(for: asset, options: options) { (imageData, dataUTI, orientation, info) in
                
                if imageData != nil
                {
                    let image : UIImage = UIImage(data: imageData!)!
                    weakSelf?.insertImageInTextView(image: image)
                    
                    picker.dismiss(animated: true, completion: nil)
                }
                
            }
            
            
        }
    }
    
    // MARK: 取消选择照片/取消拍照
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        picker.dismiss(animated: true, completion: nil)
        
    }
    
    // MARK: - 输入框中插入图片方法
    func insertImageInTextView(image : UIImage)
    {
        // 调整图片大小, 宽相同, 高随比例变化
        let newWidth = kScreenWidth - 20 * 2
        let newHeight = newWidth * image.size.height / image.size.width
        let newSize = CGSize(width: newWidth, height: newHeight)
        
        
        // 如果没有标题添加默认标题
        if self.dataModel.rename.length == 0
        {
            // 标题
            let titleString = NSMutableAttributedString(string: self.defaultTitle, attributes: (SHInputViewModel.titleAttributes() as! [NSAttributedString.Key : Any]))
            self.shInputView.textView.attributedText = titleString

            self.shInputView.placeholder.isHidden = true

            self.dataModel.rename = titleString.string
        }
        
        // 如果占位文字未隐藏, 隐藏占位文字
        self.shInputView.placeholder.isHidden = true
        
        // 前文
        let textString = NSMutableAttributedString(attributedString: self.shInputView.textView.attributedText)
        
        // 图片
        let attachment = NSTextAttachment.init()
        attachment.image = image
        attachment.bounds = CGRect(origin: CGPoint.zero, size: newSize)
        let imageString = NSMutableAttributedString(attachment: attachment)
        
        // 设置图片文字属性
        imageString.addAttributes((SHInputViewModel.contentAttributes() as? [NSAttributedString.Key : Any])!, range: NSRange(location: 0, length: imageString.length))
        // 设置图片间距
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 18
        imageString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: imageString.length))
        
        // 图片前后增加换行符
        // 如果前文以换行符结尾, 图片前面不再加换行符
        if !textString.string.hasSuffix("\n")
        {
            imageString.insert(NSAttributedString(string: "\n", attributes: (SHInputViewModel.contentAttributes() as! [NSAttributedString.Key : Any])), at: 0)
        }
        imageString.insert(NSAttributedString(string: "\n", attributes: (SHInputViewModel.contentAttributes() as! [NSAttributedString.Key : Any])), at: imageString.length)
        
        // 合并内容
        textString.insert(imageString, at: self.shInputView.textView.selectedRange.location)
        
        self.shInputView.textView.attributedText = textString
        
        // 使用内容字体
        self.shInputView.textView.typingAttributes = SHInputViewModel.contentAttributes() as! [NSAttributedString.Key : Any]
    }
    
    // MARK: - Events
    // MARK: 点击选择图片按钮
    @objc func didSelectedImageButton(sender : UIButton)
    {
        if self.shInputView.textView.canResignFirstResponder
        {
            self.shInputView.textView.resignFirstResponder()
        }
        
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
        
        weak var weakSelf = self
        
        let albumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (action) in
            
            weakSelf?.openAlbum()
            
        }
        alert.addAction(albumAction)
        
        let cameraAction = UIAlertAction(title: "相机", style: UIAlertAction.Style.default) { (action) in
            
            weakSelf?.openCamera()
            
        }
        alert.addAction(cameraAction)
        
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel , handler: nil)
        alert.addAction(cancelAction)
        
        
        
        self.present(alert, animated: true, completion: nil)
    }
    
    // MARK: 打开相册, 判断相册权限
    func openAlbum()
    {
        let status : PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        
        switch status
        {
        // MARK: 此应用程序没有被授权访问的照片数据。可能是家长控制权限
        case PHAuthorizationStatus.restricted:
            let alert = UIAlertController(title: nil, message: "此应用程序没有被授权访问的照片数据。可能是家长控制权限", preferredStyle: UIAlertController.Style.alert)
            
            let sureAction = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: nil)
            alert.addAction(sureAction)
            
            self.present(alert, animated: true, completion: nil)
            
            break
        // MARK: 用户拒绝访问相册
        case PHAuthorizationStatus.denied:
            let alert = UIAlertController(title: "此功能需要相册授权", message: "请您在设置系统中打开授权开关", preferredStyle: UIAlertController.Style.alert)
            
            let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: nil)
            alert.addAction(cancelAction)
            
            let settingAction = UIAlertAction(title: "前往设置", style: UIAlertAction.Style.default) { (action) in
                
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
                
            }
            alert.addAction(settingAction)
            
            
            self.present(alert, animated: true, completion: nil)
            
            break
        // MARK: 用户允许访问相册
        case PHAuthorizationStatus.authorized:
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary)
            {
                self.showAlbum()
            }
            break
        // MARK: 用户还没有做出选择
        case PHAuthorizationStatus.notDetermined:
            weak var weakSelf = self
            
            PHPhotoLibrary.requestAuthorization { (status) in
                
                if status == PHAuthorizationStatus.authorized
                {
                    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary)
                    {
                        weakSelf?.showAlbum()
                    }
                }

            }
            break
        default:
            break
        }
    }
    
    // MARK: 显示相册
    func showAlbum()
    {
        DispatchQueue.main.async
        {
            let imagePickerController = UIImagePickerController()
            imagePickerController.sourceType = UIImagePickerController.SourceType.photoLibrary
            imagePickerController.delegate = self
            imagePickerController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
            self.present(imagePickerController, animated: true, completion: nil)
        }
    }
    
    // MARK: 打开相机, 判断相机权限
    func openCamera()
    {
        let device : AVCaptureDevice? = AVCaptureDevice.default(for: AVMediaType.video)
        
        if device != nil
        {
            let status : AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
            switch status
            {
            // MARK: 此应用程序没有被授权访问的照片数据。可能是家长控制权限。
            case AVAuthorizationStatus.restricted:
                let alert = UIAlertController(title: nil, message: "此应用程序没有被授权访问的相机数据。可能是家长控制权限。", preferredStyle: UIAlertController.Style.alert)
                
                let sureAction = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: nil)
                alert.addAction(sureAction)
                
                self.present(alert, animated: true, completion: nil)
                
                break
            // MARK: 用户拒绝当前应用访问相机
            case AVAuthorizationStatus.denied:
                let alert = UIAlertController(title: "此功能需要相机授权", message: "请您在设置系统中打开授权开关", preferredStyle: UIAlertController.Style.alert)
                
                let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: nil)
                alert.addAction(cancelAction)
                
                let settingAction = UIAlertAction(title: "前往设置", style: UIAlertAction.Style.default) { (action) in
                    
                    UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
                    
                }
                alert.addAction(settingAction)
                
                
                self.present(alert, animated: true, completion: nil)
                
                break
            // MARK: 用户允许当前应用访问相机
            case AVAuthorizationStatus.authorized:
                if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)
                {
                    self.showCamera()
                }
                break
            // MARK: 用户还没有做出选择
            case AVAuthorizationStatus.notDetermined:
                weak var weakSelf = self
                
                PHPhotoLibrary.requestAuthorization { (status) in
                    
                    if status == PHAuthorizationStatus.authorized
                    {
                        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)
                        {
                            weakSelf?.showCamera()
                        }
                    }

                }
                break
            default:
                break
            }
            
        }
        else
        {
            self.openAlbum()
        }
        
    }
    
    // MARK: 显示相机
    func showCamera()
    {
        DispatchQueue.main.async {
            
            let imagePickerController = UIImagePickerController()
            imagePickerController.sourceType = UIImagePickerController.SourceType.camera
            imagePickerController.delegate = self
            imagePickerController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
            self.present(imagePickerController, animated: true, completion: nil)
            
        }
    }
}

// MARK: - 录音
extension SHInputController
{
    // MARK: 点击添加录音按钮
    @objc func didSelectedAddAudioButton(sender : SHInputAudioButton)
    {
        self.shInputView.bottomView.addAudioButton.isHidden = true
        self.shInputView.bottomView.pauseAudioButton.isHidden = false
        self.shInputView.bottomView.goOnAudioButton.isHidden = true
        self.shInputView.bottomView.stopAudioButton.isHidden = false
        
        let mp3Path : String = DocumentPath + "/recorder.mp3"
        let pcmPath : String = DocumentPath + "/xbMixData.caf"
        
        
        recorder_mp3.configMp3Path(mp3Path, pcmPath: pcmPath)
        recorder_mp3.start()
        
        print("mp3Path" + mp3Path)
        print("pcmPath" + pcmPath)
        
    }
    
    // MARK: 点击暂停录音按钮
    @objc func didSelectedPauseAudioButton(sender : SHInputAudioButton)
    {
        self.shInputView.bottomView.addAudioButton.isHidden = true
        self.shInputView.bottomView.pauseAudioButton.isHidden = true
        self.shInputView.bottomView.goOnAudioButton.isHidden = false
        self.shInputView.bottomView.stopAudioButton.isHidden = false
        
        recorder_mp3.pause()
        
        let mp3Path : String = DocumentPath + "/recorder.mp3"
        let pcmPath : String = DocumentPath + "/xbMixData.caf"
        
        print("mp3Path" + mp3Path)
        print("pcmPath" + pcmPath)
    }
    
    // MARK: 点击继续录音按钮
    @objc func didSelectedGoOnAudioButton(sender : SHInputAudioButton)
    {
        self.shInputView.bottomView.addAudioButton.isHidden = true
        self.shInputView.bottomView.pauseAudioButton.isHidden = false
        self.shInputView.bottomView.goOnAudioButton.isHidden = true
        self.shInputView.bottomView.stopAudioButton.isHidden = false
        
        recorder_mp3.start()
        
        let mp3Path : String = DocumentPath + "/recorder.mp3"
        let pcmPath : String = DocumentPath + "/xbMixData.caf"
        
        print("mp3Path" + mp3Path)
        print("pcmPath" + pcmPath)
    }
    
    // MARK: 点击结束录制按钮
    @objc func didSelectedStopAudioButton(sender : SHInputAudioButton)
    {
        self.shInputView.bottomView.addAudioButton.isHidden = false
        self.shInputView.bottomView.pauseAudioButton.isHidden = true
        self.shInputView.bottomView.goOnAudioButton.isHidden = true
        self.shInputView.bottomView.stopAudioButton.isHidden = true
        
        recorder_mp3.stop()
        
        let mp3Path : String = DocumentPath + "/recorder.mp3"
        let pcmPath : String = DocumentPath + "/xbMixData.caf"
        
        print("mp3Path" + mp3Path)
        print("pcmPath" + pcmPath)
    }
}
