//
//  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 = "--/100"
        view.font = UIFont.PFSC_R(ofSize: 12)
        view.textColor = UIColor.placeHolderColor
        view.textAlignment = .right
        return view
    }()
    
    private lazy var subHoldView: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        view.clipsToBounds = true
        view.layer.cornerRadius = kCornerRadius3
        
        return view
    }()
    
    private lazy var subHoldView2: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        view.clipsToBounds = true
        view.layer.cornerRadius = kCornerRadius3
        return view
    }()
    
    private lazy var skillLabel: UILabel = {
        let view = UILabel()
        view.text = "所属专业名称(如有）：资深数据科学家"
        view.font = UIFont.PFSC_R(ofSize: 14)
        view.numberOfLines = 0
        view.lineBreakMode = .byWordWrapping
        view.textColor = .init(hex: 0x6D788A)
        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: 14)
        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 = "请输入,100字内"
//    var maxNumbler : Int = 100
    var maxNumbler: Int = 100 {
        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(18)
        }
        
        iconImageV.isHidden = true
        
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapButton(gestureRecognizer:)))
        iconImageV.isUserInteractionEnabled = true
        iconImageV.addGestureRecognizer(tap)
        
        // add
        holdView.addSubview(subHoldView2)
        subHoldView2.snp.makeConstraints { make in
            make.top.equalTo(nameLable.snp.bottom).offset(12)
            make.left.right.equalToSuperview()
        }
        
        subHoldView2.addSubview(skillLabel)
        skillLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.bottom.equalToSuperview().offset(-12)
        }
        subHoldView2.isHidden = 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 }
        
        if model.type == .planDocQuestion4 {
            iconImageV.isHidden = true
        } else if model.type == .planOther {
            iconImageV.isHidden = true
        } else {
            iconImageV.isHidden = false
        }
        
        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()
        }
        
        maxNumbler = 100
        
        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)"
        
        model.contentCount = textNum // 方便后面判断
        
        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
            }
        }
        
        // 布局
        if model.other.isEmpty {
            subHoldView2.isHidden = true
            
            subHoldView.snp.removeConstraints()
            subHoldView.snp.remakeConstraints { 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)
            }
            
        } else {
            subHoldView2.isHidden = false
            skillLabel.text = "所属专业名称（如有）：" + model.other
            
            subHoldView.snp.removeConstraints()
            subHoldView2.snp.removeConstraints()
            
            subHoldView2.snp.remakeConstraints { make in
                make.top.equalTo(nameLable.snp.bottom).offset(12)
                make.left.right.equalToSuperview()
            }
            
            subHoldView.snp.remakeConstraints { make in
                make.top.equalTo(subHoldView2.snp.bottom).offset(12)
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.bottom.equalTo(line.snp.top).offset(-18)
            }
            
        }
    }
    
    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 += 1
                }
                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 += 1
                } else {
                    
                }
                isPreDone = true
            }
            
            if index == stringLength - 1 {
                if isPreDone == false {
                    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 += 1
                }
                totalNumber += 1
                isPreDone = true
                
                if totalNumber <= maxNumbler {
                    returStrn += String(scalar)
                } else {
                    return returStrn
                }
            } else if scalar.isASCII && (scalar >= "a" && scalar <= "z" || scalar >= "A" && scalar <= "Z") {
                // 英文字符（不包括ASCII数字和标点符号）
                
                isPreDone = false
                returStrn += String(scalar)
                
            } else if scalar.isASCII && (scalar >= "0" && scalar <= "9") {
                // 数字
                isPreDone = false
                returStrn += String(scalar)
                
            } else {
                if isPreDone == false {
                    totalNumber += 1
                    if totalNumber <= maxNumbler {
                        isPreDone = true
                        returStrn += String(scalar)
                    } else {
                        return returStrn
                    }
                } else {
                    isPreDone = true
                    returStrn += String(scalar)
                }
            }
            
            if index == stringLength - 1 {
                if isPreDone == false {
                    totalNumber += 1
                    
                    if totalNumber <= maxNumbler {
                        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
        }
        // 使用 NSString 来处理文本替换
        let nsString = textView.text as NSString
        let newText = nsString.replacingCharacters(in: range, with: text)
        let newLength = calcTextLength(string: newText)
            
//        let tempTxt = textView.text + text
//        let newLength = calcTextLength(string: tempTxt)
        return newLength <= maxNumbler
    }
    
    func textViewDidChange(_ textView: UITextView) {
        guard let model = dataMode else { return }
        guard let text = textView.text else { return }
        
        let txtNum: Int =  calcTextLength(string: text)
        numberLabel.text =  txtNum.string + "/\(maxNumbler)"
        
        model.content = text
        model.contentCount = txtNum
        
        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
            }
        }
    }
}
