//
//  PersonalInformationFillController.swift

//
//  Created by Leon on 2025/7/18.
//

import UIKit
import DateToolsSwift
import Combine
class PersonalInformationFillController: CLViewController<PersonalInformationFillView> {
    lazy var birthdayPicker:BirthdayPickerView = BirthdayPickerView()
    
    var userToken: String?
    
    // Data
    private var cancellables = Set<AnyCancellable>()
    @Published var isRegisterEnabled: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setupViews()
        
        setupEvents()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 禁止侧滑返回
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    private func setupViews(){
        navigationView.backButton.isHidden = true
        disabledFullScreenPan()
    }
    
    private func setupEvents(){
        container.bottomButton.addTarget(self, action: #selector(tapRegister), for: .touchUpInside)
        container.birthdaySelectView.selectBlock = {[weak self] in
            self?.selectBirthday()
        }
        
        $isRegisterEnabled.sink {[weak self] enabled in
            self?.container.bottomButton.isEnabled = enabled
        }.store(in: &cancellables)
        
//        Publishers.CombineLatest(container.$nickname, container.sexView.$sex).sink{
//            nickname, sex in
//            dlog("CombineLatest nickname:\(nickname), sex:\(sex)")
//        }.store(in: &cancellables)
        
        Publishers.CombineLatest3(container.$nickname, container.sexView.$sex, container.$birthdayStr).map{
//        Publishers.CombineLatest(container.$nickname, container.sexView.$sex).map{
            nickname,sex, birthdayStr in
            if let nick = nickname, nick.isValidNickname, let rawValue = sex, (Sex(rawValue: rawValue.rawValue) != nil), let birthdayFormat = birthdayStr, !birthdayFormat.isEmpty {
                return true
            }
            return false
        }.assign(to: &$isRegisterEnabled)
        
    }
    
    private func selectBirthday(){
        if let date = container.birthdayDate{
            birthdayPicker.setupDefaultSelectDate(date)
        }else if let dateStr = container.birthdayStr{
            let date = Date(dateString: dateStr, format: "yyyy-MM-dd")
            birthdayPicker.setupDefaultSelectDate(date)
        }
        
        birthdayPicker.show()
        birthdayPicker.tapConfirmAction = {[weak self] date, timestamp in
            dlog("birthday date:\(date). timestamp:\(timestamp)")
            self?.container.birthdayDate = date
            self?.container.birthdayStr = date.toString(dateFormat: "yyyy-MM-dd")
        }
    }
    
    @objc private func tapRegister(){
//        #warning("test")
//        //dismiss(animated: true, completion: nil)
//        self.close(dismissFirst: true)
//        return
        guard let user = UserCore.shared.user, let nickname = container.nickname else{
            return
        }
        
        if let oldNickname = user.nickname, nickname != oldNickname{// 新nickname
            Hud.showIndicator()
            UserOperator.checkname(name: nickname) {[weak self] nicknameOK in
                if nicknameOK{
                    self?.doCompleteInfo()
                }else{
                    Hud.hideIndicator()
                }
            }
        }else{
            Hud.showIndicator()
            doCompleteInfo()
        }
        
       
        // dlog("当前的sex: \(String(describing: container.sexView.sex?.rawValue))")
    }
    
    private func doCompleteInfo(){
        guard let user = UserCore.shared.user, let nickname = container.nickname, let sex = container.sexView.sex, let birthdayDate = container.birthdayDate else{
            return
        }
        let birthdayTimeStamp = birthdayDate.timeStamp
        var params = [String:Any]()
        params.updateValue(user.userId, forKey: "userId")
        params.updateValue(nickname, forKey: "nickname")
        params.updateValue(sex.rawValue, forKey: "sex")
        params.updateValue(birthdayTimeStamp, forKey: "birthday")
        
        LoginProvider.request(LoginAPI.completeUserInfo(params: params), modelType: User.self) {[weak self] result in
            Hud.hideIndicator()
            switch result{
            case .success:
                UserCore.shared.refreshUserInfo {[weak self] result in
                    self?.close(dismissFirst: true)
                }
            case.failure:
                break
            }
        }
    }

}
