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

import UIKit

class YHEditBaseUserInfoViewController: YHBaseViewController {
    var photoImageView: UIImageView!
    var photoButton: UIButton!
    var changeButton: UIButton!
    var nextButton: UIButton!
    var tableView: UITableView!
    var footView: YHEditBaseInfoFootView!
    var items: [YHUserInformationModel] = []
    var viewModel: YHEditViewModel = YHEditViewModel()
    var model: YHUserNameCardInfo = YHUserNameCardInfo()

    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getData()
    }
    
    func getData() {
        viewModel.model = model
        items = viewModel.getBaseDataSource()
        let url = URL(string: self.viewModel.model.avatar)
        photoImageView.kf.setImage(with: url)
        footView.dataSource = self.viewModel.model.signature
        tableView.reloadData()
        if self.viewModel.isCanNext(step: 1) {
            nextButton.isEnabled = true
            nextButton.backgroundColor =  UIColor.brandMainColor
        } else {
            nextButton.isEnabled = false
            nextButton.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
        }
    }
    
    func setView() {
        gk_navTitle = "基础信息"
        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 + 60)
            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)
        }
        
        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)
            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)
        }
        
        footView = {
            let view = YHEditBaseInfoFootView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 158))
            view.messageBlock = {[weak self] message in
                guard let self = self else { return }
                self.viewModel.didChange = true
                self.viewModel.model.signature = message
            }
            return view
        }()
        
        tableView = {
            let tableView = UITableView(frame:.zero, style:.grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .white
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.tableFooterView = footView
            tableView.register(cellWithClass: YHMyInformationItemCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(changeButton.snp.bottom).offset(24)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64 - 36)
            make.left.right.equalTo(view)
        }
    }
    
    @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 }
                    viewModel.model.avatar = success ?? ""
                    if self.viewModel.isCanNext(step: 1) {
                        nextButton.isEnabled = true
                        nextButton.backgroundColor =  UIColor.brandMainColor
                    } else {
                        nextButton.isEnabled = false
                        nextButton.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
                    }
                    self.viewModel.didChange = true
                }
            }
            self.navigationController?.pushViewController(clipperVC, animated: true)
        }
    }
    
    @objc func changeHead() {
        viewModel.requestChangeHead {[weak self] success, error in
            guard let self = self else { return }
            let url = URL(string: self.viewModel.model.avatar)
            self.photoImageView.kf.setImage(with: url)
            self.viewModel.didChange = true
        }
    }
    
    @objc func nextStep() {
        self.viewModel.model.signature = footView.messageTextField.text
        viewModel.requestSaveUserInfo {[weak self] success, error in
            guard let self = self else { return }
            if success {
                self.navigationController?.popViewController(animated: true)
            } else {
                YHHUD.flash(message: "保存失败")
            }
        }
    }
    
    override func backItemClick(_ sender: Any) {
        if viewModel.didChange {
            view.resignAllFirstResponders()
            YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
                self.navigationController?.popViewController()
            } callBack: {
            }
        } else {
            self.navigationController?.popViewController()
        }
    }
    
    
    
    /// 是否可以返回，包括点击返回和手势返回，默认YES
    override func navigationShouldPop() -> Bool {
        if viewModel.didChange {
            view.resignAllFirstResponders()
            YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
                self.navigationController?.popViewController()
            } callBack: {
            }
            return false
        }
        return true
    }
}

extension YHEditBaseUserInfoViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHMyInformationItemCell.self)
        cell.dataSource = items[indexPath.row]
        cell.block = { [weak self] model in
            guard let self = self else { return }
            self.viewModel.updateModel(model)
            if model.id != .id1 {
                self.getData()
            }
            if self.viewModel.isCanNext(step: 1)  {
                nextButton.isEnabled = true
                nextButton.backgroundColor =  UIColor.brandMainColor
            } else {
                nextButton.isEnabled = false
                nextButton.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 61.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
