//
//  YHUserInfoSettingViewController.swift
//  galaxy
//
//  Created by EDY on 2024/6/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHUserInfoSettingViewController: YHBaseViewController {
    var photoImageView: UIImageView!
    var photoButton: UIButton!
    var changeButton: UIButton!
    var nameLabel: UILabel!
    var nameTextField: UITextField!
    var nextButton: UIButton!
    var viewModel: YHUserInfoSettingViewModel = YHUserInfoSettingViewModel()
    var headUrl: String = ""
    var name: String = ""
    let userViewModel = YHInformationAuthorizeViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getData()
    }
    
    func getData() {
        if YHLoginManager.shared.isLogin() {
            userViewModel.requestUserInfo {[weak self] success, error in
                guard let self = self else { return }
                let url = URL(string: self.userViewModel.model.avatar)
                self.headUrl = self.userViewModel.model.avatar
                self.photoImageView.kf.setImage(with: url)
                self.nameTextField.text = self.userViewModel.model.username
                if self.nameTextField.text?.count != 0  {
                    self.nextButton.isEnabled = true
                    self.nextButton.backgroundColor = UIColor.brandMainColor
                } else {
                    self.nextButton.isEnabled = false
                    self.nextButton.backgroundColor = UIColor.brandMainColor.withAlphaComponent(0.4)
                }
            }
        }
    }
    
    
    func setView() {
        gk_navTitle = "设置"
        gk_navLeftBarButtonItems = []
        let target = self.navigationController?.interactivePopGestureRecognizer?.delegate
        let pan = UIPanGestureRecognizer(target: target, action: nil)
        self.view.addGestureRecognizer(pan)
        view.backgroundColor = .white
        photoImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "user_photo_default")
            imageView.contentMode = .scaleAspectFill
            imageView.isUserInteractionEnabled = true
            imageView.layer.cornerRadius = 46.5
            imageView.layer.masksToBounds = true
            imageView.layer.borderWidth = 1
            imageView.layer.borderColor =  UIColor(hex: 0xF4F6FA).cgColor
            return imageView
        }()
        view.addSubview(photoImageView)
        photoImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 30)
            make.height.width.equalTo(93)
        }
        
        photoButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "user_take_photo"), for: .normal)
            button.addTarget(self, action: #selector(takePhoto), for: .touchUpInside)
            return button
        }()
        view.addSubview(photoButton)
        photoButton.snp.makeConstraints { make in
            make.bottom.equalTo(photoImageView.snp.bottom)
            make.right.equalTo(photoImageView.snp.right)
            make.width.height.equalTo(28)
        }
        
        changeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "user_change_photo"), for: .normal)
            button.addTarget(self, action: #selector(changeHead), for: .touchUpInside)
            return button
        }()
        view.addSubview(changeButton)
        changeButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(photoImageView.snp.bottom).offset(20)
            make.width.equalTo(68.5)
            make.height.equalTo(20)
        }
        
        nameLabel = {
            let label = UILabel()
            label.text = "真实姓名"
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor.mainTextColor
            return label
        }()
        view.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.width.equalTo(70)
            make.top.equalTo(changeButton.snp.bottom).offset(44)
            make.height.equalTo(21)
        }
        
        nameTextField = {
            let textField = UITextField()
            textField.delegate = self
            textField.textColor = UIColor.mainTextColor
            textField.font = UIFont.PFSC_M(ofSize: 15)
            textField.adjustsFontSizeToFitWidth = true
            //最小字体
            textField.minimumFontSize = 12
            textField.placeholder = "请输入"
            return textField
        }()
        view.addSubview(nameTextField)
        nameTextField.snp.makeConstraints { make in
            make.centerY.equalTo(nameLabel.snp.centerY)
            make.left.equalTo(129)
            make.right.equalTo(-21)
            make.height.equalTo(21)
        }
        
        nextButton = {
            let button = UIButton(type: .custom)
//            button.backgroundColor =  UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("下一步", for: .normal)
            button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(nextStep), for: .touchUpInside)
            button.isEnabled = false
            button.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
            return button
        }()
        view.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom())
            make.height.equalTo(48)
        }
    }
    
    @objc func takePhoto() {
        view.endEditing(true)
        YHImagePickerView.show("请选择头像") {[weak self] image in
            guard let self = self else { return }
            let clipperVC = YHHeadImageViewController()
            clipperVC.setBaseImg(image, resultImgSize: CGSize(width: 300, height: 300), type: .Move)
            clipperVC.successClippedHandler = {[weak self] result in
                guard let self = self else { return }
                self.photoImageView.image = result
                self.viewModel.uploadImage(result, true) {[weak self] success, error in
                    guard let self = self else { return }
                    
                    let replacedString = (success ?? "").getCdnUrl()
                    print(replacedString)
                    self.headUrl = replacedString
                }
            }
            self.navigationController?.pushViewController(clipperVC, animated: true)
        }
    }
    
    @objc func changeHead() {
        viewModel.requestChangeHead {[weak self] success, error in
            guard let self = self else { return }
            self.headUrl = self.viewModel.headUrl
            let url = URL(string: self.headUrl)
            self.photoImageView.kf.setImage(with: url)
        }
    }
    
    @objc func nextStep() {
        if nameTextField.text?.count == 0 {
            YHHUD.flash(message: "请填写您的真实姓名")
            return
        }
        self.name = nameTextField.text ?? ""
        let username = name.trimmingCharacters(in: .whitespaces)
        if username.count == 0 {
            YHHUD.flash(message: "名字不合法")
            return
        }
        // 请求接口逻辑
        viewModel.requestSaveUserInfo(head: headUrl, name: username) {[weak self] success, error in
            guard let self = self else { return }
            let vc = YHAllowUseMyInfoViewController()
            self.navigationController?.pushViewController(vc)
        }
    }
}

extension YHUserInfoSettingViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newText.count > 0  {
            nextButton.isEnabled = true
            nextButton.backgroundColor =  UIColor.brandMainColor
        } else {
            nextButton.isEnabled = false
            nextButton.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
        }
        if  newText.count > 20 {
            return false
        }
        return true
    }
}

