PressureViewController.swift 18.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
//
//  PressureViewController.swift
//  Twear
//
//  Created by yangbin on 2022/2/28.
//

import UIKit
import Charts
import SwiftDate

class PressureViewController: UIViewController, DateSegmentViewDelegate, RangeSliderDelegate, ChartViewDelegate, BluetoothSyncDelegate {
    
    @IBOutlet weak var detailLabel: UILabel!
    @IBOutlet weak var locLabel2: UILabel!
    @IBOutlet weak var locLabel1: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var dateSegmentView: DateSegmentView!
    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var sliderView: RangeSliderView!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var pressureLabel: UILabel!
    @IBOutlet weak var averageLabel: UILabel!
    @IBOutlet weak var rangeLabel: UILabel!
    @IBOutlet weak var barChartView: BarChartView!
    @IBOutlet weak var detailView: UIView!
    
    private var dateType: DateType = .day
    private var selectedDate = Date()
    private lazy var monthDays = DateInRegion().monthDays
    private var minArray: [Int] = []
    private var maxArray: [Int] = []
    private var points: [Double] = []
    
    
    private var pressureArray: [PressureModel] = [] {
        didSet {
            if pressureArray.count == 0 {
                resetLabel()
            }
            points = []
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        dateSegmentView.selectedColor = UIColor.rgbColorFromHex(0x08890A)
        dateSegmentView.delegate = self
        sliderView.delegate = self
//        BluetoothManager.shared.registerSyncDelegate(self)
        titleLabel.text = LocString("压力")
        locLabel1.text = LocString("压力范围")
        locLabel2.text = LocString("平均值")
        detailLabel.text = LocString("正常")
        view.layoutIfNeeded()
        setupChartView()
        setupBarChartView()
        didSelectedDate(date: DateInRegion(), dateType: .day)
        // Do any additional setup after loading the view.
    }
    
    private func resetLabel() {
        pressureLabel.text = "--"
        averageLabel.text = "--"
        rangeLabel.text = "--"
        detailView.isHidden = true
    }
    
    private func updateLable(_ index: Int) {
        if pressureArray.count == 0 {
            resetLabel()
            return
        }
       
        if dateType == .day {
            let pressureResult = PressureModel.getAverageByDay(selectedDate)
//            value = pressureResult.pressure.value
            averageLabel.text = pressureResult.pressure.value == -1 ? "--" : "\(pressureResult.pressure.value)"
            rangeLabel.text = "\(pressureResult.min)-\(pressureResult.max)"
        } else {
//            value = pressureArray[index].value
            averageLabel.text = pressureArray[index].value == -1 ? "--" : "\(pressureArray[index].value)"
            rangeLabel.text = "\(minArray[index])-\(maxArray[index])"
        }
        let value = pressureArray[index].value
        detailView.isHidden = value == 0
        detailView.layer.borderWidth = 1
       
        switch value {
        case 1..<30:
            detailLabel.text = LocString("轻松")
            detailLabel.textColor = UIColor.rgbColorFromHex(0x01AEFF)
            detailView.layer.borderColor = UIColor.rgbColorFromHex(0x01AEFF).cgColor
        case 30..<60:
            detailLabel.text = LocString("正常")
            detailLabel.textColor = UIColor.black
            detailView.layer.borderColor = UIColor.rgbColorFromHex(0x2AE100).cgColor
        case 60..<80:
            detailLabel.text = LocString("中等")
            detailLabel.textColor = UIColor.rgbColorFromHex(0xFFC000)
            detailView.layer.borderColor = UIColor.rgbColorFromHex(0xFFC000).cgColor
        case 80..<100:
            detailLabel.text = LocString("偏高")
            detailLabel.textColor = UIColor.rgbColorFromHex(0xFF3C00)
            detailView.layer.borderColor = UIColor.rgbColorFromHex(0xFF3C00).cgColor
        default:
            detailLabel.text = LocString("正常")
        }
        
        pressureLabel.text = "\(pressureArray[index].value)"
        
        let sDate = pressureArray[index].date!
        switch dateType {
        case .day:
            dateLabel.text = sDate.toString(.custom("HH:mm"))
        case .week:
            dateLabel.text = sDate.toString(.custom("yyyy.MM.dd")) + " " + sDate.weekText// + " " + LocString("平均血氧")
        case .month:
            dateLabel.text = sDate.toString(.custom("yyyy.MM.dd"))// + " " + LocString("平均血氧")
        case .year:
            dateLabel.text = sDate.toString(.custom("yyyy.MM"))// + " " + LocString("平均血氧")
        }
    }
    
    
    //MARK: DateSegmentViewDelegate
    func didSelectedDate(date: DateInRegion, dateType: DateType) {
        self.dateType = dateType
        monthDays = date.monthDays
        selectedDate = date.date
        minArray = []
        maxArray = []
        
        var pressureResult: (pressureArray: [PressureModel], min: [Int], max: [Int]) = ([], minArray, maxArray)
        switch dateType {
        case .day:
            pressureResult.pressureArray = PressureModel.getPressureByDay(selectedDate)
            dateLabel.text = date.dateAt(.startOfDay).toString(.custom("HH:mm"))
        case .week:
            pressureResult = PressureModel.getPressureByWeek(selectedDate)
            dateLabel.text = (date.dateAt(.startOfWeek)+1.days).toString(.custom("yyyy.MM.dd")) + " " + LocString("周一") + " " + LocString("平均血氧")
        case .month:
            pressureResult = PressureModel.getPressureByMonth(selectedDate)
            dateLabel.text = date.dateAt(.startOfMonth).toString(.custom("yyyy.MM.dd")) + " " + LocString("平均血氧")
        case .year:
            pressureResult = PressureModel.getPressureByYear(selectedDate)
            dateLabel.text = date.dateAtStartOf(.year).toString(.custom("yyyy.MM")) + " " + LocString("平均血氧")
        }
        lineChartView.isHidden = !(dateType == .day)
        barChartView.isHidden = dateType == .day
    
        
        minArray = pressureResult.min
        maxArray = pressureResult.max
        pressureArray = pressureResult.pressureArray
        if dateType == .day {
            updateChartView()
        } else {
            updateBarChartView()
        }
    }
    
    //MARK: RangeSliderDelegate
    func sliderDidChanged(index: Int) {
        lineChartView.highlightValues([Highlight(x: points[index], y: 0, dataSetIndex: 0)])
        updateLable(index)
    }
    
    //MARK: ChartViewDelegate
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        if pressureArray.count == 1 {
            lineChartView.highlightValues([Highlight(x: points[0], y: 0, dataSetIndex: 0)])
        } else {
            sliderView.didSelectedValue(entry.x)
        }
    }
    
    
    private func updateChartView() {
        let xAxis = lineChartView.xAxis
        switch dateType {
        case .day:
            xAxis.valueFormatter = IndexAxisValueFormatter(values: DayXValues)
            xAxis.labelCount = 9
            xAxis.axisMinimum = -2.9
            xAxis.axisMaximum = 24 + 2
        case .week:
            xAxis.valueFormatter = IndexAxisValueFormatter(values: WeekXValues)
            xAxis.labelCount = 7
            xAxis.axisMinimum = -0.8
            xAxis.axisMaximum = 6 + 0.8
        case .month:
            xAxis.valueFormatter = IndexAxisValueFormatter(values: MonthXValues(monthDays))
            xAxis.labelCount = 8
            xAxis.axisMinimum = -3.5
            xAxis.axisMinLabels = 8
            xAxis.axisMaximum = Double(monthDays-1) + 2.1
        case .year:
            xAxis.valueFormatter = IndexAxisValueFormatter(values: MonthValues)
            xAxis.labelCount = 12
            xAxis.axisMinimum = -1.3
            xAxis.axisMaximum = 11 + 0.8
        }
        
        var dataEntries = [ChartDataEntry]()
        
        
        
        for pressure in pressureArray {
//            if pressure.value > 0 {
                var pointX: Double = 0
                switch dateType {
                case .day:
                    if pressure == pressureArray.last, pressure.date?.hour == 0 {
                        pointX = 24
                    } else {
                        pointX = Double(pressure.date!.hour)//+Double(pressure.date!.minute)/60.0
                    }
                case .week:
                    pointX = Double(pressure.date!.weekIndex)
                case .month:
                    pointX = Double(pressure.date!.day-1)
                case .year:
                    pointX = Double(pressure.date!.month-1)
                }
                points.append(pointX)
                dataEntries.append(ChartDataEntry(x: pointX, y: Double(pressure.value)))
//            }
        }
        
        
        if dataEntries.count == 1 {
            dataEntries.append(ChartDataEntry(x: dataEntries[0].x+0.2, y: dataEntries[0].y))
        }
        
        let dataSet = LineChartDataSet(entries: dataEntries)
        dataSet.drawCirclesEnabled = false
        dataSet.drawValuesEnabled = false
        dataSet.highlightEnabled = true//选中拐点,是否开启高亮效果(显示十字线)
        dataSet.highlightLineWidth = 1
        dataSet.highlightColor = UIColor.rgbColorFromHex(0x03D200)// 十字线颜色
        dataSet.drawHorizontalHighlightIndicatorEnabled = false
        dataSet.mode = .horizontalBezier
        dataSet.setColor(UIColor.rgbColorFromHex(0x2AA12B))
        dataSet.lineWidth = 1
        
        
        dataSet.drawFilledEnabled = true //填充绘制
        let gradientColors = [UIColor.rgbColorFromHex(0x16E017).cgColor, UIColor.rgbColorFromHex(0xFFFFFF).cgColor]
        let gradient = CGGradient(colorsSpace: nil, colors: gradientColors as CFArray, locations: [1.0, 0.0])
        dataSet.fillAlpha = 1
        dataSet.fill = Fill(linearGradient: gradient!, angle: 90)
        lineChartView.data = LineChartData(dataSets: [dataSet])
        lineChartView.highlightValues([Highlight(x: 0, y: 0, dataSetIndex: 0)])
        
        if dateType == .day {
            setupSliderViewScale()
        }
    }
    
    private func updateBarChartView() {
        let xAxis = barChartView.xAxis
        var barWidth: Double = 0.6
        switch dateType {
        case .day:
            xAxis.valueFormatter = IndexAxisValueFormatter(values: DayXValues)
            xAxis.labelCount = 9
            xAxis.axisMinimum = -2.9
            xAxis.axisMaximum = 24 + 2
        case .week:
            barWidth = 0.25
            xAxis.valueFormatter = IndexAxisValueFormatter(values: WeekXValues)
            xAxis.labelCount = 7
            xAxis.axisMinimum = -0.8
            xAxis.axisMaximum = 6 + 0.8
        case .month:
            xAxis.valueFormatter = IndexAxisValueFormatter(values: MonthXValues(monthDays))
            xAxis.labelCount = 8
            xAxis.axisMinimum = -3.5
            xAxis.axisMinLabels = 8
            xAxis.axisMaximum = Double(monthDays-1) + 2.1
        case .year:
            barWidth = 0.4
            xAxis.valueFormatter = IndexAxisValueFormatter(values: MonthValues)
            xAxis.labelCount = 12
            xAxis.axisMinimum = -1.3
            xAxis.axisMaximum = 11 + 0.8
        }
 
           
            var dataEntries = [BarChartDataEntry]()
           
        
        for pressure in pressureArray {
            if pressure.value > 0 {
                var pointX: Double = 0
                switch dateType {
                case .day:
                    if pressure == pressureArray.last, pressure.date?.hour == 0 {
                        pointX = 24
                    } else {
                        pointX = Double(pressure.date!.hour)+Double(pressure.date!.minute)/60.0
                    }
                case .week:
                    pointX = Double(pressure.date!.weekIndex)
                case .month:
                    pointX = Double(pressure.date!.day-1)
                case .year:
                    pointX = Double(pressure.date!.month-1)
                }
                points.append(pointX)
                dataEntries.append(BarChartDataEntry(x: pointX, y: Double(pressure.value)))
            }
        }
    
        
//            for sleep in sleepSummaryArray {
//                if sleep.sleepLength > 0 {
//                    var pointX: Double = 0
//                    switch dateType {
//                    case .day:
//                        break
//                    case .week:
//                        barWidth = 0.25
//                        pointX = Double(sleep.endDate!.weekIndex)
//                    case .month:
//                        pointX = Double(sleep.endDate!.day-1)
//                    case .year:
//                        barWidth = 0.4
//                        pointX = Double(sleep.endDate!.month-1)
//                    }
//                    points.append(SleepPoint(point: pointX, type: .awake, length: 0))
//                    dataEntries.append(BarChartDataEntry(x: pointX, y: Double(sleep.light+sleep.deep)/60))
//                }
//            }
            let dataSet = BarChartDataSet(entries: dataEntries)
            dataSet.colors = [UIColor.rgbColorFromHex(0x01CC08)]
            dataSet.highlightEnabled = true
            dataSet.highlightColor = UIColor.rgbColorFromHex(0x03D200)
            dataSet.drawValuesEnabled = false
            let chartData = BarChartData(dataSets: [dataSet])
            chartData.barWidth = barWidth
            barChartView.data = chartData
        
        
        barChartView.highlightValues([Highlight(x: 0, y: 0, dataSetIndex: 0)])
        if dateType != .day {
            setupSliderViewScale()
        }
        
    }
    
    private func setupSliderViewScale() {
        var endPointX: Int = 0
        switch dateType {
        case .day:
            endPointX = 24
        case .week:
            endPointX = 6
        case .month:
            endPointX = monthDays-1
        case .year:
            endPointX = 11
        }
        sliderView.setDrawSpace(startPointX: getChartViewX(0), endPointX: getChartViewX(endPointX), range: 0...endPointX, points: points, imageName: "slider_pressure", isLast: true)
    }
    
    private func getChartViewX(_ x: Int) -> CGFloat {
        if dateType == .day {
        return lineChartView.pixelForValues(x: Double(x), y: 0, axis: .left).x
        } else {
            return barChartView.pixelForValues(x: Double(x), y: 0, axis: .left).x
        }
    }
    
    private func setupChartView() {
        lineChartView.delegate = self
        lineChartView.chartDescription?.enabled = false //图描述
        lineChartView.legend.enabled = false //左下角图例
        lineChartView.setScaleEnabled(false) //可滑动
        lineChartView.rightAxis.enabled = false //不绘制右边轴的信息
        
        let leftAxis = lineChartView.leftAxis
        leftAxis.labelTextColor = ChartsTextColor
        leftAxis.labelFont = ChartsTextFont(11)
        leftAxis.yOffset = -5
        leftAxis.xOffset = -3
        leftAxis.gridLineDashLengths = [2.0, 2.0]  //设置虚线样式的网格线
        leftAxis.gridColor = LineColor
        leftAxis.gridLineWidth = 1
        leftAxis.axisLineWidth = 0
        leftAxis.drawGridLinesBehindDataEnabled = false
        leftAxis.labelPosition = .insideChart
        
        leftAxis.axisMinimum = 0 //设置左侧Y轴最小值
        leftAxis.axisMaximum = 100
        leftAxis.granularity = 20
        
        let litmitLine = ChartLimitLine(limit: 0, label: "")
        litmitLine.lineWidth = 1
        litmitLine.lineColor = LineColor
        leftAxis.addLimitLine(litmitLine)
        leftAxis.drawLimitLinesBehindDataEnabled = false  //设置限制线绘制在折线图的后面
        
        
        let xAxis = lineChartView.xAxis
        xAxis.granularity = 1 //间隔
        xAxis.labelPosition = .bottom
        xAxis.labelFont = ChartsTextFont(11)
        xAxis.labelTextColor = ChartsTextColor
        xAxis.drawGridLinesBehindDataEnabled = false
        xAxis.axisLineColor = LineColor
        xAxis.axisLineWidth = 1
        xAxis.gridLineDashLengths = [6, 666]
        xAxis.gridColor = LineColor
        xAxis.drawAxisLineEnabled = false
    }
    
    
    
    private func setupBarChartView() {
        barChartView.delegate = self
        barChartView.chartDescription?.enabled = false //图描述
        barChartView.legend.enabled = false //左下角图例
        barChartView.setScaleEnabled(false) //可滑动
        barChartView.rightAxis.enabled = false //不绘制右边轴的信息
        
        let leftAxis = barChartView.leftAxis
        leftAxis.labelTextColor = ChartsTextColor
        leftAxis.labelFont = ChartsTextFont(11)
        
        leftAxis.yOffset = -5
        leftAxis.xOffset = -3
        leftAxis.gridLineDashLengths = [2.0, 2.0]  //设置虚线样式的网格线
        leftAxis.gridColor = LineColor
        leftAxis.gridLineWidth = 1
        leftAxis.axisLineWidth = 0
        leftAxis.drawGridLinesBehindDataEnabled = false
        leftAxis.labelPosition = .insideChart
        
        
        leftAxis.axisMinimum = 0 //设置左侧Y轴最小值
        leftAxis.axisMaximum = 100
        leftAxis.granularity = 20
        
        let litmitLine = ChartLimitLine(limit: 0, label: "")
        litmitLine.lineWidth = 1
        litmitLine.lineColor = LineColor
        leftAxis.addLimitLine(litmitLine)
        leftAxis.drawLimitLinesBehindDataEnabled = false  //设置限制线绘制在折线图的后面
        
        
        let xAxis = barChartView.xAxis
        xAxis.granularity = 1 //间隔
        xAxis.labelPosition = .bottom
        xAxis.labelFont = ChartsTextFont(11)
        xAxis.labelTextColor = ChartsTextColor
        xAxis.drawGridLinesBehindDataEnabled = false
        xAxis.axisLineColor = LineColor
        xAxis.axisLineWidth = 1
        xAxis.gridLineDashLengths = [6, 666]
        xAxis.gridColor = LineColor
        xAxis.drawAxisLineEnabled = false
        
    }
    
    @IBAction func gotoReferenceVC(_ sender: Any) {
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Home", identifier: "PressReferenceVC")
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func back(_ sender: Any) {
        navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func share(_ sender: Any) {
        let shareView = ShareView(view.captureImage)
        shareView.show()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}