//
//  SHRecordDetailsCell.swift
//  ShorthandMaster
//
//  Created by 明津李 on 2020/9/23.
//  Copyright © 2020 明津李. All rights reserved.
//

import UIKit

class SHRecordDetailsCell: UITableViewCell {
    
    @IBOutlet weak var leftConstraint: NSLayoutConstraint?
    @IBOutlet weak var intervalConstraint: NSLayoutConstraint?
    @IBOutlet weak var bgView: UIView?
    @IBOutlet weak var selectedBtn: UIButton?
    @IBOutlet weak var icloudBtn: UIButton?
    
    @IBOutlet weak var titleName: UILabel?
    @IBOutlet weak var timeLab: UILabel?
    @IBOutlet weak var txtLab: UILabel?
    @IBOutlet weak var duringLab: UILabel?
    
    var selectCallBack: ((NSInteger, Bool)->Void)?
    
    private var _model: SHRecordModel?
    var model: SHRecordModel {
        set{
            _model = newValue
            
            titleName?.text = newValue.rename
            timeLab?.text = Date.getShortTimeByStamp_record(timestamp: Int64(newValue.modifyDate.timeIntervalSince1970))

            let txts = newValue.txt.components(separatedBy: "\n")
            var result = txts.reduce("" , { x, y in
                if x.length == 0{
                    return x + y
                }else{
                    return x + "\n" + y
                }
            })
            if result.hasSuffix("\n"){
                result = result.substring(0, length: result.length-2) ?? ""
            }
            txtLab?.text = result

            duringLab?.text = countSecond(newValue.during)
            selectedBtn?.isSelected = model.selected
            icloudBtn?.isSelected = model.icloud
        }
        get{
            return _model!
        }
    }
    
    var searchStr: String = "" {
        didSet{
            
            let titleAtt = NSMutableAttributedString.init(string: model.rename)

            let ranges = self.rangeOfString(string: model.rename.lowercased() as NSString, andInString: searchStr.lowercased())
            
            for range in ranges {
                titleAtt.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hexStr: "4183F2"), range: range)
            }
            
            titleName?.attributedText = titleAtt
            
            let txtAtt = NSMutableAttributedString.init(string: model.txt)

            let txtRanges = self.rangeOfString(string: model.txt.lowercased() as NSString, andInString: searchStr.lowercased())
            
            for range in txtRanges {
                txtAtt.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hexStr: "4183F2"), range: range)
            }
            
            txtLab?.attributedText = txtAtt
        }
    }
    
    private var _edit: Bool?
    var edit: Bool {
        set{
            _edit = newValue
            if _edit == true{
                UIView.animate(withDuration: 0.33) {
                    self.leftConstraint?.constant = 10
                    self.intervalConstraint?.constant = 40
                    self.selectedBtn?.isHidden = false
                }
            }else{
                UIView.animate(withDuration: 0.33) {
                    self.leftConstraint?.constant = 20
                    self.intervalConstraint?.constant = 0
                    self.selectedBtn?.isHidden = true
                }
            }
        }
        get{
            return _edit!
        }
    }
    
    /// 获取字符出现的位置信息(支持多次位置获取)
    /// - Parameter string: 原始文本
    /// - Parameter inString: 需要查找的字符
    private func rangeOfString(string:NSString,
                               andInString inString:String) -> [NSRange] {
        
        var arrRange = [NSRange]()
        var _fullText = string
        var rang:NSRange = _fullText.range(of: inString)
        
        while rang.location != NSNotFound {
            var location:Int = 0
            if arrRange.count > 0 {
                if arrRange.last!.location + arrRange.last!.length < string.length {
                     location = arrRange.last!.location + arrRange.last!.length
                }
            }
 
            _fullText = NSString.init(string: _fullText.substring(from: rang.location + rang.length))
 
            if arrRange.count > 0 {
                  rang.location += location
            }
            arrRange.append(rang)
            
            rang = _fullText.range(of: inString)
        }
        
        return arrRange
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        bgView?.backgroundColor = UIColor.init(hexStr: "FAFAFA")
        bgView?.layer.borderWidth = 1
        bgView?.layer.borderColor = UIColor.init(hexStr: "EEEEEE").cgColor
        
        selectedBtn?.addTarget(self, action: #selector(selectBtnClick(_:)), for: .touchUpInside)
        icloudBtn?.addTarget(self, action: #selector(selectBtnClick(_:)), for: .touchUpInside)
    }
    
    @objc func selectBtnClick(_ sender:UIButton){
        if sender == selectedBtn {
            sender.isSelected = !sender.isSelected
            selectCallBack?(0, sender.isSelected)
        }else{
            selectCallBack?(1, sender.isSelected)
        }
    }
    
    @objc private func countSecond(_ during:NSInteger) -> String {
        //小时计算
        let hours = (during)%(24*3600)/3600;
        //分钟计算
        let minutes = (during)%3600/60;
        //秒计算
        let second = (during)%60;
        let timeString  = String(format: "%02lu:%02lu:%02lu", hours, minutes, second)
        return timeString
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
