//
//  PQStuckPointMaterialController.swift
//  PQSpeed
//
//  Created by SanW on 2021/4/26.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import BFAnalyzeKit
import BFCommonKit
import BFMaterialKit
import BFMediaKit
import BFUIKit
import Photos
import UIKit

public class PQStuckPointMaterialController: BFBaseViewController {
    public var isToPublicHandle: ((_ isReCreate: Bool, _ selectedTotalDuration: Float64, _ selectedDataCount: Int, _ selectedImageDataCount: Int, _ mStickers: [PQEditVisionTrackMaterialsModel]?, _ stuckPointMusicData: PQVoiceModel?, _ editProjectModel: PQEditProjectModel?, _ rhythmMode: createStickersModel, _ speedMin: Float, _ speedMax: Float, _ audioTime: Float, _ clipAudioRange: CMTimeRange, _ playeTimeRange: CMTimeRange) -> Void)?

    // 按钮高
    let choseBtnH: CGFloat = cDefaultMargin * 3
    // 按钮宽
    let choseBtnW: CGFloat = cDefaultMargin * 5
    // 操作视图高度
    let topImageH: CGFloat = 76
    // 底部操作视图高度
    let bottomH: CGFloat = cDefaultMargin * 5
    // 间隔
    let margin: CGFloat = 12
    // 选择的总数
    var selectedDataCount: Int = 0
    // 选择的图片总数
    var selectedImageDataCount: Int = 0
    // 再创作音乐数据
    public var reCreateMusicData: PQVoiceModel?
    public var reCreateVideoData: PQReCreateModel? // 再创作数据
    lazy var changeCollecBtn: UIButton = {
        let changeCollecBtn = UIButton(frame: CGRect(x: cDefaultMargin * 5, y: cDevice_iPhoneStatusBarHei, width: cScreenWidth - cDefaultMargin * 10, height: cDefaultMargin * 4))
        changeCollecBtn.titleLabel?.lineBreakMode = .byTruncatingTail
        changeCollecBtn.tintColor = BFConfig.shared.styleTitleColor
        changeCollecBtn.setTitle("我的相册", for: .normal)
        changeCollecBtn.setImage(UIImage.moduleImage(named: "icon_selected_down", moduleName: "BFStuckPointKit", isAssets: false)?.withRenderingMode(.alwaysTemplate), for: .normal)
        changeCollecBtn.setImage(UIImage.moduleImage(named: "icon_selected_up", moduleName: "BFStuckPointKit", isAssets: false)?.withRenderingMode(.alwaysTemplate), for: .selected)
        changeCollecBtn.setTitleColor(BFConfig.shared.styleTitleColor, for: .normal)
        changeCollecBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        changeCollecBtn.tag = 1
        changeCollecBtn.imagePosition(at: PQButtonImageEdgeInsetsStyle.right, space: cDefaultMargin / 2)
        changeCollecBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return changeCollecBtn
    }()

    lazy var albumController: BFPhotoAlbumController = {
        let albumController = BFPhotoAlbumController()
        albumController.isTopShow = true
        albumController.categoryH = cDefaultMargin * 40
        addChild(albumController)
        view.insertSubview(albumController.view, belowSubview: navHeadImageView!)
        albumController.updateViewFrame(frame: CGRect(x: 0, y: navHeadImageView?.frame.maxY ?? cDevice_iPhoneNavBarAndStatusBarHei, width: view.frame.width, height: view.frame.height - (navHeadImageView?.frame.maxY ?? cDevice_iPhoneNavBarAndStatusBarHei)))
        albumController.selectedHandle = { [weak self] seletedData in
            if seletedData != nil {
                self?.albumSelectedHandle(seletedData: seletedData)
            } else {
                self?.changeCollecBtn.isSelected = false
            }
        }
        return albumController
    }()

    lazy var choseLocalAllBtn: UIButton = {
        let choseLocalAllBtn = UIButton(frame: CGRect(x: (view.frame.width - choseBtnW * 3) / 4, y: cDevice_iPhoneNavBarAndStatusBarHei + margin, width: choseBtnW, height: choseBtnH))
        choseLocalAllBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#999999"), for: .normal)
        choseLocalAllBtn.setTitleColor(BFConfig.shared.styleTitleColor, for: .selected)
        choseLocalAllBtn.setTitle("全部", for: .normal)
        choseLocalAllBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        choseLocalAllBtn.addCorner(corner: 6)
        choseLocalAllBtn.tag = 10
        choseLocalAllBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return choseLocalAllBtn
    }()

    lazy var choseLocalVideoBtn: UIButton = {
        let choseLocalVideoBtn = UIButton(frame: CGRect(x: choseLocalAllBtn.frame.maxX + (view.frame.width - choseBtnW * 3) / 4, y: choseLocalAllBtn.frame.minY, width: choseBtnW, height: choseBtnH))
        choseLocalVideoBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#999999"), for: .normal)
        choseLocalVideoBtn.setTitleColor(BFConfig.shared.styleTitleColor, for: .selected)
        choseLocalVideoBtn.setTitle("视频", for: .normal)
        choseLocalVideoBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        choseLocalVideoBtn.addCorner(corner: 6)
        choseLocalVideoBtn.tag = 11
        choseLocalVideoBtn.isSelected = true
        choseLocalVideoBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return choseLocalVideoBtn
    }()

    lazy var choseLocalImageBtn: UIButton = {
        let choseLocalImageBtn = UIButton(frame: CGRect(x: choseLocalVideoBtn.frame.maxX + (view.frame.width - choseBtnW * 3) / 4, y: choseLocalAllBtn.frame.minY, width: choseBtnW, height: choseBtnH))
        choseLocalImageBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#999999"), for: .normal)
        choseLocalImageBtn.setTitleColor(BFConfig.shared.styleTitleColor, for: .selected)
        choseLocalImageBtn.setTitle("照片", for: .normal)
        choseLocalImageBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        choseLocalImageBtn.addCorner(corner: 6)
        choseLocalImageBtn.tag = 12
        choseLocalImageBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return choseLocalImageBtn
    }()

    lazy var choseLineView: UIView = {
        let choseLineView = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 3))
        choseLineView.frame.origin.y = (navHeadImageView?.frame.maxY ?? 0) - 6
        choseLineView.center.x = choseLocalVideoBtn.center.x
        choseLineView.backgroundColor = UIColor.hexColor(hexadecimal: BFConfig.shared.styleColor.rawValue)
        return choseLineView
    }()

    // 顶部提示视图
//    lazy var materialHeadView: PQStuckPointMaterialHeadView = {
//        let materialHeadView: PQStuckPointMaterialHeadView = PQStuckPointMaterialHeadView(frame: CGRect(x: 0, y: navHeadImageView?.frame.maxY ?? cDevice_iPhoneNavBarAndStatusBarHei, width: view.frame.width, height: topImageH))
//        return materialHeadView
//    }()

    // 底部操作视图
    lazy var bottomRemindView: UIView = {
        let bottomRemindView = UIView(frame: CGRect(x: 0, y: view.frame.height - (bottomH + cSafeAreaHeight), width: view.frame.width, height: bottomH + cSafeAreaHeight))
        bottomRemindView.backgroundColor = BFConfig.shared.styleBackGroundColor
        return bottomRemindView
    }()

    // 确定按钮
    lazy var confirmBtn: UIButton = {
        let confirmBtn = UIButton(frame: CGRect(x: bottomRemindView.frame.width - cDefaultMargin * 9 - margin, y: margin / 2, width: cDefaultMargin * 9, height: bottomH - margin))
        confirmBtn.backgroundColor = BFConfig.shared.otherTintColor
//        confirmBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#EE0051")
        confirmBtn.setTitle("确定", for: .normal)
        confirmBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#999999"), for: .normal)
        confirmBtn.setTitleColor(UIColor.white, for: .selected)
        confirmBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        confirmBtn.addCorner(corner: 3)
        confirmBtn.tag = 13
        confirmBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return confirmBtn
    }()

    // 底部提示视图
    lazy var bottomRemindLab: UILabel = {
        let bottomRemindLab = UILabel(frame: CGRect(x: margin, y: 0, width: bottomRemindView.frame.width - margin * 3 - confirmBtn.frame.width, height: bottomH))
        bottomRemindLab.attributedText = NSAttributedString(string: "至少选择 1 个视频或 2 张照片")
        bottomRemindLab.textAlignment = .left
        bottomRemindLab.textColor = BFConfig.shared.styleTitleColor
        bottomRemindLab.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        return bottomRemindLab
    }()

    /// 已选素材列表
    lazy var materialListView: BFSelectedMaterialListView = {
        let materialListView = BFSelectedMaterialListView(frame: CGRect(x: 0, y: cScreenHeigth, width: cScreenWidth, height: 88))
        materialListView.deletedMaterialHandle = { [weak self] materialData, isDissmiss in
            /// 处理已经选择的数据
            self?.dealWithSelectedMaterials(isDissmiss: isDissmiss, isChose: false, materialData: materialData)
        }
        materialListView.detailMaterialHandle = { [weak self] _, materialData in
            let detailVc: BFMaterialDetailController = BFMaterialDetailController()
            detailVc.materialDetailClickHandle = { [weak self] isMaterialSelected, materialData in
                if isMaterialSelected != materialData?.isSelected {
                    self?.photoMaterialVc.updateMaterials(isSelected:!(isMaterialSelected ?? false), materialData: materialData)
                }
            }
            if !(materialData?.isSelected ?? false) {
                materialData?.selectedIndex = (self?.selectedDataCount ?? 0) + 1
            }
            detailVc.materialData = materialData
            detailVc.isStuckPoint = true
            self?.navigationController?.pushViewController(detailVc, animated: true)
        }
        return materialListView
    }()

    /// 图片加载视图
    lazy var photoMaterialVc: BFPhotosMaterialController = {
        let photoMaterialVc = BFPhotosMaterialController()
        photoMaterialVc.isShowMediaTag = false
        photoMaterialVc.imageDuration = 1.5
        addChild(photoMaterialVc)
        view.insertSubview(photoMaterialVc.view, belowSubview: bottomRemindView)
        photoMaterialVc.updateFrame(newFrame: CGRect(x: 0, y: (navHeadImageView?.frame.maxY ?? cDevice_iPhoneNavBarAndStatusBarHei) + margin / 2, width: view.frame.width, height: view.frame.height - ((navHeadImageView?.frame.maxY ?? cDevice_iPhoneNavBarAndStatusBarHei) + margin + bottomRemindView.frame.height)))
        photoMaterialVc.selectedMaterialHandle = { [weak self] currentMaterialData, selectedPhotoData, selectedTotalDuration, imageCount in

            self?.selectedDataCount = selectedPhotoData.count
            self?.selectedImageDataCount = imageCount

            self?.dealWithSelectedMaterial(materialData: currentMaterialData, totalDuration: selectedTotalDuration)
            /// 处理已经选择的数据
            self?.dealWithSelectedMaterials(isDissmiss: selectedPhotoData.count <= 0, isChose: true, materialData: currentMaterialData)
        }
        photoMaterialVc.detailMaterialHandle = { [weak self] _, currentMaterialData in
            let detailVc: BFMaterialDetailController = BFMaterialDetailController()
            detailVc.isStuckPoint = true
            detailVc.materialDetailClickHandle = { [weak self] isMaterialSelected, materialData in
                if isMaterialSelected != materialData?.isSelected {
                    self?.photoMaterialVc.updateMaterials(isSelected:!(isMaterialSelected ?? false), materialData: materialData)
                }
            }
            if !(currentMaterialData?.isSelected ?? false) {
                currentMaterialData?.selectedIndex = (self?.selectedDataCount ?? 0) + 1
            }
            detailVc.materialData = currentMaterialData
            self?.navigationController?.pushViewController(detailVc, animated: true)
        }
        photoMaterialVc.emptyRefreshHandle = { [weak self] msgType in
            self?.btnClick(sender: msgType == .video ? self?.choseLocalImageBtn : (msgType == .image ? self?.choseLocalVideoBtn : self?.choseLocalAllBtn))
        }
        photoMaterialVc.scrollViewDidScroll = { [weak self] _ in
            // 更新frame
//            self?.updateMaterialHeadFrame(contentOffset: contentOffset)
        }
        return photoMaterialVc
    }()

    override public func viewDidLoad() {
        super.viewDidLoad()
        leftButton(image: UIImage(named: "upload_delete"), tintColor: BFConfig.shared.styleTitleColor)
        navHeadImageView?.addSubview(changeCollecBtn)
        navHeadImageView?.frame.size.height = cDevice_iPhoneNavBarAndStatusBarHei + margin * 2 + choseBtnH
        navHeadImageView?.addSubview(choseLocalAllBtn)
        navHeadImageView?.addSubview(choseLocalVideoBtn)
        navHeadImageView?.addSubview(choseLocalImageBtn)
        navHeadImageView?.addSubview(choseLineView)
        view.addSubview(bottomRemindView)
        bottomRemindView.addSubview(confirmBtn)
        bottomRemindView.addSubview(bottomRemindLab)
        addChild(photoMaterialVc)
        view.insertSubview(photoMaterialVc.view, belowSubview: bottomRemindView)
        view.bringSubviewToFront(navHeadImageView!)
        view.insertSubview(materialListView, belowSubview: bottomRemindView)
        // 卡点音乐素材选择曝光上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_windowView, objectType: .ot_view_selectSyncedUpMaterial, pageSource: .sp_stuck_selectMaterial, commonParams: commonParams())
        // 注册通知
        addNotification(self, selector: #selector(dismissVc), name: cFinishedPublishedNotiKey, object: nil)
    }

    /// 按钮点击事件
    /// - Parameter sender: <#sender description#>
    /// - Returns: <#description#>
    @objc func btnClick(sender: UIButton?) {
        switch sender?.tag {
        case 1: // 选择图库
            sender?.isSelected = !(sender?.isSelected ?? false)
            if sender?.isSelected ?? false {
                albumController.showCategoryView()
            } else {
                albumController.dismissCategoryView()
            }
        case 10, 11, 12: // 筛选全部图库
            choseLocalAllBtn.isSelected = sender?.tag == 10
            choseLocalVideoBtn.isSelected = sender?.tag == 11
            choseLocalImageBtn.isSelected = sender?.tag == 12
            if sender?.tag == 11 {
                photoMaterialVc.msgType = .video
            } else if sender?.tag == 12 {
                photoMaterialVc.msgType = .image
            } else {
                photoMaterialVc.msgType = .all
            }
            UIView.animate(withDuration: 0.3, delay: 0, options: .allowUserInteraction) { [weak self] in
                self?.choseLineView.center.x = sender?.center.x ?? 0
            } completion: { _ in
            }
        case 13:
            if confirmBtn.isSelected {
//                reCreateMusicData?.endTime = (reCreateMusicData?.startTime ?? 0) + (reCreateMusicData?.stuckPointCuttingTime(videoCount: selectedDataCount - selectedImageDataCount, imageCount: selectedImageDataCount, totalDuration: photoMaterialVc.selectedTotalDuration) ?? 0)

                if reCreateMusicData != nil {
                    let editerVC: PQStuckPointEditerController = PQStuckPointEditerController()
                    editerVC.stuckPointMusicData = reCreateMusicData
                    editerVC.selectedDataCount = selectedDataCount
                    editerVC.selectedImageDataCount = selectedImageDataCount
                    // mdf by ak 进入编辑界面的时候去掉图片的时长
                    editerVC.selectedTotalDuration = photoMaterialVc.selectedTotalDuration - (Double(selectedImageDataCount) * 1.5)
                    editerVC.selectedPhotoData = photoMaterialVc.selectedPhotoData
                    editerVC.reCreateVideoData = reCreateVideoData
                    editerVC.isReCreate = true
                    navigationController?.pushViewController(editerVC, animated: true)
                } else {
                    let stuckPointMusicVc = PQStuckPointMusicController()
                    stuckPointMusicVc.selectedMusicData = reCreateMusicData
                    stuckPointMusicVc.selectedDataCount = selectedDataCount
                    stuckPointMusicVc.reCreateVideoData = reCreateVideoData
                    stuckPointMusicVc.selectedImageDataCount = selectedImageDataCount
                    stuckPointMusicVc.selectedTotalDuration = photoMaterialVc.selectedTotalDuration
                    stuckPointMusicVc.selectedPhotoData = photoMaterialVc.selectedPhotoData
                    navigationController?.pushViewController(stuckPointMusicVc, animated: true)
                }
                // 卡点视频素材确认按钮
                BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_confirmMaterial, pageSource: .sp_stuck_selectMaterial, extParams: ["materialNumber": selectedDataCount], commonParams: commonParams())
            }
        default:
            break
        }
    }

    override public func backBtnClick() {
        super.backBtnClick()
        if isPresent {
            postNotification(name: cFinishedPublishedNotiKey)
        }
        // 卡点视频返回按钮点击上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_click_back, pageSource: .sp_stuck_selectMaterial, commonParams: commonParams())
    }

    // 返回
    @objc func dismissVc() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { [weak self] in
            if self?.isPresent ?? false {
                self?.dismiss(animated: true, completion: nil)
            }
        }
    }

    deinit {
        photoMaterialVc.assetCollection = nil
        photoMaterialVc.allPhotos = nil
        PQNotification.removeObserver(self)
        BFLog(message: "\(self) 已销毁")
    }

    /// 图库选择的回调
    /// - Parameter seletedData: <#seletedData description#>
    /// - Returns: <#description#>
    func albumSelectedHandle(seletedData: PHAsset?) {
        changeCollecBtn.isSelected = false
        if seletedData != nil {
            changeCollecBtn.setTitle(seletedData?.title ?? "全部", for: .normal)
            changeCollecBtn.imagePosition(at: PQButtonImageEdgeInsetsStyle.right, space: cDefaultMargin / 2)
            photoMaterialVc.assetCollection = seletedData?.assetCollection
        }
    }

    /// 点击选择的回调
    /// - Parameter materialData: <#materialData description#>
    /// - Returns: <#description#>
    func dealWithSelectedMaterial(materialData _: PHAsset?, totalDuration: Float64) {
        confirmBtn.isSelected = (selectedDataCount > 0 && (selectedImageDataCount >= 2 || selectedDataCount > selectedImageDataCount))
        if confirmBtn.isSelected {
            confirmBtn.backgroundColor = UIColor.hexColor(hexadecimal: BFConfig.shared.styleColor.rawValue)
        } else {
            confirmBtn.backgroundColor = BFConfig.shared.otherTintColor
        }
        if selectedDataCount <= 0 {
            bottomRemindLab.attributedText = NSAttributedString(string: "至少选择 1 个视频或 2 张照片")
        } else if selectedImageDataCount == 1, selectedDataCount == selectedImageDataCount {
            let att = NSMutableAttributedString(string: "至少选择 1 个视频或 2 张照片")
            bottomRemindLab.attributedText = att
        } else {
            let att = NSMutableAttributedString(string: "素材总时长 \(totalDuration.formatDurationToHMS())")
            att.setAttributes([.foregroundColor: UIColor.hexColor(hexadecimal: BFConfig.shared.styleColor.rawValue)], range: NSRange(location: 6, length: "\(totalDuration.formatDurationToHMS())".count))
            bottomRemindLab.attributedText = att
        }
        confirmBtn.setTitle(selectedDataCount > 0 ? "确定(\(selectedDataCount))" : "确定", for: .normal)
    }

    /// 处理已经选择的数据
    /// - Returns: <#description#>
    func dealWithSelectedMaterials(isDissmiss: Bool, isChose: Bool, materialData: PHAsset?) {
        // 添加当前素材
        if materialData != nil {
            if isChose {
                materialListView.addMaterialData(materialData: materialData!)
            } else {
                photoMaterialVc.deSeletedMaterialData(indexPath: nil, materialData: materialData)
            }
        }
        if isChose && !isDissmiss && materialListView.frame.minY > (bottomRemindView.frame.minY - 88) {
            UIView.animate(withDuration: 0.5, delay: 0, options: .allowUserInteraction) { [weak self] in
                self?.materialListView.frame = CGRect(x: 0, y: (self?.bottomRemindView.frame.minY ?? 0) - 88, width: cScreenWidth, height: 88)
                self?.photoMaterialVc.updateFrame(newFrame: CGRect(x: 0, y: self?.photoMaterialVc.view.frame.minY ?? 0, width: self?.photoMaterialVc.view.frame.width ?? 0, height: (self?.photoMaterialVc.view.frame.height ?? 0) - 88))
            } completion: { _ in
            }

        } else if isDissmiss && materialListView.frame.minY != cScreenHeigth {
            UIView.animate(withDuration: 0.5, delay: 0, options: .allowUserInteraction) { [weak self] in
                self?.materialListView.frame = CGRect(x: 0, y: cScreenHeigth, width: cScreenWidth, height: 88)
                self?.photoMaterialVc.updateFrame(newFrame: CGRect(x: 0, y: self?.photoMaterialVc.view.frame.minY ?? 0, width: self?.photoMaterialVc.view.frame.width ?? 0, height: (self?.photoMaterialVc.view.frame.height ?? 0) + 88))
            } completion: { _ in
            }
        }
    }
}
