//
//  YHWorkExperienceItemView.swift
//  galaxy
//
//  Created by EDY on 2024/2/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHWorkExperienceItemView: UIView {
    typealias ItemBlock = (_ model: YHWorkExperienceModel) -> Void
    typealias CompanyBlock = (_ model: YHCompanyModelListModel) -> Void
    var block: ItemBlock?
    var companyBlock: CompanyBlock?
    var titleLabel: UILabel!
    var messageTextField: UITextField!
    var nextStepImageView: UIImageView!
    var centerButton: UIButton!
    var leftButton: UIButton!
    var rightButton: UIButton!
    var showPromptLabel: UILabel!
    var longTimeButton: UIButton!
    var country: String = ""
    var workId: Int = 0
    var orderId: Int = 0
    var companyList: [YHWorkItemListModel] = []
    var dataSource: YHWorkExperienceModel? {
        didSet {
            updateAllViews()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        setUpView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpView() {
        titleLabel = {
            let label = UILabel()
            label.numberOfLines = 0
            return label
        }()
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(112)
        }
        
        messageTextField = {
            let textField = UITextField()
            textField.delegate = self
            textField.textColor = UIColor.mainTextColor
            textField.font = UIFont.PFSC_M(ofSize: 14)
            textField.adjustsFontSizeToFitWidth = true
            // 最小字体
            textField.minimumFontSize = 12
            return textField
        }()
        addSubview(messageTextField)
        messageTextField.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.left.equalTo(112)
        }
        
        showPromptLabel = {
            let label = UILabel()
            label.textColor = UIColor.red
            label.font = UIFont.PFSC_M(ofSize: 12)
            return label
        }()
        addSubview(showPromptLabel)
        showPromptLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.left)
            make.height.equalTo(20)
            make.right.bottom.equalToSuperview()
        }
        
        nextStepImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "form_right_arrow")
            return imageView
        }()
        addSubview(nextStepImageView)
        nextStepImageView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.width.equalTo(20)
        }
        
        centerButton = {
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(centerClick), for: .touchUpInside)
            return button
        }()
        addSubview(centerButton)
        centerButton.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.left.equalTo(112)
        }
        
        rightButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor = UIColor.brandMainColor.withAlphaComponent(0.08)
            button.setTitleColor(UIColor.brandMainColor, for: .selected)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.layer.cornerRadius = 16
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
            button.layer.borderWidth = 1
            button.layer.borderColor = UIColor.brandMainColor.cgColor
            button.isSelected = true
            button.addTarget(self, action: #selector(rightClick), for: .touchUpInside)
            return button
        }()
        addSubview(rightButton)
        rightButton.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalTo(32)
            make.width.equalTo(74)
        }
        
        leftButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor = UIColor.contentBkgColor
            button.setTitleColor(UIColor.brandMainColor, for: .selected)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.layer.cornerRadius = 16
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
            button.addTarget(self, action: #selector(leftClick), for: .touchUpInside)
            return button
        }()
        addSubview(leftButton)
        leftButton.snp.makeConstraints { make in
            make.right.equalTo(rightButton.snp.left).offset(-12)
            make.centerY.equalToSuperview()
            make.height.equalTo(32)
            make.width.equalTo(74)
        }
        
        longTimeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "main_time_normal"), for: .normal)
            button.setImage(UIImage(named: "login_privacy_agree"), for: .selected)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.setTitle("至今", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.contentHorizontalAlignment = .right
            button.addTarget(self, action: #selector(longTimeButtonClick), for: .touchUpInside)
//            button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 30)
            button.isSelected = false
            return button
        }()
        
        addSubview(longTimeButton)
        longTimeButton.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalTo(32)
            make.width.equalTo(43)
        }
        longTimeButton.iconInLeft(spacing: 3)
    }
    
    @objc func longTimeButtonClick() {
        longTimeButton.isSelected = !longTimeButton.isSelected
        if longTimeButton.isSelected {
            self.dataSource?.message = "至今"
            self.updateAllViews()
            if let block = self.block {
                block(self.dataSource ?? YHWorkExperienceModel())
            }
        } else {
            self.dataSource?.message = ""
            self.updateAllViews()
            if let block = self.block {
                block(self.dataSource ?? YHWorkExperienceModel())
            }
        }
    }
    
    func updateAllViews() {
        guard let dataSource = dataSource else { return }
        if dataSource.id == .id14 || dataSource.id == .id16 || dataSource.id == .id17 {
            messageTextField.keyboardType = .numberPad
        }
        if dataSource.isNeed ?? false {
            let str = "*" + (dataSource.title ?? "")
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_R(ofSize: 14),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            let starRange = NSRange(location: 0, length: 1)
            questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
            titleLabel.attributedText = questionAttrStr
        } else {
            let str = dataSource.title ?? ""
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_R(ofSize: 14),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            titleLabel.attributedText = questionAttrStr
        }
        messageTextField.placeholder = dataSource.prompts
        messageTextField.text = dataSource.message
        if dataSource.message == "0" && (dataSource.id == .id15 || dataSource.id == .id19) {
            messageTextField.text = ""
        }
        showPromptLabel.text = dataSource.alertMessage
        if dataSource.isUserKeyBoard ?? false {
            nextStepImageView.isHidden = true
            centerButton.isHidden = true
        } else {
            if let type = dataSource.type {
                switch type {
                case .normal:
                    break
                case .unit:
                    break
                case .nature:
                    break
                case .country:
                    break
                case .address:
                    break
                case .time:
                    break
                case .certificate:
                    break
                case .structure:
                    let arr = YHConstantArrayData.arrStructure
                    arr.forEach { item in
                        if item["id"] == dataSource.message {
                            messageTextField.text = item["title"]
                        }
                    }
                case .level:
                    let arr = YHConstantArrayData.arrLevel
                    arr.forEach { item in
                        if item["id"] == dataSource.message {
                            messageTextField.text = item["title"]
                        }
                    }
                    if messageTextField.text == "0" {
                        messageTextField.text = ""
                    }
                case .prove:
                    break
                case .company:
                    if dataSource.message == "0" {
                        messageTextField.text = ""
                    } else {
                        messageTextField.text = "已选择"
                    }
                case .field:
                    break
                case .myCompany:
                    break
                case .position:
                    break
                }
            }
            nextStepImageView.isHidden = false
            centerButton.isHidden = false
            messageTextField.snp.remakeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.right.equalTo(-20)
                make.left.equalTo(112)
            }
        }
       
        if dataSource.leftButtonString != nil {
            leftButton.isHidden = false
            leftButton.setTitle(dataSource.leftButtonString, for: .normal)
            nextStepImageView.isHidden = true
            messageTextField.isHidden = true
            if dataSource.message == "0" {
                buttonState(isLeft: 1)
            } else if dataSource.message == "1" {
                buttonState(isLeft: 0)
            } else {
                buttonState(isLeft: 2)
            }
        } else {
            leftButton.isHidden = true
        }
        
        if dataSource.rightButtonString != nil {
            rightButton.isHidden = false
            rightButton.setTitle(dataSource.rightButtonString, for: .normal)
            nextStepImageView.isHidden = true
            messageTextField.isHidden = true
        } else {
            rightButton.isHidden = true
        }
        
        if dataSource.isShowPrompts ?? false {
            if dataSource.message?.count != 0 && dataSource.message != "0" {
                showPromptLabel.isHidden = true
            } else {
                if dataSource.id == .id14 || dataSource.id == .id16 {
                    showPromptLabel.isHidden = true
                } else {
                    showPromptLabel.isHidden = false
                }
            }
        } else {
            showPromptLabel.isHidden = true
        }
        
        if dataSource.id == .id10 || dataSource.id == .id22 || dataSource.id == .id24 {
            longTimeButton.isHidden = false
            nextStepImageView.isHidden = true
            if dataSource.message == "至今" {
                longTimeButton.isSelected = true
                longTimeButton.snp.remakeConstraints { make in
                    make.left.equalTo(messageTextField.snp.left)
                    make.centerY.equalToSuperview()
                    make.height.equalTo(32)
                    make.width.equalTo(43)
                }
                centerButton.isHidden = true
                messageTextField.isHidden = true
            } else {
                longTimeButton.isSelected = false
                longTimeButton.snp.remakeConstraints { make in
                    make.right.equalToSuperview()
                    make.centerY.equalToSuperview()
                    make.height.equalTo(32)
                    make.width.equalTo(43)
                }
                centerButton.isHidden = false
                messageTextField.isHidden = false
            }
        } else {
            longTimeButton.isHidden = true
        }
    }
    
    func buttonState(isLeft: Int) {
        if isLeft == 0 {
            leftButton.isSelected = true
            rightButton.isSelected = false
            leftButton.layer.borderWidth = 1
            leftButton.layer.borderColor = UIColor.brandMainColor.cgColor
            leftButton.backgroundColor = UIColor.brandMainColor.withAlphaComponent(0.08)
            rightButton.backgroundColor = UIColor.contentBkgColor
            rightButton.layer.borderWidth = 0
        } else if isLeft == 1 {
            rightButton.isSelected = true
            leftButton.isSelected = false
            rightButton.layer.borderWidth = 1
            rightButton.layer.borderColor = UIColor.brandMainColor.cgColor
            rightButton.backgroundColor = UIColor.brandMainColor.withAlphaComponent(0.08)
            leftButton.backgroundColor = UIColor.contentBkgColor
            leftButton.layer.borderWidth = 0
        } else {
            rightButton.isSelected = false
            leftButton.isSelected = false
            rightButton.layer.borderWidth = 0
            rightButton.layer.borderColor = UIColor.brandMainColor.cgColor
            rightButton.backgroundColor = UIColor.contentBkgColor
            leftButton.backgroundColor = UIColor.contentBkgColor
            leftButton.layer.borderWidth = 0
        }
    }
    
    @objc func rightClick() {
        rightButton.isSelected = true
        leftButton.isSelected = false
        rightButton.layer.borderWidth = 1
        rightButton.layer.borderColor = UIColor.brandMainColor.cgColor
        rightButton.backgroundColor = UIColor.brandMainColor.withAlphaComponent(0.08)
        leftButton.backgroundColor = UIColor.contentBkgColor
        leftButton.layer.borderWidth = 0
        dataSource?.message = "0"
        dataSource?.value = ["0"]
        
        rightButton.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
        leftButton.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        if let block = block {
            block(dataSource ?? YHWorkExperienceModel())
        }
    }
    
    @objc func leftClick() {
        leftButton.isSelected = true
        rightButton.isSelected = false
        leftButton.layer.borderWidth = 1
        leftButton.layer.borderColor = UIColor.brandMainColor.cgColor
        leftButton.backgroundColor = UIColor.brandMainColor.withAlphaComponent(0.08)
        rightButton.backgroundColor = UIColor.contentBkgColor
        rightButton.layer.borderWidth = 0
        dataSource?.message = "1"
        dataSource?.value = ["1"]
        
        leftButton.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
        rightButton.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        if let block = block {
            block(dataSource ?? YHWorkExperienceModel())
        }
    }
    
    @objc func centerClick() {
        UIViewController.current?.view.endEditing(true) // 收起键盘
        guard let type = dataSource?.type else { return }
        switch type {
        case .normal:
            printLog("不需要跳转")
        case .address:
            var provice = ""
            if country.contains("台湾") {
                provice = "台湾省"
            }
            if country.contains("香港") {
                provice = "香港特别行政区"
            }
            if country.contains("澳门") {
                provice = "澳门特别行政区"
            }
            let addressPicker = YHAddressViewController(selectProvince: provice)
            addressPicker.backLocationStringController = { (address, province, city, _) in
                self.dataSource?.message = address
                self.dataSource?.value = [province, city]
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
            UIViewController.current?.present(addressPicker, animated: true, completion: nil)
        case .time:
            var title = ""
            var lastIsTaday = false
            if dataSource?.id == .id9 {
                title = "选择入职日期"
                lastIsTaday = true
            }
            if dataSource?.id == .id10 {
                title = "选择离职日期"
                lastIsTaday = true
            }
            if dataSource?.id == .id21 {
                title = "选择高管在职开始时间"
                lastIsTaday = true
            }
            if dataSource?.id == .id22 {
                title = "选择高管在职结束时间"
                lastIsTaday = true
            }
            if dataSource?.id == .id23 {
                title = "选择开始就职年月"
                lastIsTaday = true
            }
            if dataSource?.id == .id24 {
                title = "选择结束就职年月"
                lastIsTaday = true
            }
            YHDatePickView.show(type: .yyyymm, title: title, lastIsTaday: lastIsTaday, currentDay: dataSource?.message ?? "") { date in
                self.dataSource?.message = date
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .country:
            let vc = YHSelectCountryViewController()
            vc.backLocationStringController = { (country) in
                self.dataSource?.message = country
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
            UIViewController.current?.navigationController?.pushViewController(vc)
        case .unit:
            let vc = YHCompanySelectViewController()
            vc.backLocationStringController = { (country) in
                self.dataSource?.message = country.company_name
                self.updateAllViews()
                if let block = self.companyBlock {
                    block(country)
                }
            }
            UIViewController.current?.navigationController?.pushViewController(vc)
        case .nature:
            YHOtherPickerView.show(type: .nature, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .certificate:
            YHOtherPickerView.show(type: .certificate, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .structure:
            YHOtherPickerView.show(type: .structure, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.dataSource?.value = [data.index]
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .level:
            YHOtherPickerView.show(type: .level, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.dataSource?.value = [data.index]
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .prove:
            YHOtherPickerView.show(type: .prove, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .company:
            YHWorkExperienceCompanySelectView.show(workId: workId, orderId: orderId) { [weak self] in
                guard let self = self else { return }
                self.dataSource?.message = "1"
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .field:
            YHOtherPickerView.show(type: .field, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .myCompany:
            var arrData: [YHOtherPickerViewItemData] = []
            companyList.forEach { item in
                let model = YHOtherPickerViewItemData(title: item.company_name ?? "", subTitle: "", index: "\(item.id ?? 0)")
                arrData.append(model)
            }
            if arrData.count == 0 {
                YHHUD.flash(message: "请确认工作经验中您是否已填写在职公司")
                return
            }
            YHOtherPickerView.show(type: .myCompany, selectTitle: self.dataSource?.message ?? "", arrData) {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        case .position:
            YHOtherPickerView.show(type: .position, selectTitle: self.dataSource?.message ?? "") {[weak self] data in
                guard let self = self else { return }
                self.dataSource?.message = data.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHWorkExperienceModel())
                }
            }
        }
    }
}

extension YHWorkExperienceItemView: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.isEmpty == true {
            let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            var data = dataSource ?? YHWorkExperienceModel()
            data.message = newText
            if let block = block {
                block(data)
            }
            return true
        }
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if (dataSource?.id == .id7 || dataSource?.id == .id14 || dataSource?.id == .id16 || dataSource?.id == .id18) && newText.count > 10 {
            return false
        }
        
        if dataSource?.id == .id1 && newText.count > 50 {
            return false
        }
        
        if dataSource?.id == .id3 && newText.count > 2000 {
            return false
        }
        
        if dataSource?.id == .id4 && newText.count > 500 {
            return false
        }
        
        if dataSource?.id == .id17 && newText.count > 14 {
            // 10万亿元  100000 000000000
//            let target = 100000000000000
//            if let value = Int64(newText) {
//                if value > target {
//                    return false
//                }
//            } else {
//                return false
//            }
            return false
        }
        
        if (dataSource?.id == .id12 || dataSource?.id == .id8 ) && newText.count > 50 {
            return false
        }
        
        if (dataSource?.id == .id14 || dataSource?.id == .id16 || dataSource?.id == .id18) && newText.count > 10 {
            return false
        }
        
        if dataSource?.id == .id14 || dataSource?.id == .id16 {
            // 数据库最大存储问题  Int32   Max = 4294967295
            if let value = Int32(newText) {
            } else {
                YHHUD.flash(message: "数字超过最大范围")
                return false
            }
        }
        
        var data = dataSource ?? YHWorkExperienceModel()
        data.message = newText
        if let block = block {
            block(data)
        }
        return true
    }
}
