//
//  YHInfoItemView.swift
//  galaxy
//
//  Created by edy on 2024/8/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

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

    private var debounceTimer: Timer?
    
    var item: YHFamilyInfoItem = YHFamilyInfoItem()
    var faimilyInfo: YHFamilyMemberInfoModel = YHFamilyMemberInfoModel()
    // 姓名更改
    var updateName: ((String) -> Void)?

    let rightBtnWidth = 22.0
    let viewModel = YHFamilyInfoConfirmViewModel()
    
    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(20)
        }
        
        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.updateItem(self.item, familyInfo: self.faimilyInfo)
                }
                
            } else if item.id == .birthPlaceInChina { // 国内出生地
                
                let vc = YHAddressViewController()
                vc.backLocationStringController = {
                     [weak self] (_, string2, string3, _) in
                     guard let self = self else { return }
                    var address = ""
                    if !isEmptyString(string2) {
                        address += string2
                    }
                    if !isEmptyString(string3) {
                        address += string3
                    }
                    self.item.value = address
                    self.detailLabel.text = address
                    self.faimilyInfo.birthPlace.area = [string2, string3]
                    self.updateItem(self.item, familyInfo: self.faimilyInfo)
                }
                UIViewController.current?.present(vc, animated: true)
                
            } 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.updateItem(self.item, familyInfo: self.faimilyInfo)
                }
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func updateItem(_ item: YHFamilyInfoItem, familyInfo: YHFamilyMemberInfoModel) {
        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
        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 isSelectSheet = item.isEditMode && item.action == .select
        clickRowBtn.isHidden = !isSelectSheet
        
        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 {
                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.isCheck && !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)
        }
    }
}

extension YHInfoItemView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        
        if self.item.id != .birthPlaceAboard {
            if newText.count >= 30 {
                textField.text = String(newText.prefix(30))
                textFieldChanged(textField: textField)
                return false
            }
        }
        
        printLog("\(newText)")
        
        if self.item.id == .mainApplicantName || self.item.id == .spouseName || self.item.id == .childName {
            // 名称编辑时需防抖请求拼音
            debounceTimer?.invalidate()
            debounceTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] _ in
                self?.updateNamePinYin()
            }
        }
        return true
    }
    
    @objc func textFieldChanged(textField: UITextField) {
        if let text = textField.text {
            self.updateText(text)
            self.faimilyInfo.isCheck = false
            
        } else {
            self.updateText("")
        }
        
        self.updateItem(self.item, familyInfo: self.faimilyInfo)
    }
    
    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 = ""
                updateName?("")
                return
            }
            
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.getPinYinFromName(text) {
                [weak self] firstNamePinYin, lastNamePinYin in
                YHHUD.hide()
                guard let self = self else { return }
                self.faimilyInfo.familyName = firstNamePinYin
                self.faimilyInfo.givenName = lastNamePinYin
                updateName?(text)
            }
        }
    }
    
    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
            
        } else 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 == .birthPlaceAboard {
            self.faimilyInfo.birthPlace.foreign = newText
        }
    }
    
    func getPlaceHolder() -> String {
        if self.item.id == .mainApplicantName {
            return "请输入主申人姓名"
        }
        
        if self.item.id == .spouseName {
            return "请输入配偶姓名"
        }
        
        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 == .birthPlaceAboard {
            return "请输入出生地"

        } else if self.item.id == .occupation {
            return "请输入职业"
            
        } else if self.item.id == .hongKongId {
            return "请输入香港身份证号"
        }
        return ""
    }
}

class YHInfoOptionView: UIView {
    
    var clickBlock: ((YHFamilyInfoOption) -> Void)?
    var item: YHFamilyInfoItem = YHFamilyInfoItem()
    var familyInfo: YHFamilyMemberInfoModel = YHFamilyMemberInfoModel()
    
    let btnBaseTag = 9527
    let btnHeight = 32.0
    let btnWidth = 74.0
    
    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.text = "张全蛋"
        label.textColor = UIColor.mainTextColor
        return label
    }()
    
    lazy var optionsView: UIView = {
        let view = UIView()
        return view
    }()
    
    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
    }()

    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(optionsView)
        self.addSubview(previousContentView)
        previousContentView.addSubview(previousTitleLabel)
        previousContentView.addSubview(previousDetailLabel)
        
        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)
        }
        
        optionsView.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.right.equalTo(-18)
            make.height.equalTo(32)
            make.left.equalTo(titleLabel)
        }
        
        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(20)
        }
    }
    
    func updateItem(_ item: YHFamilyInfoItem, familyInfo: YHFamilyMemberInfoModel) {
        
        self.item = item
        self.familyInfo = 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
        detailLabel.text = item.value
        detailLabel.isHidden = item.isEditMode
        optionsView.isHidden = !item.isEditMode
        
        optionsView.removeSubviews()
    
        for (index, option) in item.options.reversed().enumerated() {
            let btn = UIButton()
            btn.backgroundColor = UIColor.init(hex: 0xF8F9FB)
            btn.titleLabel?.font = .PFSC_R(ofSize: 13)
            btn.setTitle(option.value, for: .normal)
            btn.layer.cornerRadius = self.btnHeight/2.0
            btn.clipsToBounds = true
            btn.layer.borderWidth = option.isSelect ? 1.0 : 0.0
            btn.layer.borderColor = option.isSelect ? UIColor.brandMainColor.cgColor : nil
            btn.setTitleColor(option.isSelect ? UIColor.brandMainColor : UIColor.init(hex: 0x222222), for: .normal)
            btn.addTarget(self, action: #selector(didOptionBtnClicked(_:)), for: .touchUpInside)
            btn.tag = btnBaseTag+index
            optionsView.addSubview(btn)
            btn.snp.makeConstraints { make in
                let gap = 12.0
                make.right.equalTo(-Double(index)*(btnWidth+gap))
                make.centerY.equalToSuperview()
                make.size.equalTo(CGSize(width: btnWidth, height: btnHeight))
            }
        }
        
        previousTitleLabel.text = item.previousTitle
        previousDetailLabel.text = item.previousValue
        
        previousContentView.isHidden = !item.isShowPreviousInfo
        previousContentView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(item.isShowPreviousInfo ? -16 : 0)
            if !item.isShowPreviousInfo {
                make.height.equalTo(0)
            }
            make.top.equalTo(detailLabel.snp.bottom).offset(16)
        }
    }
    
    @objc func didOptionBtnClicked(_ sender: UIButton) {
        // tag 是按数组反序index排列的
        let selectIndex = (item.options.count-1)-(sender.tag-btnBaseTag)
        if 0 <= selectIndex, selectIndex < item.options.count {
            for (index, option) in item.options.enumerated() {
                let isSelect = (selectIndex == index)
                option.isSelect = isSelect
                if isSelect {
                    item.value = option.value
                    clickBlock?(option)
                }
            }
            self.updateItem(item, familyInfo: self.familyInfo)
            
        }
    }
}
