//
//  INIntrocudeController.swift
//  Introduce
//
//  Created by 胡志强 on 2021/11/29.
//  制作录音，预览页面

import BFCommonKit
import BFRecordScreenKit
import Foundation
import Photos
import UIKit
import BFAnalyzeKit
import BFUIKit


class INIntroduceController: BFBaseViewController {
    lazy var stripSwithView : BFStripSwithView = {
        let v = BFStripSwithView(frame: .zero, items: 0, space: 4)
        v.itemClickHandle = { [weak self] _, index in
            guard let wself = self else { return }
            wself.recordScreenVC.updateContentOffset(index: index)
        }
        return v
    }()
    let exportBtn = UIButton()
    var assets: [PHAsset]?

    let recordUid = getRandomStringOfLength(length: 16)

    let recordScreenVC = BFRecordScreenController()
    
    lazy var addMaterialBtn : UIButton  = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "dl_add"), for: .normal)
        btn.addTarget(self, action: #selector(addmaterial), for: .touchUpInside)
        return btn
    }()
    // MARK: - VC生命周期

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        showNavigation()

        PQNotification.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        PQNotification.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PQNotification.removeObserver(self)
        cHiddenHUB(superView: nil)
    }

    @objc internal func keyboardWillHide(_: Notification?) {
        navHeadImageView?.isHidden = false
    }

    @objc internal func keyboardWillShow(_: Notification?) {
        navHeadImageView?.isHidden = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navHeadImageView?.backgroundColor = .clear
        navHeadImageView?.image = UIImage(named: "top_shadow")
        navHeadImageView?.contentMode = .scaleToFill
        leftButton(image: nil, imageName: nil, tintColor: .white)

        exportBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#389AFF")
        exportBtn.setTitle("option_export".BFLocale, for: .normal)
        exportBtn.addCorner(corner: 4)
        exportBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        exportBtn.addTarget(self, action: #selector(exportAction), for: .touchUpInside)
        navHeadImageView?.addSubview(exportBtn)
        exportBtn.frame = CGRect(x: (navHeadImageView?.frame.width ?? 0) - 12 - 60, y: 0, width: 60, height: 36)
        exportBtn.center.y = backButton?.center.y ?? 0
        exportBtn.titleLabel?.adjustsFontSizeToFitWidth = true
        addChild(recordScreenVC)
        recordScreenVC.view.frame = view.frame
        view.addSubview(recordScreenVC.view)
        if let ass = assets {
            recordScreenVC.fetchMaterial(ass)
        }
        recordScreenVC.changeItemHandle = { [weak self] index in
            
            guard let wself = self else { return }
            
            // 删除了一条
            if index == -3 {
                wself.resetStripSwithView(wself.recordScreenVC.itemModels.count)

            }else{
                wself.stripSwithView.changeSwitchStatus(index: index)
            }
        }
        recordScreenVC.recordEndHandle = {model in
            // 录音完成时上报
            BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_speekButton, pageSource: .sp_speekPage,extParams: ["duration":Int(((model?.endCMTime.seconds ?? 0) - (model?.startCMTime.seconds ?? 0)) * 1000)],commonParams: commonParams())
        }
        recordScreenVC.subTitleBtnClickHandle = { isOn in
            // 点击字幕按钮上报
            BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_captionsButton, pageSource: .sp_speekPage,extParams: ["isSubtitlesClose":isOn],commonParams: commonParams())
        }
        
        recordScreenVC.voiceBtnClickHandle = { voice in
            if(voice != nil){
                BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_voiceChangerButton, pageSource: .sp_speekPage,extParams: ["voiceMode":voice?.name ?? ""],commonParams: commonParams())
            }
            
        }
        
        
        navHeadImageView?.addSubview(stripSwithView)
        navHeadImageView?.addSubview(addMaterialBtn)
        stripSwithView.snp.makeConstraints { make in
            make.left.equalTo(backButton!.snp.right).offset(5)
            make.top.height.equalTo(backButton!)
            if (assets?.count ?? 0) > 1 {
                make.width.equalTo(cScreenWidth).priority(.high)
            }else{
                make.width.equalTo(0).priority(.high)
            }
        }
        addMaterialBtn.snp.makeConstraints { make in
            make.left.equalTo(stripSwithView.snp.right).offset(-2)
            make.top.height.equalTo(backButton!)
            if (assets?.count ?? 0) < 20 {
                make.width.equalTo(addMaterialBtn.snp.height)
            }else {
                make.width.equalTo(0)
            }
            make.right.lessThanOrEqualTo(exportBtn.snp.left).offset(-15)
        }
        
        if assets != nil, (assets?.count ?? 0) > 1 {
            stripSwithView.resetView(count: assets?.count ?? 0)
        } else if assets != nil,(assets?.count ?? 0) > 0 {
            // 曝光上报
            BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: assets?.first?.mediaType == .video ? .ot_video: .ot_image, pageSource: .sp_speekPage, commonParams: commonParams())
        }
        
        // 已选素材上报
        if assets != nil ,(assets?.count ?? 0) > 0 {
            var materialTypeList:[String] = []
            assets?.forEach({ item in
                materialTypeList.append(item.mediaType == .video ? "video": "image")
            })
            BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: .ot_addMaterialSuccess, pageSource: .sp_speekPage,extParams: ["materialTypeList":materialTypeList],commonParams: commonParams())
        }
    }
    
    // MARK: - Button action
    func updateAsset(_ phAssets:[PHAsset]) {
        recordScreenVC.fetchMaterial(phAssets)
        if recordScreenVC.itemModels.count >= 20 {
            addMaterialBtn.snp.remakeConstraints { make in
                make.left.equalTo(stripSwithView.snp.right).offset(-2)
                make.top.height.equalTo(backButton!)
                make.width.equalTo(0)
                make.right.lessThanOrEqualTo(exportBtn.snp.left).offset(-15)
            }
        }
        resetStripSwithView(recordScreenVC.itemModels.count)
    }
    
    func resetStripSwithView(_ count: Int){
        stripSwithView.resetView(count: count)
        DispatchQueue.main.async {[weak self] in
            guard let wself = self else { return }
            wself.stripSwithView.snp.updateConstraints { make in
                if count > 1 {
                    make.width.equalTo(cScreenWidth).priority(.high)
                }else{
                    make.width.equalTo(0).priority(.high)
                }
            }
            wself.stripSwithView.setNeedsLayout()
            wself.stripSwithView.layoutIfNeeded()
        }
    }
    
    @objc func addmaterial(){
        if recordScreenVC.itemModels.count >= 20{
            cShowHUB(superView: nil, msg: "option_tips_max20".BFLocale)
            return
        }
        if recordScreenVC.isNormalPlaying {
            recordScreenVC.pause()
        }
        
        
        let alee = BFActionSheetView()
        
        if recordScreenVC.itemModels.count > 0 && recordScreenVC.itemModels.last!.mediaType != .Camera {
            alee.addAction(title: "home_shoot".BFLocale, sheetStyle: .defalt) {[weak self] in
                guard let wself = self else { return }
                
                let phAsset = PHAsset()
                phAsset.title = "record.camera"
                wself.updateAsset([phAsset])
            }
        }
        
        alee.addAction(title: "home_choose".BFLocale, sheetStyle: .defalt) {[weak self] in
            guard let wself = self else { return }
            
            let vc = INPhotoVideosController()
            vc.maxMaterialNum = 20 - wself.recordScreenVC.itemModels.count
            vc.modalPresentationStyle = .fullScreen
            vc.nextBtnCallBack = {[weak self] phAssets in
                guard let wself = self else { return }
                
                wself.updateAsset(phAssets)
            }
            
            wself.navigationController?.present(vc, animated: true, completion: nil)
        }
        alee.addAction(title: "option_cancel".BFLocale, sheetStyle: .cancle, handler: nil)
        alee.show()
        
//        let alertv = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
//        if let subview = alertv.view.subviews.first?.subviews.first?.subviews.first {
//            subview.backgroundColor = .black
//        }
//
//        if recordScreenVC.itemModels.count > 0 && recordScreenVC.itemModels.last!.mediaType != .Camera {
//            let action = UIAlertAction(title: "拍摄录制", style: .default) {[weak self]  action in
//                guard let wself = self else { return }
//
//                let phAsset = PHAsset()
//                phAsset.title = "record.camera"
//                wself.updateAsset([phAsset])
//            }
//            alertv.addAction(action)
//        }
//
//        let action1 = UIAlertAction(title: "从相册选择", style: .destructive) {[weak self] action in
//            guard let wself = self else { return }
//            let vc = INPhotoVideosController()
//            vc.maxMaterialNum = 20 - wself.recordScreenVC.itemModels.count
//            vc.modalPresentationStyle = .fullScreen
//            vc.nextBtnCallBack = {[weak self] phAssets in
//                guard let wself = self else { return }
//
//                wself.updateAsset(phAssets)
//            }
//
//            wself.navigationController?.present(vc, animated: true, completion: nil)
//        }
//        alertv.addAction(action1)
//
//        let action2 = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//        alertv.addAction(action2)
//
//        self.present(alertv, animated: true, completion: nil)
    }

    override func backBtnClick() {
  
        let alertController = UIAlertController(title: "compose_tips_exit".BFLocale,
                       message: "", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "option_not exit".BFLocale, style: .default, handler: nil)

        let okAction = UIAlertAction(title: "option_exit".BFLocale, style: .cancel, handler: {[weak self]
           action in
           self?.recordScreenVC.backBtnClick()
//            self?.super_back()
            self?.navigationController?.popToRootViewController(animated: true)
        })
        okAction.setValue(UIColor.red, forKey:"titleTextColor")

        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated: true, completion: nil)
        
    }

    private func super_back() {
        super.backBtnClick()
    }

    @objc func exportAction() {
        
        //add by ak 如果当前段有没有转完的发音人显示 Loadingview
        if(!recordScreenVC.voiceChangeStickerFinish(isShowLoadView: true)){
            return
        }
        
        let count = recordScreenVC.itemModels.reduce(0, { partialResult, model in
            model.voiceStickers.count + partialResult
        })
        if count == 0 {
            cShowHUB(superView: nil, msg: "compose_tips_export".BFLocale)
            return
        }
        
        recordScreenVC.backBtnClick()

        let controller = INVideoExportController()
        controller.export.data = recordScreenVC.itemModels
        controller.export.originSoundVolumn = recordScreenVC.noSpeakVolume
        controller.export.originSoundInRecordVolumn = recordScreenVC.haveSpeakVolume
        controller.recordUid = recordUid
        controller.coverIV.image = recordScreenVC.itemModels.first?.coverImg
        navigationController?.pushViewController(controller, animated: true)
        // 点击导出按钮上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_exportButton, pageSource: .sp_speekPage,commonParams: commonParams())
    }
}
