//
//  PQEditPublicCoverImageView.swift
//  BFFramework
//
//  Created by ak on 2021/7/22.
//  功能：选择封面

import BFCommonKit
import BFUIKit
import Foundation

class PQEditPublicCoverImageView: UIView {
    // 确认选择回调
    public var selectImageCallBack: ((_ image: UIImage?) -> Void)?

    // 从相册选择 BTN 点击回调 用于弹出照片选择界面
    public var selectPhotoBtnCallBack: (() -> Void)?
    // 选择的封面图片
    var selectImage: UIImage?
    // 最后选择的封面 btn 用于还原角标
    var lastSelectcoverImageBtn: UIButton?

    lazy var backView: UIView = {
        let backView = UIView()
        backView.addCorner(corner: 1.5)
        backView.backgroundColor = BFConfig.shared.otherTintColor
        return backView
    }()

    lazy var closeView: UIView = {
        let closeView = UIView()
        closeView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
        return closeView
    }()

    // 确定按钮
    lazy var compliteBtn: UIButton = {
        let compliteBtn = UIButton(type: .custom)
        compliteBtn.backgroundColor = UIColor.hexColor(hexadecimal: BFConfig.shared.styleColor.rawValue)
        compliteBtn.setTitle("确定", for: .normal)
        compliteBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        compliteBtn.setTitleColor(UIColor.hexColor(hexadecimal: "#FFFFFF"), for: .normal)
        compliteBtn.adjustsImageWhenHighlighted = false
        compliteBtn.tag = 2
        compliteBtn.addCorner(corner: 11)
        compliteBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return compliteBtn
    }()

    // 从相册选择
    lazy var selectPhotoBtn: UIButton = {
        let selectPhotoBtn = UIButton(type: .custom)

        selectPhotoBtn.setImage(UIImage.moduleImage(named: BFConfig.shared.editCoverimageSelectImage, moduleName: "BFStuckPointKit", isAssets: false), for: .normal)
        selectPhotoBtn.adjustsImageWhenHighlighted = false
        selectPhotoBtn.addCorner(corner: 11)
        selectPhotoBtn.tag = 1
        selectPhotoBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return selectPhotoBtn
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        closeView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewHidden)))
        backgroundColor = .clear

        addSubview(closeView)
        addSubview(backView)
        addSubview(compliteBtn)
        addSubview(selectPhotoBtn)

        // 9个封面
        for i in 0...8 {
            let coverImageBtn = UIButton(type: .custom)
            var frame: CGRect = .zero
            frame.size.width = 108.0 * cAdaptatWidth
            frame.size.height = 108.0 * cAdaptatWidth

            // 按钮横向间隔10，左边距16
            let spedScorp = 10.0 * cAdaptatWidth
            let spedHeght = 16.0 * cAdaptatWidth
            frame.origin.x = CGFloat((i % 3) * (Int(frame.size.width) + Int(spedScorp)) + Int(spedHeght))
            // 按钮竖向间隔10，左边距16
            frame.origin.y = floor(CGFloat(i / 3)) * (frame.size.height + spedScorp) + spedHeght
            coverImageBtn.frame = frame
            coverImageBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#F6F6F6")
            coverImageBtn.tag = (i + 1) * 100
            coverImageBtn.adjustsImageWhenHighlighted = false
            coverImageBtn.imageView?.contentMode = .scaleAspectFit
            coverImageBtn.addTarget(self, action: #selector(coverImageBtnClick(sender:)), for: .touchUpInside)
            // 选中后的角标
            let iconView = UIImageView(frame: CGRect(x: frame.size.width - 22.0 - 6, y: 6, width: 22, height: 22))
            iconView.image = UIImage.moduleImage(named: BFConfig.shared.editCoverimageSelectedImage, moduleName: "BFStuckPointKit", isAssets: false)

            iconView.tag = 1000
            if i == 0 {
                iconView.isHidden = false
                lastSelectcoverImageBtn = coverImageBtn
            } else {
                iconView.isHidden = true
            }

            coverImageBtn.addSubview(iconView)
            backView.addSubview(coverImageBtn)
        }

        backView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(459 * cAdaptatWidth + cAKSafeAreaHeight)
            make.bottom.equalToSuperview()
        }

        closeView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(cScreenHeigth - 459)
            make.top.equalToSuperview()
        }

        selectPhotoBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16 * cAdaptatWidth)
            make.width.equalTo(164 * cAdaptatWidth)
            make.height.equalTo(54 * cAdaptatWidth)
            make.bottom.equalToSuperview().offset(-19 - cAKSafeAreaHeight)
        }

        compliteBtn.snp.makeConstraints { make in
            make.left.equalTo(selectPhotoBtn.snp.right).offset(14.0 * cAdaptatWidth)
            make.width.equalTo(164 * cAdaptatWidth)
            make.height.equalTo(54 * cAdaptatWidth)
            make.top.equalTo(selectPhotoBtn.snp.top)
        }
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func viewHidden() {
        isHidden = true
        if selectImageCallBack != nil {
            selectImageCallBack!(nil)
        }
    }

    func show(videoURL: URL, duration: Float64) {
        isHidden = false

        PQVideoSnapshotUtil.videoSnapshot(videoURL: videoURL, duration: TimeInterval(duration), count: 9) { [weak self] images in
            DispatchQueue.main.async {
                for i in 0...(images?.count ?? 0) - 1 {
                    let btn = self?.backView.viewWithTag((i + 1) * 100) as? UIButton
                    btn?.setImage(images?[i], for: .normal)
                }
            }
        }
    }

    /// 按钮点击事件
    /// - Parameter sender: <#sender description#>
    /// - Returns: <#description#>
    @objc func btnClick(sender: UIButton?) {
        switch sender?.tag {
        case 1:
            BFLog(message: "选择图库")
            if selectPhotoBtnCallBack != nil {
                selectPhotoBtnCallBack!()
            }

        case 2:
            BFLog(message: "确认选择")
            if selectImageCallBack != nil {
                selectImageCallBack!(selectImage)
            }
            isHidden = true
        default:
            break
        }
    }

    // 封面选择
    @objc func coverImageBtnClick(sender: UIButton?) {
        // 角标的显示
        lastSelectcoverImageBtn?.viewWithTag(1000)?.isHidden = true
        sender?.viewWithTag(1000)?.isHidden = false
        lastSelectcoverImageBtn = sender

        BFLog(message: "封面选择了\(String(describing: sender?.tag))")
        selectImage = sender?.currentImage
    }
}
