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

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

class INIntroduceController: BFBaseViewController {
    var stripSwithView: BFStripSwithView?
    let exportBtn = UIButton()
    var assets: [PHAsset]? {
        didSet {
            if let ass = assets {
                recordScreenVC.assets = ass
            }
        }
    }

    let recordScreenVC = BFRecordScreenController()

    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)
        recordScreenVC.changeItemHandle = { [weak self] index in
            self?.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())
        }
        if assets != nil, (assets?.count ?? 0) > 1 {
            stripSwithView = BFStripSwithView(frame: CGRect(x: (backButton?.frame.maxX ?? 0), y: 0, width: exportBtn.frame.minX - (backButton?.frame.maxX ?? 0) - 10, height: cDevice_iPhoneNavBarHei), items: assets?.count ?? 1,space: 4)
            stripSwithView?.center.y = backButton?.center.y ?? 0
            stripSwithView?.itemClickHandle = { [weak self] _, index in
                self?.recordScreenVC.updateContentOffset(index: index)
//                if (self?.assets?.count ?? 0) > index {
//                    // 曝光上报
//                    BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: self?.assets?[index].mediaType == .video ? .ot_video: .ot_image, pageSource: .sp_speekPage, commonParams: commonParams())
//                }
            }
            navHeadImageView?.addSubview(stripSwithView!)
        } 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())
        }
    }

    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() {
        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.coverIV.image = recordScreenVC.itemModels.first?.coverImg
        navigationController?.pushViewController(controller, animated: true)
        // 点击导出按钮上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_exportButton, pageSource: .sp_speekPage,commonParams: commonParams())
    }
}
