//
//  INPhotoVideosController.swift
//  Introduce
//
//  Created by 胡志强 on 2021/11/29.
//

import BFCommonKit
import BFMaterialKit
import BFRecordScreenKit
import BFUIKit
import Foundation
import Photos
import UIKit

class INPhotoVideosController: BFBaseViewController {
    var chosedAsset: [PHAsset]?
    // 按钮高
    let choseBtnH: CGFloat = cDefaultMargin * 3
    // 按钮宽
    let choseBtnW: CGFloat = cDefaultMargin * 9
    // 间隔
    let margin: CGFloat = 12

    lazy var albumController: BFPhotoAlbumController = {
        let albumController = BFPhotoAlbumController()
        albumController.mediaType = .all
        albumController.showGIF = false
        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 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("album_title".BFLocale, for: .normal)
        changeCollecBtn.setImage(UIImage.moduleImage(named: "icon_selected_down", moduleName: "BFMaterialKit", isAssets: false)?.withRenderingMode(.alwaysTemplate), for: .normal)
        changeCollecBtn.setImage(UIImage.moduleImage(named: "icon_selected_up", moduleName: "BFMaterialKit", 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 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("album_all".BFLocale, for: .normal)
        choseLocalAllBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        choseLocalAllBtn.addCorner(corner: 6)
        choseLocalAllBtn.tag = 10
        choseLocalAllBtn.isSelected = true
        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("album_video".BFLocale , for: .normal)
        choseLocalVideoBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        choseLocalVideoBtn.addCorner(corner: 6)
        choseLocalVideoBtn.tag = 11
        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("album_album".BFLocale, 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 photoMaterialVc: BFPhotosMaterialController = {
        let vc = BFPhotosMaterialController()
        vc.maxChoseNum = 20
        vc.showGIF = false
        vc.view.backgroundColor = .black
        vc.updateFrame(newFrame: CGRect(x: 0, y: navHeadImageView?.bottomY ?? 0, width: cScreenWidth, height: cScreenHeigth - cDevice_iPhoneTabBarHei - (navHeadImageView?.bottomY ?? 0)))
        vc.selectedMaterialHandle = { [weak self] materialData, selectedPhotoData, _, _ in
            self?.chosedAsset = selectedPhotoData
        }
        vc.detailMaterialHandle = { [weak self] _, currentMaterialData in
            let detailVc: BFMaterialDetailController = BFMaterialDetailController()
            detailVc.isShowNextBtn = true
            detailVc.maxChoseNum = 20
            detailVc.isStuckPoint = true
            detailVc.materialDetailClickHandle = { [weak self] isMaterialSelected, materialData in
                if isMaterialSelected != materialData?.isSelected {
                    self?.photoMaterialVc.updateMaterials(isSelected:!(isMaterialSelected ?? false), materialData: materialData)
                }
            }
            detailVc.nextClickHandle = {[weak self] sender in
                self?.nextBtnClick(sender: sender)
            }
            if !(currentMaterialData?.isSelected ?? false) {
                currentMaterialData?.selectedIndex = (self?.chosedAsset?.count ?? 0) + 1
            }
            detailVc.materialData = currentMaterialData
            self?.navigationController?.pushViewController(detailVc, animated: true)
        }
        vc.emptyRefreshHandle = {[weak self] msgType in
            if msgType == .image {
                self?.btnClick(sender: self?.choseLocalVideoBtn)
            } else {
                self?.btnClick(sender: self?.choseLocalImageBtn)
            }
        }
        return vc
    }()
    
    // MARK: - 生命周期

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

        // 清理cache文件
        clearCacheFile(at: exportVideosDirectory)
        clearCacheFile(at: exportAudiosDirectory)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        leftButton(image: nil, imageName: nil, tintColor: .white)
        navHeadImageView?.backgroundColor = .black
        navHeadImageView?.frame.size.height = cDevice_iPhoneNavBarAndStatusBarHei + margin * 2 + choseBtnH
        navHeadImageView?.addSubview(changeCollecBtn)
        navHeadImageView?.addSubview(choseLocalAllBtn)
        navHeadImageView?.addSubview(choseLocalVideoBtn)
        navHeadImageView?.addSubview(choseLocalImageBtn)

        addChild(photoMaterialVc)
        view.addSubview(photoMaterialVc.view)

        let bottomV = UIView(frame: CGRect(x: 0, y: cScreenHeigth - cDevice_iPhoneTabBarHei, width: cScreenWidth, height: cDevice_iPhoneTabBarHei))
        bottomV.backgroundColor = .black
        view.addSubview(bottomV)

        let nextBtn = UIButton(type: .custom)
        nextBtn.frame = CGRect(x: cScreenWidth - 94, y: 10, width: 78, height: 36)
        nextBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#389AFF")
        nextBtn.setTitle("option_next".BFLocale, for: .normal)
        nextBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        nextBtn.layer.cornerRadius = 4
        nextBtn.addTarget(self, action: #selector(nextBtnClick(sender:)), for: .touchUpInside)
        bottomV.addSubview(nextBtn)
    }

    // MARK: - 按钮点击事件

    /// - 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: // 筛选全部图库
            if (sender?.tag == choseLocalAllBtn.tag && choseLocalAllBtn.isSelected) ||
                (sender?.tag == choseLocalVideoBtn.tag && choseLocalVideoBtn.isSelected) ||
                (sender?.tag == choseLocalImageBtn.tag && choseLocalImageBtn.isSelected) {
                return
            }
                    
            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
            }
        default:
            break
        }
    }

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

    @objc func nextBtnClick(sender _: UIButton) {
        if let assets = chosedAsset, assets.count > 0 {
            if let totalDura = chosedAsset?.reduce(0.0, { partialResult, phasset in
                let dur = (phasset.mediaType == .video) ?  phasset.duration : 0
                return (partialResult ?? 0.0) + dur
            }), totalDura > 7200{
                let alertController = UIAlertController(title: nil, message: "album_tips_maxtime".BFLocale, preferredStyle: UIAlertController.Style.alert)
                let cancelAction = UIAlertAction(title: "option_ok".BFLocale, style: .default, handler: nil)
                alertController.addAction(cancelAction)
                self.present(alertController, animated: true, completion: nil)
                return
            }
//           判断是否时icloud网络资源
//            let arr = assets.filter { asset in
//                asset.
//            }
//
            let vc = INIntroduceController()
            vc.assets = assets
            navigationController?.pushViewController(vc, animated: true)
        } else {
            cShowHUB(superView: nil, msg: "album_tips_least".BFLocale)
        }
    }

    func clearCacheFile(at folderPath: String) {
        if let files = try? FileManager.default.contentsOfDirectory(atPath: folderPath) {
            for file in files {
                do {
                    try FileManager.default.removeItem(at: URL(fileURLWithPath: folderPath).appendingPathComponent(file))
                } catch {
                    BFLog(1, message: "\(error), \(file)")
                }
            }
        }
    }

    // MARK: -

    override open var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}
