//
//  MVMineProductController.swift
//  MusicVideoPlus
//
//  Created by SanW on 2021/6/22.
//


import UIKit
import BFUIKit

class MVMineProductController: BFBaseViewController {
    var itemsList: [PQVideoListModel] = Array<PQVideoListModel>.init()
    var pageNum: Int = 1
    let margin: CGFloat = 14
    let headH: CGFloat = cDefaultMargin * 9

    lazy var headInfoView: MVMineHeadInfoView = {
        let headInfoView = MVMineHeadInfoView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: headH), margin: 0)
        return headInfoView
    }()

    lazy var flowLayout: PQCollectionViewFlowlayout = {
        let flowLayout = PQCollectionViewFlowlayout()
        flowLayout.columnCount = 2
        flowLayout.sectionInset = .zero
        flowLayout.minimumLineSpacing = cDefaultMargin / 2
        flowLayout.minimumInteritemSpacing = cDefaultMargin / 2
        flowLayout.headerH = headH
        return flowLayout
    }()

    lazy var collectionView: UICollectionView = {
        let width = (cScreenWidth - 30) / 2
        let proCollectView = UICollectionView(frame: CGRect(x: margin, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth - margin * 2, height: view.frame.height - cDevice_iPhoneNavBarAndStatusBarHei - cSafeAreaHeight), collectionViewLayout: flowLayout)
        proCollectView.register(MVMineProductCell.self, forCellWithReuseIdentifier: String(describing: MVMineProductCell.self))
        proCollectView.showsVerticalScrollIndicator = false
        proCollectView.delegate = self
        proCollectView.dataSource = self
        proCollectView.backgroundColor = UIColor.white
        proCollectView.addRefreshView { [weak self] isRefresh in
            self?.loadRequestData(isRefresh: isRefresh)
        }
        return proCollectView
    }()

    lazy var emptyView: MVProductEmptyView = {
        let emptyView = MVProductEmptyView(frame: CGRect(x: 0, y: headH, width: collectionView.frame.width, height: collectionView.frame.height - headH))
        emptyView.btnClickHandle = { [weak self] _ in
            let vc = PQStuckPointMaterialController()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        emptyView.isHidden = true
        return emptyView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
        collectionView.addSubview(emptyView)
        collectionView.addSubview(headInfoView)
        leftBackButton()
        loadRequestData()
        setTitle(title: BFLoginUserInfo.shared.nickName, color: UIColor(white: 0, alpha: 0))
        MVMineViewModel.userInfoData { [weak self] count, avatarUrl, nickName, msg in
            if count != nil {
                BFLoginUserInfo.shared.videos = "\(count ?? 0)"
            }
            if avatarUrl != nil, (avatarUrl?.count ?? 0) > 0 {
                BFLoginUserInfo.shared.avatarUrl = avatarUrl ?? ""
            }
            if nickName != nil, (nickName?.count ?? 0) > 0 {
                BFLoginUserInfo.shared.nickName = nickName ?? ""
            }
            if msg == nil {
                saveUserDefaults(key: cUserInfoStorageKey, value: BFLoginUserInfo.shared.toString())
                self?.headInfoView.addData()
            }
        }

        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: .ot_shanyinApp_viewPage_mineTab, pageSource: .sp_shanyinApp_mine, extParams: nil, remindmsg: "")
    }

    /// 请求网络数据
    /// - Parameter isRefresh: <#isRefresh description#>
    /// - Returns: <#description#>
    func loadRequestData(isRefresh: Bool = true) {
        BFLoadingHUB.shared.showHUB(superView:view)
        if isRefresh {
            pageNum = 1
        } else {
            pageNum = pageNum + 1
        }
        MVMineViewModel.userVideoListData(pageNum: pageNum) { [weak self] videoList, _ in
            if videoList != nil {
                if (videoList?.count ?? 0) > 0 {
                    if isRefresh {
                        self?.itemsList = videoList!
                    } else {
                        self?.itemsList = self!.itemsList + videoList!
                    }
                    if self?.itemsList != nil {
                        self?.flowLayout.findList = self?.itemsList as! [Any]
                    }
                    self?.collectionView.reloadData()
                    self?.emptyView.isHidden = true
                } else {
                    self?.emptyView.isHidden = false
                }
            } else {
                cShowHUB(superView: nil, msg: "没有网络连接")
                self?.pageNum = (self?.pageNum ?? 1) - 1
            }
            if isRefresh {
                self?.collectionView.mj_header?.endRefreshing()
                self?.collectionView.mj_footer?.resetNoMoreData()
            } else {
                self?.collectionView.mj_footer?.endRefreshing()
            }
            if (videoList?.count ?? 0) < 20, videoList != nil {
                self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }
            BFLoadingHUB.shared.dismissHUB(superView:(self?.view ?? UIView()))
           
        }
    }
}

extension MVMineProductController: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return itemsList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let itemData = itemsList[indexPath.item]
        let cell = MVMineProductCell.productCell(collectionView: collectionView, indexPath: indexPath)
        cell.videoData = itemData
        cell.btnClickHandle = { [weak self] sender, videoData in
            self?.btnClickHandle(sender: sender, videoData: videoData, indexPath: indexPath)
        }
        return cell
    }

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if itemsList[indexPath.item].auditStatus != 5 || itemsList[indexPath.item].transcodeStatus != 3 {
            return
        }
        let playVC = MVPlayViewController()
        playVC.itemsList = itemsList
        playVC.currentIndex = indexPath
        playVC.pageNum = pageNum
        navigationController?.pushViewController(playVC, animated: true)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        BFLog(message: "scrollView.contentOffset.y = \(scrollView.contentOffset.y)")
        if scrollView.contentOffset.y <= 0 {
            navTitleLabel?.textColor = UIColor(white: 0, alpha: 0)
        } else if scrollView.contentOffset.y >= headH {
            navTitleLabel?.textColor = UIColor(white: 0, alpha: 1)
        } else {
            var alpha: CGFloat = (scrollView.contentOffset.y / headH)
            if alpha < 0 {
                alpha = 0
            }
            if alpha > 1 {
                alpha = 1
            }
            navTitleLabel?.textColor = UIColor(white: 0, alpha: alpha)
        }
    }

    /// 处理按钮点击事件
    /// - Parameters:
    ///   - sender: <#sender description#>
    ///   - videoData: <#videoData description#>
    func btnClickHandle(sender: UIButton, videoData: PQVideoListModel?, indexPath: IndexPath) {
        switch sender.tag {
        case 1:
            let seleView = PQSelectedOprationView.showSelectedOprationView(itemList: ["删除视频"]) { sender in
                if sender.tag == 1 {
                    if !isNetConnected() {
                        cShowHUB(superView: nil, msg: "没有网络连接")
                        return
                    }
                    PQBaseViewModel.deleteVideo(videoId: Int(videoData?.uniqueId ?? "0") ?? 0) { [weak self] isSuccess, videoId, _ in
                        if isSuccess {
                            self?.itemsList.removeAll(where: { tempVideo in
                                tempVideo.uniqueId == "\(videoId)"
                            })
                            self?.flowLayout.findList = self?.itemsList as! [PQVideoListModel]
                            self?.collectionView.reloadData()
                            cShowHUB(superView: nil, msg: "删除成功")
                            if (self?.itemsList.count ?? 0) <= 0 {
                                self?.loadRequestData()
                            }
                            var videos: Int = (Int(BFLoginUserInfo.shared.videos) ?? 0) - 1
                            if videos < 0 {
                                videos = 0
                            }
                            BFLoginUserInfo.shared.videos = "\(videos)"
                            self?.headInfoView.updateProducts()
                        } else {
                            cShowHUB(superView: nil, msg: "删除失败")
                        }
                    }
                }
            }
            seleView.contentView.backgroundColor = UIColor.hexColor(hexadecimal: "#F2F2F2")
            seleView.cancelBtn.backgroundColor = UIColor.white
            seleView.cancelBtn.setTitleColor(UIColor.black, for: .normal)
            seleView.cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
            let firstBtn: UIButton? = seleView.contentView.subviews[1] as? UIButton
            firstBtn?.backgroundColor = UIColor.white
            firstBtn?.setTitleColor(UIColor.hexColor(hexadecimal: "#FF0000"), for: .normal)
            firstBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
            seleView.contentView.subviews[2].backgroundColor = UIColor.hexColor(hexadecimal: "#F2F2F2")
        case 2:
            PQBaseViewModel.videoDetailInfo(videoId: videoData?.uniqueId ?? "") { [weak self] videoList, _, msg in
                if (videoList?.count ?? 0) > 0, msg == nil, !(videoList?.first?.first?.transcodeStatus == 2 || videoList?.first?.first?.auditStatus == 1 || videoList?.first?.first?.transcodeStatus == 1) {
                    let tempVideoData = videoList?.first?.first
                    if tempVideoData != nil {
                        self?.itemsList[indexPath.item] = tempVideoData!
                    }
                    self?.collectionView.reloadData()
                    self?.collectionView(self!.collectionView, didSelectItemAt: indexPath)
                } else {
                    cShowHUB(superView: nil, msg: "请稍后再刷新")
                }
            }
        default:
            break
        }
    }

    @objc func btnClick(sender _: UIButton) {}
}
