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

import UIKit

class YHInformationAuthorizationStepOneViewController: YHBaseViewController {
    var stepOneView: UIView!
    var stepTwoView: UIView!
    var photoImageView: UIImageView!
    var photoButton: UIButton!
    var changeButton: UIButton!
    var nextButton: UIButton!
    var tableView: UITableView!
    var promptView: YHFailPromptView!
    var items: [YHUserInformationModel] = []
    var viewModel: YHInformationAuthorizeViewModel = YHInformationAuthorizeViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getData()
    }
    
    func getData() {
        if YHLoginManager.shared.isLogin() {
            viewModel.requestUserInfo {[weak self] success, error in
                guard let self = self else { return }
                self.items = viewModel.getBaseDataSource()
                self.tableView.reloadData()
                let url = URL(string: self.viewModel.model.avatar)
                self.photoImageView.kf.setImage(with: url)
                if self.viewModel.isCanNext() {
                    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
        
        stepOneView = {
            let view = UIView()
            view.backgroundColor = UIColor.brandMainColor
            return view
        }()
        view.addSubview(stepOneView)
        stepOneView.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 16)
            make.height.equalTo(3)
            make.right.equalTo(view.snp.centerX).offset(-3)
        }
        
        stepTwoView = {
            let view = UIView()
            view.backgroundColor = UIColor(hex: 0xf4f6fa)
            return view
        }()
        view.addSubview(stepTwoView)
        stepTwoView.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 16)
            make.height.equalTo(3)
            make.left.equalTo(view.snp.centerX).offset(3)
        }
        
        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 + 59)
            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.withAlphaComponent(0.4)
            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
            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)
        }
        
        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.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)
        }
        
        promptView = {
            let view = YHFailPromptView()
            view.titleLable.text = "温馨提示：请填写真实信息，AI人脉匹配更精准"
            view.backgroundColor = UIColor(hex: 0xf0f4fb)
            view.titleLable.textColor = UIColor.brandMainColor
            view.alertImageView.image = UIImage(named: "user_prompt_image")
            return view
        }()
        view.addSubview(promptView)
        promptView.snp.makeConstraints { make in
            make.height.equalTo(36)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            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 }
                    self.viewModel.model.avatar = success ?? ""
                }
            }
            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)
        }
    }
    
    @objc func nextStep() {
        viewModel.requestSaveUserInfo {[weak self] success, error in
            guard let self = self else { return }
            let vc = YHInformationAuthorizationStepTwoViewController()
            vc.name = self.viewModel.model.username
            self.navigationController?.pushViewController(vc)
        }
    }
}

extension YHInformationAuthorizationStepOneViewController: 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 self.viewModel.isCanNext() {
                nextButton.isEnabled = true
                nextButton.backgroundColor =  UIColor.brandMainColor
            } else {
                nextButton.isEnabled = false
                nextButton.backgroundColor =  UIColor.brandMainColor.withAlphaComponent(0.4)
            }
            if model.id != .id1 && model.id != .id3 && model.id != .id5 {
                self.items = viewModel.getBaseDataSource()
                self.tableView.reloadData()
            }
        }
        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
    }
}
