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

import UIKit
import JXSegmentedView
import Lottie

class YHMatchUserViewController: YHBaseViewController {
    let viewModel = YHMatchUserViewModel()
    var informationAuthorizeViewModel: YHInformationAuthorizeViewModel = YHInformationAuthorizeViewModel()
    var needToMatch: Bool = false
    var isStartMatch: Bool = false
    
    lazy var bgImgV:UIImageView = {
        let bg = UIImageView(image: UIImage(named: "people_match_bg"))
        return bg
    }()
    
    lazy var topLabel:UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.textColor = UIColor.white
        label.font = UIFont.PFSC_R(ofSize:16)
        label.text = "为您匹配适合您的优质人脉"
        return label
    }()
    
    lazy var wingLeftImgV: UIImageView = {
        let view = UIImageView(image: UIImage(named: "people_match_wing_left"))
        return view
    }()
    
    lazy var wingRightImgV: UIImageView = {
        let view = UIImageView(image: UIImage(named: "people_match_wing_right"))
        return view
    }()
    
    lazy var bottomBtn:UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("AI人脉雷达匹配", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 15)
        btn.layer.cornerRadius = 3.0
        btn.addTarget(self, action: #selector(didMatchBtnClicked), for: .touchUpInside)
        return btn
    }()
        
    lazy var headLottieView: LottieAnimationView = {
        let view = LottieAnimationView(name: "people_head")
        view.loopMode = .loop
        return view
    }()
    
    lazy var launchLottieView: LottieAnimationView = {
        let view = LottieAnimationView(name: "people_launch")
        return view
    }()
    
    lazy var rotateLottieView: LottieAnimationView = {
        let view = LottieAnimationView(name: "people_rotate")
        view.isHidden = true
        return view
    }()
    
    lazy var bottomLabel:UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.textColor = UIColor.mainTextColor70
        label.font = UIFont.PFSC_R(ofSize:13)
        label.text = "授权基础信息，获取更多人脉"
        return label
    }()
    
    lazy var matchTipsLabel:UILabel = {
        let label = UILabel()
        label.text = "AI 人脉雷达正在为您智能匹配..."
        label.textAlignment = .center
        label.textColor = UIColor.white
        label.font = UIFont.PFSC_R(ofSize:16)
        label.isHidden = true
        return label
    }()
    
    lazy var firstImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "people_first_bg_image")
        imageView.isHidden = true
        return imageView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        self.view.backgroundColor = .clear
        createUI()
        NotificationCenter.default.addObserver(self, selector: #selector(startMatchUsers), name: YhConstant.YhNotification.didLookPeopleSuccessNotifiction, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if YHLoginManager.shared.isLogin() {
            informationAuthorizeViewModel.requestUserInfo {[weak self] success, error in
                guard let self = self else { return }
                if informationAuthorizeViewModel.model.is_fillin != 1 {
                    self.firstImageView.isHidden = false
                    self.bottomLabel.isHidden = false
                    self.headLottieView.isHidden = true
                    self.launchLottieView.isHidden = true
                    self.rotateLottieView.isHidden = true
                    self.bottomBtn.setTitle("开启AI人脉雷达", for: .normal)
                } else {
                    self.firstImageView.isHidden = true
                    self.bottomLabel.isHidden = true
                    self.headLottieView.isHidden = self.isStartMatch ? true : false
                    self.launchLottieView.isHidden = false
                    self.rotateLottieView.isHidden = true
                    self.bottomBtn.setTitle("AI人脉雷达匹配", for: .normal)
                }
            }
            viewModel.requestUserAuthorization {[weak self] success, error in
                guard let self = self else { return }
                if self.needToMatch && self.viewModel.setModel.authorization_basic_information == 2 {
                    self.needToMatch = false
                    self.didMatchBtnClicked()
                }
            }
        } else {
            self.firstImageView.isHidden = false
            self.bottomLabel.isHidden = false
            self.headLottieView.isHidden = true
            self.launchLottieView.isHidden = true
            self.rotateLottieView.isHidden = true
            self.bottomBtn.setTitle("开启AI人脉雷达", for: .normal)
        }
    }
    
    func createUI() {
        
        self.view.addSubview(self.bgImgV)
        self.view.addSubview(self.wingLeftImgV)
        self.view.addSubview(self.wingRightImgV)
        
        self.view.addSubview(topLabel)
        self.view.addSubview(firstImageView)
        self.view.addSubview(self.bottomLabel)
        
        self.view.addSubview(launchLottieView)
        self.view.addSubview(rotateLottieView)
        self.view.addSubview(headLottieView)
        self.view.addSubview(matchTipsLabel)
        self.view.addSubview(self.bottomBtn)

        self.headLottieView.play()
        
        bgImgV.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(-k_Height_statusBar()-48.0)
            make.bottom.equalToSuperview().offset(k_Height_TabBar)
        }

        launchLottieView.snp.makeConstraints { make in
            make.width.height.equalTo(KScreenWidth)
            make.centerX.equalToSuperview()
            make.top.equalTo(204-48-k_Height_statusBar())
        }
        headLottieView.snp.makeConstraints { make in
            make.width.height.equalTo(KScreenWidth)
            make.center.equalTo(launchLottieView)
        }
        rotateLottieView.snp.makeConstraints { make in
            make.width.height.equalTo(KScreenWidth)
            make.center.equalTo(launchLottieView)
        }
        
        self.topLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(50)
            make.height.equalTo(22)
        }
        
        firstImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(470)
            make.width.equalTo(305)
            make.top.equalTo(topLabel.snp.bottom).offset(30)
        }
        
        self.bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(48.0)
            make.bottom.equalTo(-60)
        }
        
        self.bottomLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(18.0)
            make.top.equalTo(self.bottomBtn.snp.bottom).offset(12)
        }
        
        self.matchTipsLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.launchLottieView.snp.bottom).offset(20)
            make.height.equalTo(18.0)
        }
        
        
        self.wingLeftImgV.snp.makeConstraints { make in
            make.width.height.equalTo(19)
            make.right.equalTo(self.topLabel.snp.left)
            make.centerY.equalTo(self.topLabel)
        }
        self.wingRightImgV.snp.makeConstraints { make in
            make.width.height.equalTo(19)
            make.left.equalTo(self.topLabel.snp.right)
            make.centerY.equalTo(self.topLabel)
        }
    }
    
    @objc func didMatchBtnClicked() {
        
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        
        if informationAuthorizeViewModel.model.is_fillin == 1 {
            if viewModel.setModel.authorization_basic_information == 2 {
                startMatchUsers()
            } else {
                YHCommonAlertView.show("", "您暂未开启AI人脉匹配授权", "取消", "去开启") {
                    
                } callBack: {
                    self.needToMatch = true
                    let vc = YHInformationAuthorizationStepTwoViewController()
                    vc.stepFlag = false
                    self.navigationController?.pushViewController(vc)
                }
            }
        } else {
            let vc = YHInformationAuthorizationStepOneViewController()
            self.navigationController?.pushViewController(vc)
        }
    }
    
    func resetAnimation() {
        self.isStartMatch = false
        self.launchLottieView.stop()
        self.rotateLottieView.stop()
        self.headLottieView.isHidden = false
        self.launchLottieView.isHidden = false
        self.rotateLottieView.isHidden = true
        self.wingLeftImgV.isHidden = false
        self.wingRightImgV.isHidden = false
        self.topLabel.isHidden = false
        self.bottomBtn.isHidden = false
        self.matchTipsLabel.isHidden = true

    }
}

extension YHMatchUserViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension YHMatchUserViewController: YHMatchProtocol {
    @objc func startMatchUsers() {
        self.isStartMatch = true
        self.bottomBtn.isHidden = true
        self.matchTipsLabel.isHidden = false
        self.headLottieView.isHidden = true
        self.launchLottieView.isHidden = false
        self.topLabel.isHidden = true
        self.wingLeftImgV.isHidden = true
        self.wingRightImgV.isHidden = true
        self.launchLottieView.loopMode = .playOnce
        self.launchLottieView.play {
            [weak self] completed in
            guard let self = self else { return }
            self.launchLottieView.isHidden = true
            self.rotateLottieView.isHidden = false
            self.rotateLottieView.loopMode = .loop
            self.rotateLottieView.play { [weak self] completed in
                if completed {
                    print("yyyyyyyyy")
                } else {
                    print("nnnnnnnnnn")
                    self?.isStartMatch = false
                    self?.resetAnimation()
                }
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now()+2.0, execute: {
            if self.isStartMatch {
                self.requestMatchUserList()
            } else {
                self.resetAnimation()
            }
        })
    }
}

extension YHMatchUserViewController {
    func requestMatchUserList() {
        self.viewModel.getMatchUserlist { 
            success, error in
            if success {
                let vc = YHMatchResultListViewController()
                vc.delegate = self
                vc.matchUsersArr = self.viewModel.matchUserArr
                self.resetAnimation()
                if let curVc = UIViewController.current as? YHCommunityViewController,curVc.segmentedView.selectedIndex == 1 {
                    curVc.navigationController?.pushViewController(vc, completion: {
                    })
                } else {
                    printLog("hhhhhhhhhhhhhhhhhhhhhhhh")
                }
               
            } else {
                
                if let err = error, err.errorCode == YHErrorCode.peopleMatchBlackList.rawValue {
                    // 人脉匹配黑名单
                    let vc = YHMatchResultListViewController()
                    vc.delegate = self
                    vc.matchUsersArr = self.viewModel.matchUserArr
                    self.resetAnimation()
                    if let curVc = UIViewController.current as? YHCommunityViewController,curVc.segmentedView.selectedIndex == 1 {
                        curVc.navigationController?.pushViewController(vc, completion: {
                        })
                    } else {
                        printLog("hhhhhhhhhhhhhhhhhhhhhhhh")
                    }
                    return
                }
                var msg = "匹配失败"
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    msg = errorMsg
                }
                YHHUD.flash(message: msg)
                self.resetAnimation()
            }
        }
    }
    
    func rematchUsers() {
        if YHLoginManager.shared.isLogin() {
            YHHUD.show(.progress(message: "加载中..."))
            self.informationAuthorizeViewModel.requestUserInfo {[weak self] success, error in
                YHHUD.hide()
                guard let self = self else { return }
                YHHUD.show(.progress(message: "加载中..."))
                self.viewModel.requestUserAuthorization {[weak self] success, error in
                    YHHUD.hide()
                    guard let self = self else { return }
                    self.didMatchBtnClicked()
                }
            }
        }
    }
}

