//
//  DiscoverNewsView.swift
//  wyy
//
//  Created by 施书顺 on 2021/3/5.
//

import UIKit

class DiscoverNewsView: UIView, UIScrollViewDelegate {
    
    let scrollView = UIScrollView()
    let pageControl = UIPageControl()
    var timer: Timer?
    var pageImage = [UIImage]()
    var scrollImageViews = [UIImageView]()
    var currentIndex: Int = 0

    init(){
        super.init(frame: CGRect.zero)
        pageImage = [UIImage(named: "p1")!,
                     UIImage(named: "p2")!,
                     UIImage(named: "p3")!,
                     UIImage(named: "p4")!,
                     UIImage(named: "p5")!]

        addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(0)
            make.width.equalTo(350)
            make.height.equalTo(200)
        }
        scrollView.layer.cornerRadius = 5
        scrollView.backgroundColor = .gray
        scrollView.isPagingEnabled = true
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.contentSize = CGSize(width: 350 * 3, height: 200)
//        scrollView.scrollRectToVisible(CGRect(x: 0, y: -150, width: 350, height: 200), animated: false)
        scrollView.delegate = self
        
        for index in -1 ... 1 {
            let imageView = UIImageView(frame: CGRect(x: CGFloat(index + 1) * 350, y: 0, width: 350, height: 200))
            imageView.isUserInteractionEnabled = true
            imageView.contentMode = .scaleToFill
            imageView.image = pageImage[(index + pageImage.count) % pageImage.count]
            scrollImageViews.append(imageView)
            scrollView.addSubview(imageView)
        }
        
        addSubview(pageControl)
        pageControl.isUserInteractionEnabled = true
        pageControl.pageIndicatorTintColor = UIColor.black
        pageControl.currentPageIndicatorTintColor = UIColor.red
        pageControl.numberOfPages = pageImage.count
        pageControl.currentPage = 0
        pageControl.snp.makeConstraints { make in
            make.width.equalTo(200)
            make.height.equalTo(20)
            make.bottom.equalTo(scrollView.snp.bottom).offset(-10)
            make.centerX.equalToSuperview()
        }
        pageControl.addTarget(self, action: #selector(pageClick(sender:)), for: .valueChanged)
        startTimer()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func pageClick(sender: UIPageControl){
        stopTimer()
        if (sender.currentPage > currentIndex){
            UIView.animate(withDuration: 0.4, animations: {
                self.scrollView.contentOffset = CGPoint(x: self.scrollView.frame.width * 2, y: 0)
            }, completion: { ok in
                if ok {
                    self.refreshPage()
                }
            })
        } else {
            UIView.animate(withDuration: 0.4, animations: {
                self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
            }, completion: { ok in
                if ok {
                    self.refreshPage()
                }
            })
        }
        startTimer()
    }
    
    func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    
    func stopTimer(){
        timer?.invalidate()
        timer = nil
    }
    
    func refreshPage() {
        let count = pageImage.count
        let offset = scrollView.contentOffset
        if offset.x > scrollView.frame.width {
            currentIndex = (currentIndex + 1) % count
        } else if offset.x < scrollView.frame.width {
            currentIndex = (currentIndex - 1 + count) % count
        }
        let leftIndex = (currentIndex - 1 + count) % count
        let rightIndex = (currentIndex + 1) % count
        
        scrollImageViews[0].image = pageImage[leftIndex]
        scrollImageViews[1].image = pageImage[currentIndex]
        scrollImageViews[2].image = pageImage[rightIndex]
        scrollView.setContentOffset(CGPoint(x: scrollView.frame.width, y: 0), animated: false)
        pageControl.currentPage = currentIndex
    }
    
    @objc func timerAction() {
        UIView.animate(withDuration: 0.5, animations: {
            self.scrollView.contentOffset = CGPoint(x: self.scrollView.frame.width * 2, y: 0)
        }, completion: { ok in
            if ok {
                self.refreshPage()
            }
        })
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        stopTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        startTimer()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        refreshPage()
    }
    
}
