//
//  SHRecordViewController.swift
//  ShorthandMaster
//
//  Created by 明津李 on 2020/8/10.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit
import AVFoundation
import Speech
import PDFGenerator

class SHRecordViewController: SHBaseViewController{

    private var waveView = DDSoundWaveView()
    
    var folderModel: SHRecordFolderModel = SHRecordFolderModel()
    var saveSuccessCallBack:((SHRecordFolderModel)->Void)?
    
    @IBOutlet var recordTextView: UITextView!
    @IBOutlet var waveBgView: UIView!
    @IBOutlet var secondsLabel: UILabel!
    @IBOutlet var recorderBtn: UIButton!
    @IBOutlet var maskView: UIView!
    
    private var currentModel: SHRecordModel?
    private var currentTxt: String?
    private var currentAddress: String = ""
    
    private var start: Bool = false
    private var save: Bool = false
    
    private var secondTimer: SHTimer?
    private var seconds: NSInteger = 0
    private let non_member_limit_seconds: NSInteger = 60
    
    // mp3_url : 录音文件的路径
    var wav_file_path = DocumentPath.appending("/record.wav")
    var mp3_file_path = ""
    var pcm_file_path = ""
    
    var image_file_path = ""
    var image_file_paths: [String] = []
    var image_indexs: [NSInteger] = []

    var recorder_mp3: SHMp3RecordManager = SHMp3RecordManager.shared()
    var recorderManager =  SHAVAudioManager.shared
      
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        
        setupUI()
        configPathFile()
        
        recorderManager.decibelsCallBack = { decibels in
            self.waveView.displayWave(Double(decibels))
        }
        
        recorderManager.recoderResiltCallBack = { result in
            self.currentTxt = result
            self.recordTextView.attributedText = self.textView_text(self.currentTxt!)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(backGroundAlive), name: NSNotification.Name(rawValue: "recordAlive"), object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func backGroundAlive(){
        if recorderManager.state == .start{
            recorderManager.start()
        }
    }
    
    override func goback() {
        super.goback()
        saveContent()
        self.recorder_mp3.stop()
        self.recorderManager.stop()
        saveSuccessCallBack?(folderModel)
    }

    override func setupUI() {
        super.setupUI()
        
        self.view.bringSubviewToFront(maskView)
        self.view.bringSubviewToFront(recorderBtn)
        
        self.view.layoutIfNeeded()
        self.view.layoutSubviews()
    
        recordTextView?.attributedText = self.textView_text("")
        recordTextView?.textContainerInset = UIEdgeInsets.init(top: 20, left: 20, bottom: 20, right: 30)
        recordTextView?.isEditable = false
        
        waveView.frame = waveBgView.bounds
        waveBgView.addSubview(waveView)
        self.waveView.displayWave(Double(0))
        setNavTitleAndConfirmBtn()
    }
    
    func setNavTitleAndConfirmBtn(){
        
        let titleLab = UILabel()
        titleLab.frame = CGRect.init(x: 0, y: 0, width: 200, height: 44)
        titleLab.text = Date().format("yyyy年MM月dd日")
        titleLab.textColor = UIColor.init(r: 17, g: 17, b: 17)
        titleLab.font = UIFont.systemFont(ofSize: 16)
        titleLab.textAlignment = .center
        titleLab.adjustsFontSizeToFitWidth = true
        self.navigationItem.titleView = titleLab
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "record_nav_confirm"), style: .plain, target: self, action: #selector(confirmCilck))
        
        if CRUserDefaults.isFirstInstall == false{
            let guide = SHRecordGuideView.init(frame: UIApplication.shared.keyWindow!.bounds)
            UIApplication.shared.keyWindow!.addSubview(guide)
            CRUserDefaults.isFirstInstall = true
        }
    }
    
    @objc func confirmCilck(){
        
        if currentModel == nil {
            return
        }
        
//        if let model = currentModel {
//             self.removeCurrentRecored(model)
//        }
        
        self.recorderManager.stop()
        self.save = true
        self.saveContent()
        self.saveSuccessCallBack?(folderModel)
        self.timerInvalidate()
        self.recorder_mp3.stop()
        self.recorderManager.stop()
        
        let export = SHRecordExportAlertView.loadFromNibAndClass(SHRecordExportAlertView.self)!
        export.frame = UIApplication.shared.keyWindow!.bounds
        UIApplication.shared.keyWindow!.addSubview(export)
        export.selectedIndexCallBack = { index in
            if index == 0 {
                MBProgressHUD.showMessage("已复制文本内容", to: export)
                self.copyBtn()
            } else if index == 1{
                self.generatePDF()
            } else if index == 2{
                self.generateWav()
            } else if index == 404{
                if self.save == true {
                    self.currentTxt = ""
                    self.recorderBtn.setImage(UIImage.init(named: "record_start"), for: .normal)
                    self.recordTextView.attributedText = self.textView_text("")
                    self.configPathFile()
                    self.recorderBtn.isSelected = false
                    self.secondsLabel.text = "00:00:00"
                    self.seconds = 0
                    self.save = false
                }
                DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    @objc @IBAction func recordBtnClick(_ sender:UIButton){
        
        if seconds >= non_member_limit_seconds {
            let isMember = self.verityMember()
            if isMember == false {
                return
            }
        }
        
        sender.setImage(UIImage.init(named: "record_pause"), for: .normal)
        sender.isSelected = !sender.isSelected
        if sender.isSelected == true {
            
            SHLocationManager.shared.locationStatusService { (address) in
                self.currentAddress = address
                self.recordTextView.attributedText = self.textView_text(self.currentTxt ?? "")
            }
            
            self.view.sendSubviewToBack(maskView)
            self.recorderManager.start()
            self.recorder_mp3.start()
            self.start = true
            self.secondTimer = SHTimer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countSecond), userInfo: nil, repeats: true)

        }else{
            self.recorderManager.manualPause()
            self.recorder_mp3.pause()
            self.start = false
            self.timerInvalidate()
        }
    }
    
    func verityMember()->Bool{
        if SHUserAccountManager.shared.isMember == false{
            
            recorderBtn.isSelected = false
        
            self.recorderManager.manualPause()
            self.recorder_mp3.pause()
            self.start = false
            self.timerInvalidate()
            self.showMemberAlert()
        }
        return SHUserAccountManager.shared.isMember
    }
    
    func showMemberAlert(){
        let alert = SHMemberUpgradeAlertView.init()
        self.view.window?.addSubview(alert)
        alert.callBack = {
            self.goGoods("record_upgrade")
        }
    }
        
    private func configPathFile(){
        
        let fileManager = FileManager.default
        let fileArr = SHRecordViewController.getAllFilePath(DocumentPath)
        let subFile = Date().format("yyyyMMdd")
        var exist = false
        let time = Date.init().timeStamp
        
        for (_, documentsFile) in fileArr!.enumerated() {
         
            if documentsFile == DocumentPath.appending("/\(subFile)")  {

                let path = documentsFile.appending(time)
                mp3_file_path = "/"+subFile+time+RecordMp3
                pcm_file_path = "/"+subFile+time+RecordCaf
                
                image_file_path = "/"+subFile+time+"/"
   
                try! fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
                
                recorder_mp3.configMp3Path(DocumentPath+mp3_file_path, pcmPath: DocumentPath+pcm_file_path)
                
                exist = true
                break
            }
        }
        if exist == false {
            let path = (DocumentPath.appending("/\(subFile)").appending(time))

            mp3_file_path = "/"+subFile+time+RecordMp3
            pcm_file_path = "/"+subFile+time+RecordCaf
            
            image_file_path = "/"+subFile+time+"/"

            try! fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            
            recorder_mp3.configMp3Path(DocumentPath+mp3_file_path, pcmPath: DocumentPath+pcm_file_path)
        }
        
        NSLog("mp3_file_path=======\(String(describing: mp3_file_path))  pcm_file_path=======\(String(describing: pcm_file_path))")
    }
    
    func saveContent(){
        
        let nowDate = Date()
        let model = SHRecordModel()
        model.recordingType = 0
        model.createDate = nowDate
        model.modifyDate = nowDate
        model.address = (currentAddress.length != 0) ? currentAddress : "未知位置"
        model.rename = (currentAddress.length != 0) ? currentAddress : "未知位置"
        model.txt = "\n"+(currentTxt ?? "")
        model.pathFile = mp3_file_path
        model.pcmPathFile = pcm_file_path
        model.during = seconds
        
//        image_file_paths = []
//        image_indexs = []
//        let images = ["recordlist_no_data_search", "recordlist_no_data"]
//        for (index, imageStr) in images.enumerated(){
//            let image = UIImage.init(named: imageStr)
//            let filePath = DocumentPath+image_file_path+"\(index).jpeg"
//            let imageData = image!.jpegData(compressionQuality: 1)
//            try? imageData?.write(to: URL(fileURLWithPath: filePath))
//            image_file_paths.append(image_file_path+"\(index).jpeg")
//            image_indexs.append(index)
//        }
        model.imagesPath = []
        model.imagesIndex = []
        
        var contains = false
        if folderModel.dataSources.count != 0 {
            
            for (index, subModel) in folderModel.dataSources.enumerated() {
                if subModel.pathFile == model.pathFile {
                    contains = true
                    folderModel.dataSources[index] = model
                    break
                }
            }
            if contains == false{
                folderModel.dataSources.append(model)
            }
        }else{
            folderModel.dataSources.append(model)
        }

        let list = CRUserDefaults.recordList
        if var recordList = list{
            for (index, subDict) in recordList.enumerated(){
                let subFolderModel:SHRecordFolderModel = getDataDictWith(dict: subDict)
                if subFolderModel.id == folderModel.id {
                    contains = true
                    subFolderModel.modifyDate = nowDate
                    subFolderModel.dataSources = folderModel.dataSources
                    let dic = getDictWith(obj: subFolderModel)
                    recordList[index] = dic
                    break
                }
            }
            if contains == true {
                CRUserDefaults.recordList = recordList
            }
        }
        currentModel = model
    }
    
    func removeCurrentRecored(_ model:SHRecordModel){
        
        var list = CRUserDefaults.recordList
        for (index, subDic) in list!.enumerated(){
            if (subDic["pathFile"] as! String) == model.pathFile {
                list?.remove(at: index)
                break
            }
        }
        CRUserDefaults.recordList = list
    }
    
    func timerInvalidate(){
        secondTimer?.invalidate()
    }
    
    deinit {
        secondTimer?.invalidate()
    }
}

extension SHRecordViewController{
    
    @objc private func countSecond() {
        seconds += 1
        //小时计算
        let hours = (seconds)%(24*3600)/3600;
        //分钟计算
        let minutes = (seconds)%3600/60;
        //秒计算
        let second = (seconds)%60;
        let timeString  = String(format: "%02lu:%02lu:%02lu", hours, minutes, second)
        secondsLabel.text = timeString
        
        saveContent()
        if seconds == non_member_limit_seconds {
            _ = self.verityMember()
        }
    }
    
    static func getAllFilePath(_ dirPath: String) -> [String]? {
        var filePaths = [String]()
        
        do {
            let array = try FileManager.default.contentsOfDirectory(atPath: dirPath)
            
            for fileName in array {
                var isDir: ObjCBool = true
                
                let fullPath = "\(dirPath)/\(fileName)"
                
                if FileManager.default.fileExists(atPath: fullPath, isDirectory: &isDir) {
                    if isDir.boolValue {
                        filePaths.append(fullPath)
                    }
                }
            }
            
        } catch let error as NSError {
            print("get file path error: \(error)")
        }
        return filePaths;
    }
    
    func textView_text(_ text:String) -> NSAttributedString {
        let address = "地点: " + self.currentAddress
        
        let content = address + "\n \n" + text
        
        let addressRange = content.range(of: address)
        let attStr = NSMutableAttributedString.init(string: content)
        attStr.addAttributes([.font:UIFont.boldSystemFont(ofSize: 18)], range: NSRange(addressRange!, in: content))
        if let textRange = content.range(of: text) {
            attStr.addAttributes([.font:UIFont.systemFont(ofSize: 18)], range: NSRange(textRange, in: content))
        }
        return attStr
    }
    
    private func copyBtn(){
        if self.recordTextView?.text.length == 0 {
            return
        }
        MBProgressHUD.showMessage("文本已复制到剪切板", to: self.view)
        let board = UIPasteboard.general
        board.string = self.recordTextView?.text
    }
    
    private func generatePDF() {
        
        if SHUserAccountManager.shared.isMember == false{
            self.goGoods("dialog_record_success_trans_pdf")
            return
        }
        
        do {
            let range: Range = currentModel!.pathFile.range(of: RecordMp3)!
            let location: Int = currentModel!.pathFile.distance(from: currentModel!.pathFile.startIndex, to: range.lowerBound)
            let subStr = currentModel!.pathFile.prefix(location)
            
            let documentsFile = DocumentPath+subStr+"/\(currentModel!.rename).pdf"
            
            try PDFGenerator.generate(self.recordTextView!, to: documentsFile)
            //此三方会把传入控件约束移除  需重新添加
            self.recordTextView?.snp.makeConstraints({ (maker) in
                maker.top.left.right.equalToSuperview()
                maker.bottom.equalTo(secondsLabel.snp.top).offset(-20)
            })
            
//            let webvc = SHWebViewController.init()
//            webvc.url = documentsFile
//            self.navigationController?.pushViewController(webvc, animated: true)

            let fileURL = URL.init(fileURLWithPath: documentsFile)
            let data = try Data.init(contentsOf: fileURL)

            let activityVC = UIActivityViewController(activityItems: [data, fileURL], applicationActivities: nil)
            activityVC.completionWithItemsHandler = {
                activity, success, items, errot in
                // result
            }
            present(activityVC, animated: true, completion: nil)
            
        } catch let error {
            print(error)
        }
    }
    
    private func generateWav() {
    
        do{
            let documentsFile_wav = DocumentPath.appending(currentModel!.pathFile)
            let fileURL_wav = URL.init(fileURLWithPath: documentsFile_wav)
//            let data_wav = try Data.init(contentsOf: fileURL_wav)
            
            let range: Range = currentModel!.pathFile.range(of: RecordMp3)!
            let location: Int = currentModel!.pathFile.distance(from: currentModel!.pathFile.startIndex, to: range.lowerBound)
            let subStr = currentModel!.pathFile.prefix(location)

            let documentsFile_rename = DocumentPath+subStr+"/\(currentModel!.rename).mp3"
            let fileURL_rename = URL.init(fileURLWithPath: documentsFile_rename)
            
            if FileManager.default.fileExists(atPath: documentsFile_rename) == false {
                try FileManager.default.copyItem(at: fileURL_wav, to: fileURL_rename)
            }

            let data_rename = try Data.init(contentsOf: fileURL_rename)
            
            let activityVC = UIActivityViewController(activityItems: [data_rename, fileURL_rename], applicationActivities: nil)
            activityVC.completionWithItemsHandler = {
                activity, success, items, errot in
                // result
            }
            present(activityVC, animated: true, completion: nil)
        } catch let error {
            print(error)
        }
    }
}
