//
//  YHResignInfoItemView.swift
//  galaxy
//
//  Created by edy on 2024/10/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString


// 文字编辑和选择弹窗时使用
class YHResignInfoItemView: UIView {

    private var debounceTimer: Timer?
    
    var item: YHResignFamilyInfoItem = YHResignFamilyInfoItem()
    var faimilyInfo = YHResignInfoConfirmFamilyModel()
    // 更新姓名拼音
    var updateNamePinYinBlock:(()->())?
    var updateList:(()->())?

    let rightBtnWidth = 22.0
    let viewModel = YHResignInfoConfirmViewModel()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 14)
        return label
    }()
    
    lazy var detailLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_M(ofSize: 14)
        label.textColor = UIColor.mainTextColor
        return label
    }()
    
    lazy var textField: UITextField = {
        let tf = UITextField()
        tf.font = UIFont.PFSC_M(ofSize: 14)
        tf.textColor = UIColor.mainTextColor
        tf.isHidden = true
        tf.delegate = self
        tf.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged)
        return tf
    }()
    
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "family_info_del"), for: .normal)
        btn.addTarget(self, action: #selector(didActionButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var previousContentView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = kCornerRadius6
        view.backgroundColor = UIColor(hex: 0xF8F9FB)
        view.clipsToBounds = true
        return view
    }()
    
    lazy var previousTitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor.mainTextColor(alpha: 0.3)
        return label
    }()
    
    lazy var previousDetailLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_M(ofSize: 12)
        label.textColor = UIColor.mainTextColor(alpha: 0.3)
        return label
    }()
    
    lazy var errorTipsLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 12)
        label.textColor = UIColor.failColor
        return label
    }()
    
    // 拉起弹窗用的一行透明的按钮
    lazy var clickRowBtn: UIButton = {
        let btn = UIButton()
//        btn.backgroundColor = .mainTextColor(alpha: 0.2)
        btn.addTarget(self, action: #selector(didSelectSheetBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
        
        self.addSubview(lineView)
        self.addSubview(titleLabel)
        self.addSubview(detailLabel)
        self.addSubview(textField)
        self.addSubview(rightBtn)
        self.addSubview(previousContentView)
        self.addSubview(errorTipsLabel)
        self.addSubview(clickRowBtn)
        previousContentView.addSubview(previousTitleLabel)
        previousContentView.addSubview(previousDetailLabel)
        
        clickRowBtn.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        lineView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(0)
            make.height.equalTo(20)
            make.width.equalTo(122)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(titleLabel.snp.right)
            make.right.equalTo(-18.0-rightBtnWidth)
        }
        
        textField.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(detailLabel)
            make.right.equalTo(-18.0-rightBtnWidth)
            make.height.equalTo(52)
        }
        
        rightBtn.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.width.height.equalTo(rightBtnWidth)
            make.right.equalTo(0)
        }
        
        previousContentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-16)
            make.top.equalTo(detailLabel.snp.bottom).offset(16)
        }
        
        previousTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(12)
            make.width.equalTo(110)
        }
        
        previousDetailLabel.snp.makeConstraints { make in
            make.left.equalTo(previousTitleLabel.snp.right).offset(0)
            make.top.equalTo(12)
            make.right.equalTo(-18)
            make.bottom.equalTo(-12)
            make.height.greaterThanOrEqualTo(17)
        }
        
        errorTipsLabel.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(previousContentView.snp.bottom)
            make.bottom.equalTo(-16)
        }
    }
    
    @objc func didActionButtonClicked() {
        let isTextEdit = item.isEditMode && item.action == .edit
        if isTextEdit {
            textField.becomeFirstResponder()
            textField.text = ""
            textFieldChanged(textField:textField)
        }
    }
    
    @objc func didSelectSheetBtnClicked() {
        if item.action == .select {
            // 强制键盘消失
            UIApplication.shared.yhKeyWindow()?.endEditing(true)
            
            if item.id == .marriage { // 婚姻状况
                YHSheetPickerView.show(type:.marriage1, selectTitle: self.faimilyInfo.getMarriageState()) {
                    [weak self]  item in
                    guard let self = self else { return }
                    self.item.value = item.title
                    self.detailLabel.text = item.title
                    self.faimilyInfo.married = "\(item.index)"
                    self.updateList?()
                }
                
            } else if item.id == .declareNation { // 申报国籍
                let vc = YHSelectCountryViewController()
                vc.backLocationStringController = { (country) in
                    self.item.value = country
                    self.detailLabel.text = country
                    self.faimilyInfo.nationality = country
                    self.updateList?()

                }
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func updateItem(_ item: YHResignFamilyInfoItem, familyInfo: YHResignInfoConfirmFamilyModel) {
        self.item = item
        self.faimilyInfo = familyInfo
        // 标题
        var title: ASAttributedString = .init("\(item.title)", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.mainTextColor))
        // 是否必填
        if item.isMust {
            let mustTag: ASAttributedString = .init("*", .font(UIFont.PFSC_R(ofSize: 14)),.foreground(UIColor.failColor))
            title = mustTag + title
        }
        
        titleLabel.attributed.text = title
    
        let isTextEdit = item.isEditMode && item.action == .edit
        detailLabel.text = (item.value.isEmpty ? "-" : item.value)
        detailLabel.isHidden = isTextEdit
        textField.isHidden = !isTextEdit
        let placeHolder = self.getPlaceHolder()
        textField.attributedPlaceholder = NSAttributedString(string: placeHolder,  attributes: [NSAttributedString.Key.foregroundColor : UIColor.placeHolderColor, NSAttributedString.Key.font: UIFont.PFSC_R(ofSize: 14)])
   
        if item.id == .firstName || item.id == .lastName {
            textField.keyboardType = .asciiCapable //  英文键盘
        }
        
        let isSheetEdit = item.isEditMode && item.action == .select
        clickRowBtn.isHidden = !isSheetEdit
        
        textField.text = item.value
        rightBtn.isHidden = !item.isEditMode
        
        if item.action == .edit {
            rightBtn.setImage(UIImage(named: "family_info_del"), for: .normal)
            
        } else if item.action == .select {
            rightBtn.setImage(UIImage(named: "family_info_arrow"), for: .normal)
        }
        previousTitleLabel.text = item.previousTitle
        previousDetailLabel.text = item.previousValue
        
        detailLabel.snp.remakeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(titleLabel.snp.right)
            make.right.equalTo(item.isEditMode ? -18.0-rightBtnWidth : 0)
            if isTextEdit || isSheetEdit  {
                make.height.equalTo(20)
            } else {
                make.height.greaterThanOrEqualTo(20)
            }
        }
        
        previousContentView.isHidden = !item.isShowPreviousInfo
        previousContentView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(detailLabel.snp.bottom).offset(item.isShowPreviousInfo ? 16 : 0)
            if !item.isShowPreviousInfo {
                make.height.equalTo(0)
            }
        }
        
        let isShowTips = (familyInfo.isNeedCheck && !item.tips.isEmpty)
        errorTipsLabel.text = item.tips
        errorTipsLabel.isHidden = !isShowTips
        errorTipsLabel.snp.remakeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            if !isShowTips {
                make.height.equalTo(0)
            }
            make.top.equalTo(previousContentView.snp.bottom).offset(isShowTips ? 6 : 0)
            make.bottom.equalTo(-16)
        }
        
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    
    func updateLineMargin(_ margin: CGFloat) {
        lineView.snp.updateConstraints { make in
            make.left.equalTo(margin)
            make.right.equalTo(-margin)
        }
    }
}

extension YHResignInfoItemView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        var newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        printLog("\(newText)")
        
        
        if self.item.id == .mainApplicantName || self.item.id == .spouseName || self.item.id == .childName {
            if newText.count > 30 { // 上限30个字符
                newText = String(newText.prefix(30))
                textField.text = newText
                textFieldChanged(textField: textField)
                return false
            }
        }
        
        if self.item.id == .occupation  { // 职业
            if newText.count > 30 { // 上限30个字符
                newText = String(newText.prefix(30))
                textField.text = newText
                textFieldChanged(textField: textField)
                return false
            }
        }
        
        if self.item.id == .hongkongAddress  { // 香港住址
            if newText.count > 200 { // 上限200个字符
                newText = String(newText.prefix(200))
                textField.text = newText
                textFieldChanged(textField: textField)
                return false
            }
        }
        return true
    }
    
    @objc func textFieldChanged(textField:UITextField) {
        if let text = textField.text {
            self.updateText(text)
            
        } else {
            self.updateText("")
        }
//      self.updateItem(self.item, familyInfo: self.faimilyInfo)
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        if self.item.id == .mainApplicantName || self.item.id == .spouseName || self.item.id == .childName {
            self.updateNamePinYin()

        } else {
            self.updateList?()
        }
    }
        
    func updateNamePinYin() {
        // 编辑姓名
        if self.item.id == .mainApplicantName || self.item.id == .spouseName || self.item.id == .childName {
            
            let text = textField.text ?? ""
            if text.isEmpty {
                self.faimilyInfo.familyName = ""
                self.faimilyInfo.givenName = ""
                self.updateList?()
                return
            }
            self.updateNamePinYinBlock?()
        }
    }
    
    func updateText(_ newText: String) {
        
        self.item.value = newText
        
        if self.item.id == .mainApplicantName || self.item.id == .spouseName || self.item.id == .childName {
            self.faimilyInfo.name = newText
            if newText.isEmpty {
                self.faimilyInfo.familyName = ""
                self.faimilyInfo.givenName = ""
                self.updateList?()
            } else {
                
            }
            return
        }
        
        if self.item.id == .firstName {
            self.faimilyInfo.familyName = newText.uppercased()
            self.item.value = newText.uppercased()
            
        } else if self.item.id == .lastName {
            self.faimilyInfo.givenName = newText.uppercased()
            self.item.value = newText.uppercased()

        } else if self.item.id == .occupation {
            self.faimilyInfo.occupationName = newText
            
        } else if self.item.id == .hongKongId {
            self.faimilyInfo.hkIdentityid = newText
            
        } else if self.item.id == .hongkongAddress {
            self.faimilyInfo.hkAddress = newText
        }
    }
    
    func getPlaceHolder() -> String {
        if self.item.id == .mainApplicantName {
            return "请输入主申人姓名"
            
        } else if self.item.id == .spouseName {
            return "请输入配偶姓名"
            
        } else if self.item.id == .childName {
            return "请输入子女姓名"
            
        } else if self.item.id == .firstName {
            return "请输入姓(拼音)"
            
        } else if self.item.id == .lastName {
            return "请输入名(拼音)"
            
        } else if self.item.id == .occupation {
            return "请输入职业"
            
        } else if self.item.id == .hongKongId {
            return "示例：A123456(A)"
            
        } else if self.item.id == .hongkongAddress {
            return "请输入香港住址"
        }
        return ""
    }
}
