//
//  YHHKPlanItemView.swift
//  galaxy
//
//  Created by davidhuangA on 2024/4/1.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SwifterSwift

class YHHKPlanItemView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private lazy var line : UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    
    private lazy var numberLabel : UILabel = {
        let view = UILabel()
        view.text = "--/300"
        view.font = UIFont.PFSC_R(ofSize: 12)
        view.textColor = UIColor.placeHolderColor
        view.textAlignment = .right
        return view
    }()
    
    
    private lazy var myTextView : UITextView = {
        let view = UITextView()
        view.textColor = UIColor.mainTextColor
        view.font = UIFont.PFSC_R(ofSize: 14)
        view.backgroundColor = .clear
        
        view.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//        view.backgroundColor = .red
        return view
    }()
    
    
    
    private lazy var nameLable : UILabel = {
        let lable0 = UILabel(text: "1、主要事业成就")
        lable0.textColor = UIColor.mainTextColor
        lable0.font = UIFont.PFSC_M(ofSize: 17)
        return lable0
    }()
    
    
    private lazy var iconImageV : UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "other_info_warning")
        view.contentMode = .scaleAspectFill
        view.isHidden = true
        return view
    }()
    
    
    var dataMode : YHHKPlanDocModel? {
        didSet {
            updateUI()
        }
    }
    
    let holdView : UIView = UIView()
    
    //提示文字
    var tipsTxt : String = "请输入,300字内"
//    var maxNumbler : Int = 300
    var maxNumbler : Int = 300 {
        didSet {
            tipsTxt = "请输入," + maxNumbler.string + "字内"
        }
    }
    
    //提示lable
    private lazy var tipsLable : UILabel = {
        let lable = UILabel(text: tipsTxt)
        lable.textColor = UIColor.yhGreyColor //#94A3B8
        lable.font = UIFont.PFSC_R(ofSize: 14)
        return lable
    }()
}

private extension YHHKPlanItemView {
    func initView() {
        backgroundColor = .clear
        
        //应香港入境处最新要求，
        //赴港计划书格式、内容作出调整，共分为六部分，每部分不得超过100字(不含标点)
        //。其中“赴港具体计划”仅代表个人预期规划，无须严格执行。
        
        addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
        
        holdView.backgroundColor = UIColor.white
        addSubview(holdView)
        
        holdView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(line.snp.top)
        }
        
        holdView.addSubview(nameLable)
        nameLable.snp.makeConstraints { make in
            make.top.equalTo(18)
            make.left.equalTo(0)
            make.height.equalTo(20)
        }
        
        
        holdView.addSubview(iconImageV)
        iconImageV.snp.makeConstraints { make in
            make.left.equalTo(nameLable.snp.right).offset(4)
            make.centerY.equalTo(nameLable)
            make.height.width.equalTo(16)
        }
        
        
        let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapButton(gestureRecognizer:)))
        iconImageV.isUserInteractionEnabled = true
        iconImageV.addGestureRecognizer(tap)
        
        
        let subHoldView : UIView = UIView()
        subHoldView.backgroundColor = UIColor.contentBkgColor
        subHoldView.layer.cornerRadius = kCornerRadius6
        subHoldView.clipsToBounds = true
        holdView.addSubview(subHoldView)
        subHoldView.snp.makeConstraints { make in
            make.top.equalTo(nameLable.snp.bottom).offset(12)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(line.snp.top).offset(-18)
        }
        
        subHoldView.addSubview(numberLabel)
        numberLabel.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.height.equalTo(18)
            make.bottom.equalToSuperview().offset(-8)
        }
        
        subHoldView.addSubview(myTextView)
        myTextView.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(12)
            make.right.equalTo(-12)
            make.height.greaterThanOrEqualTo(90)
            make.bottom.equalTo(numberLabel.snp.top).offset(-2)
        }
        myTextView.delegate = self
//        myTextView.wrapToContent()
        
        
        subHoldView.addSubview(tipsLable)
        tipsLable.snp.makeConstraints { make in
            make.top.equalTo(myTextView.snp.top).offset(8)
            make.left.equalTo(myTextView.snp.left).offset(4)
            make.height.equalTo(17)
        }
    }
    
    @objc func tapButton(gestureRecognizer:UITapGestureRecognizer) {
        guard let model = dataMode else { return }
        switch model.type  {
        case .planDocQuestion1:
            YHWholeScreenTipsView.show(type: .hkPlanQ1, targetView: iconImageV)
        case .planDocQuestion2:
            YHWholeScreenTipsView.show(type: .hkPlanQ2, targetView: iconImageV)
        case .planDocQuestion3:
            YHWholeScreenTipsView.show(type: .hkPlanQ3, targetView: iconImageV)
        case .planDocQuestion4:
            YHWholeScreenTipsView.show(type: .hkPlanQ4, targetView: iconImageV)
        case .planDocQuestion5:
            YHWholeScreenTipsView.show(type: .hkPlanQ5, targetView: iconImageV)
        case .planDocQuestion6:
            YHWholeScreenTipsView.show(type: .hkPlanQ6, targetView: iconImageV)
        case .unknow:
            printLog("")
        case .planOther:
            YHWholeScreenTipsView.show(type: .hkPlanQ7, targetView: iconImageV)
        }
    }
    
    func updateUI() {
        guard let model = dataMode else { return }
        nameLable.text = model.title
        myTextView.text = model.content
        if model.canEditFlag {
            myTextView.isEditable = true
            myTextView.isSelectable = true
            myTextView.textColor = UIColor.mainTextColor
        } else {
            myTextView.isEditable = false
            myTextView.isSelectable = false
            myTextView.textColor = UIColor(hex: 0x222222, alpha: 0.5)
            
            myTextView.wrapToContent()
        }
        
        if model.type == .planOther {
            maxNumbler = 300
            tipsTxt = "在此补充其他信息，非必填"
            
            iconImageV.isHidden = true
        } else {
            maxNumbler = 300
            iconImageV.isHidden = false
        }
        
        tipsLable.text = tipsTxt
        
//        print("原始数据： " + model.content)
        let ttt = getFuckString(string: model.content)
        
//        print("之后数据： " + ttt)
        myTextView.text = ttt
        
        let textNum = calcTextLength(string: myTextView.text)
        numberLabel.text = textNum.string + "/\(maxNumbler)"
        if textNum > maxNumbler {
            numberLabel.textColor = .failColor
        } else {
            numberLabel.textColor = UIColor.placeHolderColor
        }
        
        if model.isLastData {
            line.isHidden = true
        } else {
            line.isHidden = false
        }
        
        
        if model.content.count > 0 {
            tipsLable.isHidden = true
        } else {
            
            if model.canEditFlag {
                tipsLable.isHidden = false
            } else {
                tipsLable.isHidden = true
            }
        }
        
    }
    
    func calcTextLength(string : String) -> Int {
        if string.isEmpty {
            return 0
        }
        
        /*
         具体规则：
         （1）仅计算中文/英文/数字，不计算标点等特殊字符。
         （2）中文算一个字；
         （3）连续的英文/数字记为一个字。
         （4）空格不计入字数统计
         （5）如果英文之间有空格或标点符号，例如“aaa aaaa”字数记为2；中英混杂分开计算，例如“aaa你好 你aaa”字数记为5；
         （6）非中文、英文、数字的语言，例如日文，不计入字数统计。
         （7）如果C端用户，在APP上输入的字数超过300个字符，则APP再传给后端时，进行截断后再发给后台
         */
        
        var isPreDone : Bool = true //前一个字符已处理
        let stringLength : Int = string.unicodeScalars.count
        var totalNumber : Int = 0
        
        for (index,scalar) in string.unicodeScalars.enumerated() {
            if scalar.value >= 0x4E00 && scalar.value <= 0x9FFF {
                // 中文字符的Unicode范围
                if isPreDone == false {
                    totalNumber = totalNumber + 1
                }
                totalNumber = totalNumber + 1
                isPreDone = true
                
            } else if scalar.isASCII && (scalar >= "a" && scalar <= "z" || scalar >= "A" && scalar <= "Z") {
                // 英文字符（不包括ASCII数字和标点符号）
                
                isPreDone = false
                
            } else if scalar.isASCII && (scalar >= "0" && scalar <= "9") {
                // 数字
                isPreDone = false
                
            } else {
                if isPreDone == false {
                    totalNumber = totalNumber + 1
                }
                isPreDone = true
            }
            
            if index == stringLength - 1 {
                if isPreDone == false {
                    totalNumber = totalNumber + 1
                }
            }
        }
        return totalNumber
    }
    
    //获取固定长度的字符串
    func getFuckString(string : String) -> String {
        if string.isEmpty {
            return ""
        }
        
        if string.count <= maxNumbler {
            return string
        }
        
        /*
         具体规则：
         （1）仅计算中文/英文/数字，不计算标点等特殊字符。
         （2）中文算一个字；
         （3）连续的英文/数字记为一个字。
         （4）空格不计入字数统计
         （5）如果英文之间有空格或标点符号，例如“aaa aaaa”字数记为2；中英混杂分开计算，例如“aaa你好 你aaa”字数记为5；
         （6）非中文、英文、数字的语言，例如日文，不计入字数统计。
         （7）如果C端用户，在APP上输入的字数超过300个字符，则APP再传给后端时，进行截断后再发给后台
         */
        
        var isPreDone : Bool = true //前一个字符已处理
        let stringLength : Int = string.unicodeScalars.count
        var totalNumber : Int = 0
        
        var returStrn = ""
        
        for (index,scalar) in string.unicodeScalars.enumerated() {
            if scalar.value >= 0x4E00 && scalar.value <= 0x9FFF {
                // 中文字符的Unicode范围
                if isPreDone == false {
                    totalNumber = totalNumber + 1
                    
                }
                totalNumber = totalNumber + 1
                isPreDone = true
                
                if totalNumber <= maxNumbler {
                    returStrn = returStrn + String(scalar)
                } else {
                    return returStrn
                }
            } else if scalar.isASCII && (scalar >= "a" && scalar <= "z" || scalar >= "A" && scalar <= "Z") {
                // 英文字符（不包括ASCII数字和标点符号）
                
                isPreDone = false
                returStrn = returStrn + String(scalar)
                
            } else if scalar.isASCII && (scalar >= "0" && scalar <= "9") {
                // 数字
                isPreDone = false
                returStrn = returStrn + String(scalar)
                
            } else {
                if isPreDone == false {
                    totalNumber = totalNumber + 1
                    
                    
                    if totalNumber <= maxNumbler {
                        returStrn = returStrn + String(scalar)
                    } else {
                        return returStrn
                    }
                }
                isPreDone = true
                returStrn = returStrn + String(scalar)
            }
            
            if index == stringLength - 1 {
                if isPreDone == false {
                    totalNumber = totalNumber + 1
                    
                    if totalNumber <= maxNumbler {
                        returStrn = returStrn + String(scalar)
                    } else {
                        return returStrn
                    }
                }
            }
        }
        return returStrn
    }
}


extension YHHKPlanItemView : UITextViewDelegate {
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text.isEmpty {
            return true
        }
        
        let newLength = calcTextLength(string: textView.text)
        return newLength <= maxNumbler - 1
    }
    
    func textViewDidChange(_ textView: UITextView) {
        guard let model = dataMode else { return }
        guard let text = textView.text else { return }
        
        var txtNum : Int = 0
        
        txtNum = calcTextLength(string: text)
        numberLabel.text =  txtNum.string + "/\(maxNumbler)"
        
        
        printLog(text.count)
//        if text.count <= maxNumbler{
//            model.content = text
//        } else {
//            var ttt = text
//            let subString = ttt.slice(from: 0, length: maxNumbler)
//            
//            model.content = subString
//        }
        
        model.content = text
        if txtNum > maxNumbler {
            numberLabel.textColor = .failColor
        } else {
            numberLabel.textColor = UIColor.placeHolderColor
        }
        
        if text.count > 0 {
            tipsLable.isHidden = true
        } else {
            
            if model.canEditFlag {
                tipsLable.isHidden = false
            } else {
                tipsLable.isHidden = true
            }
        }
    }
}
