//
//  ViewController.swift
//  SHZX
//
//  Created by 曹云霄 on 2018/3/6.
//  Copyright © 2018年 上海勾芒信息科技有限公司. All rights reserved.
//

import UIKit
import Charts
import Kingfisher

class ViewController: UIViewController {

    /// 折线图
    @IBOutlet weak var lineChartBgView: UIView!
    /// 柱状图
    @IBOutlet weak var histogramBgView: UIView!
    @IBOutlet weak var photoImg1BgView: UIView!
    @IBOutlet weak var photoImg1: UIImageView!
    @IBOutlet weak var photoImg2BgView: UIView!
    @IBOutlet weak var photoImg2: UIImageView!
    /// 折线图
    @IBOutlet weak var chartView: LineChartView!
    let width: CGFloat = UIScreen.main.bounds.size.width
    let height: CGFloat = UIScreen.main.bounds.size.height
    var oldFrame: CGRect!
    /// 横坐标title
    final lazy var xTitles: Array<String> = {
        var xTitles = ["8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23"]
        return xTitles
    }()
    
    /// 柱状图
    @IBOutlet weak var barChartView: BarChartView!
    
    /// 登陆用户信息
    var userData: LoginData!
    
    
    var imageArray: Array<String> = {
       var imageArray = ["http://121.40.116.34:8077/KlImages/KlyAPI?ID=2&Type=SHZX","http://121.40.116.34:8077/KlImages/KlyAPI?ID=2&Type=SHZX"]
        return imageArray
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loginAction()
        addTapGestureRecognizer()
        setupPhotoImg()
        setupLineChartView()
        setupBarChartView()
    }
    
    // MARK: - 登陆
    fileprivate func loginAction() {
        Network.request(target: .Login(), success: {[weak self] (json) in
            let model = LoginResult(fromJson: json)
            if model.success {
                self?.userData = model.data
                self?.getSpotsDataAction()
                self?.getDensityDataAction()
            }else {
                ShowMessage(model.message)
            }
        }) { (error) in
            ShowMessage(error.localizedDescription)
        }
    }
    
    // MARK: - 拍摄照片
    fileprivate func setupPhotoImg() {
        photoImg1.kf.setImage(with: ImageResource(downloadURL: URL(string: imageArray.first!)!), placeholder: nil, options: [KingfisherOptionsInfoItem.transition(ImageTransition.fade(1)), KingfisherOptionsInfoItem.forceRefresh], progressBlock: nil, completionHandler: nil)
        photoImg2.kf.setImage(with: ImageResource(downloadURL: URL(string: imageArray.last!)!), placeholder: nil, options: [KingfisherOptionsInfoItem.transition(ImageTransition.fade(1)), KingfisherOptionsInfoItem.forceRefresh], progressBlock: nil, completionHandler: nil)
    }
    
    // MARK: - 获取折线图数据
    fileprivate func getSpotsDataAction() {
        let time = Date().dateToDateString(dateFormat: "yyyy-MM-dd HH:mm:ss")
        Network.request(target: .Spots(userData.uuid, time), success: {[weak self] (json) in
            let model = SpotsResult(fromJson: json)
            if model.success {
                var todayValue = Array<Double>()
                var yesterdayValue = Array<Double>()
                for i in 0..<self!.xTitles.count {
                    if let count = model.data.last?.hour.object(forKey: self!.xTitles[i]) {
                        yesterdayValue.append(count as! Double)
                    }else {
                        yesterdayValue.append(0)
                    }
                    if let count = model.data.first?.hour.object(forKey: self!.xTitles[i]) {
                        todayValue.append(count as! Double)
                    }else {
                        todayValue.append(0)
                    }
                }
                self?.setChart(todayValue: todayValue, yesterdayValue: yesterdayValue)
            }else {
                ShowMessage(model.message)
            }
        }) { (error) in
            ShowMessage(error.localizedDescription)
        }
    }
    
    // MARK: - 获取柱状图数据
    fileprivate func getDensityDataAction() {
        let time = Date().dateToDateString(dateFormat: "yyyy-MM-dd HH:mm:ss")
        Network.request(target: .GETDensity(userData.uuid, time), success: {[weak self] (json) in
            let model = DensityResult(fromJson: json)
            if model.success {
                var todayValue = Array<Double>()
                var titleArray = Array<String>()
                for i in 0..<model.data.count {
                    titleArray.append(model.data[i].deviceGroup)
                    todayValue.append(Double(model.data[i].displayDensity)!)
                }
                self?.setBarChart(todayValue: todayValue, title: titleArray)
            }else {
                ShowMessage(model.message)
            }
        }) { (error) in
            ShowMessage(error.localizedDescription)
        }
    }
    
    // MARK: - 设置折线图
    fileprivate func setupLineChartView() {
        chartView.chartDescription?.text = nil
        chartView.legend.form = .none
        chartView.highlightPerTapEnabled = false
        chartView.rightAxis.drawAxisLineEnabled = false
        chartView.rightAxis.enabled = false
        chartView.leftAxis.axisLineColor = UIColor.white
        chartView.leftAxis.gridColor = UIColor.clear
        chartView.leftAxis.labelTextColor = UIColor.white
        chartView.doubleTapToZoomEnabled = false
    }
    
    // MARK: - 填充折线图数据
    func setChart(todayValue: [Double],yesterdayValue: [Double]) {
        var todayDataEntries: [ChartDataEntry] = []
        var tyesterdayDataEntries: [ChartDataEntry] = []
        for i in 0..<xTitles.count {
            let time = Date().hour
            if Int(xTitles[i])! <= time {
                let dataEntry = ChartDataEntry(x: Double(i), y: todayValue[i])
                todayDataEntries.append(dataEntry)
            }
            let dataEntry1 = ChartDataEntry(x: Double(i), y: yesterdayValue[i])
            tyesterdayDataEntries.append(dataEntry1)
        }
        let todayDataSet = LineChartDataSet(values: todayDataEntries, label: nil)
        todayDataSet.setCircleColor(UIColor.red)
        todayDataSet.circleRadius = 4
        todayDataSet.circleHoleColor = UIColor.red
        todayDataSet.colors = [UIColor.red]
        todayDataSet.valueColors = [UIColor.white]
        
        let yesterdayDataSet = LineChartDataSet(values: tyesterdayDataEntries, label: nil)
        yesterdayDataSet.setCircleColor(UIColor.green)
        yesterdayDataSet.circleRadius = 4
        yesterdayDataSet.circleHoleColor = UIColor.green
        yesterdayDataSet.colors = [UIColor.green]
        yesterdayDataSet.valueColors = [UIColor.white]
        yesterdayDataSet.lineDashLengths = [5.0, 5.0]
        
        let data = LineChartData(dataSets: [todayDataSet,yesterdayDataSet])
        chartView.data = data
        let formatter = ChartViewAxisValueFormatter()
        formatter.titleArray = xTitles
        chartView.xAxis.valueFormatter = formatter
        chartView.xAxis.granularity = 1.0
        chartView.xAxis.drawGridLinesEnabled = false
        chartView.xAxis.labelCount = xTitles.count
        chartView.xAxis.labelPosition = .bottom
        chartView.xAxis.gridColor = UIColor.clear
        chartView.xAxis.labelTextColor = UIColor.white
        chartView.animate(xAxisDuration: 1)
    }
    
    // MARK: - 设置柱状图
    fileprivate func setupBarChartView() {
        barChartView.chartDescription?.text = nil
        barChartView.legend.form = .none
        barChartView.highlightPerTapEnabled = false
        barChartView.rightAxis.drawAxisLineEnabled = false
        barChartView.rightAxis.enabled = false
        barChartView.leftAxis.axisLineColor = UIColor.white
        barChartView.leftAxis.gridColor = UIColor.clear
        barChartView.leftAxis.labelTextColor = UIColor.white
        barChartView.leftAxis.valueFormatter = AxisValueFormatter()
        barChartView.xAxis.labelPosition = .bottom
        barChartView.xAxis.gridColor = UIColor.clear
        barChartView.xAxis.labelTextColor = UIColor.white
    }
    
    // MARK: - 填充柱状图数据
    fileprivate func setBarChart(todayValue: [Double], title: [String]) {
        var dataEntris = [BarChartDataEntry]()
        for i in 0..<todayValue.count {
            let dataEntry = BarChartDataEntry(x: Double(i), y: todayValue[i])
            dataEntris.append(dataEntry)
        }
        barChartView.xAxis.labelCount = title.count
        let chartDataSet = BarChartDataSet(values: dataEntris, label: nil)
        chartDataSet.valueTextColor = UIColor.white
        chartDataSet.setColors(NSUIColor.RGB(35, g: 145, b: 205),NSUIColor.RGB(37, g: 181, b: 176))
        let chartData = BarChartData(dataSet: chartDataSet)
        chartData.setValueFormatter(DigitValueFormatter())
        self.barChartView.data = chartData
        let formatter = BarChartViewAxisValueFormatter()
        formatter.titleArray = title
        barChartView.xAxis.valueFormatter = formatter
        self.barChartView.animate(yAxisDuration: 1.0, easingOption: .easeInBack)
    }
    
    // MARK: - 添加点击手势
    fileprivate func addTapGestureRecognizer() {
        photoImg1BgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.zoomClickAction)))
        photoImg2BgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.zoomClickAction)))
    }
    
    // MARK: - 缩放
    @objc open func zoomClickAction(_ tap: UIGestureRecognizer) {
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let detailVc = storyBoard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        detailVc.imageString = imageArray[tap.view!.tag]
        present(detailVc, animated: true, completion: nil)
    }
    
    // MARK: - 更新数据
    @IBAction func updateBtnClickAction(_ sender: UIButton) {
        getSpotsDataAction()
        getDensityDataAction()
        setupPhotoImg()
    }
}




















