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

import UIKit
import DragCardContainer

protocol YHMatchProtocol: NSObjectProtocol  {
    func rematchUsers()
}

class YHMatchResultListViewController: YHBaseViewController {

    let viewModel = YHMatchUserViewModel()
    let loginViewModel = YHLoginViewModel()
    let secondCardColor = UIColor.init(hex: 0xE7EBF3)
    let thirdCardColor = UIColor.init(hex: 0xC4CEE3)
    var matchUsersArr:[YHMatchUserInfo?] = []
    weak var delegate: YHMatchProtocol?
    lazy var bgImgV:UIImageView = {
        let bg = UIImageView(image: UIImage(named: "people_match_result_bg"))
        return bg
    }()
    
    lazy var navBar: YHCustomNavigationBar = {
        let bar = YHCustomNavigationBar.navBar()
        bar.backgroundColor = .clear
        bar.title = "AI人脉雷达"
        bar.titleColor = .white
        bar.backButton.setImage(UIImage(named: "back_icon_for_code_input"), for: .normal)
        bar.backBlock = {
            [weak self] in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        bar.rightBtnClick = {
            [weak self] in
            guard let self = self else { return }
        }
        return bar
    }()
    
    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 guideView:YHMatchCardUsageGuideView = {
        let view = YHMatchCardUsageGuideView.createView()
        view.isHidden = true
        return view
    }()
    
    lazy var changeBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "people_match_change"), for: .normal)
        btn.setTitle("换一换", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize:15)
        btn.addTarget(self, action: #selector(didchangeBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var myCardBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "people_match_nameCard"), for: .normal)
        btn.setTitle("我的名片", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize:15)
        btn.addTarget(self, action: #selector(didMyCardBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor(hex: 0xFFFFFF, alpha: 0.3)
        return lineView
    }()
    
    lazy var rematchBtn:UIButton = {
       let btn = UIButton()
        btn.isHidden = true
        btn.setTitle("再次智能匹配", for: .normal)
        btn.backgroundColor = .brandMainColor
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .PFSC_M(ofSize: 15)
        btn.layer.cornerRadius = 3
        btn.addTarget(self, action: #selector(didRematchBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var noDataView:YHPeopleMatchNoDataView = {
        let view = YHPeopleMatchNoDataView.createView()
        view.isHidden = true
        view.relookBlock = {
            [weak self] in
            guard let self = self else { return }
            self.rematchBtn.isHidden = true
            self.changeBtn.isHidden = false
            self.myCardBtn.isHidden = false
            self.lineView.isHidden = false
            self.cardContainer.reloadData(forceReset: true)
        }
        return view
    }()
    
    // 卡片允许使用的手势方向
    private let allowedDirection: [Direction] = [.left, .right]
    lazy var cardContainer: DragCardContainer = {
        let cardContainer = DragCardContainer()
        // 是否可以无限滑动
        cardContainer.infiniteLoop = false
        // 数据源
        cardContainer.dataSource = self
        // 代理
        cardContainer.delegate = self
        // 可见卡片数量
        cardContainer.visibleCount = 3
        // 是否可以打印日志
        cardContainer.enableLog = true
        // 是否禁用卡片拖动
        cardContainer.disableTopCardDrag = false
        // 是否禁用卡片点击
        cardContainer.disableTopCardClick = false
        
        let mode = ScaleMode()
        // 卡片之间间距
        mode.cardSpacing = 5
        // 方向（可以运行Demo，修改该参数看实际效果）
        mode.direction = .bottom
        // 最小缩放比例
        mode.minimumScale = 0.9
        // 卡片最大旋转角度
        mode.maximumAngle = 0
        // 赋值mode
        cardContainer.mode = mode
        cardContainer.isHidden = true
        return cardContainer
    }()
    
    lazy var cardActionView:UIView = {
        let view = UIView()
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
    }
    
    @objc func didchangeBtnClicked() {
        self.cardContainer.swipeTopCard(to: .right)
    }
    
    @objc func didMyCardBtnClicked() {
        
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        
        if let userId = YHLoginManager.shared.userModel?.id, !userId.isEmpty {
            let vc = YHNameCardViewController()
            vc.userId = userId
            self.navigationController?.pushViewController(vc)
        } else {
            YHHUD.show(.progress(message: "加载中..."))
            self.loginViewModel.getUserId {
                [weak self] uid in
                YHHUD.hide()
                guard let self = self else { return }
                if !uid.isEmpty {
                    YHLoginManager.shared.userModel?.id = uid
                    let vc = YHNameCardViewController()
                    vc.userId = uid
                    self.navigationController?.pushViewController(vc)
                }
            }
        }
    }
    
    @objc func didRematchBtnClicked() {
        
        self.delegate?.rematchUsers()
        self.navigationController?.popViewController(animated: true)
    }
    
    func createUI() {
        gk_navigationBar.isHidden = true
        
        self.view.addSubview(bgImgV)
        self.view.addSubview(navBar)
        self.view.addSubview(self.noDataView)
        
        self.bgImgV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        self.navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_statusBar())
            make.height.equalTo(k_Height_NavContentBar)
        }
        
        self.noDataView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.navBar.snp.bottom).offset(192)
            make.height.equalTo(YHPeopleMatchNoDataView.height)
        }
        
        if self.matchUsersArr.count <= 0 {
            self.noDataView.isHidden = false
            self.noDataView.titleLabel.text = "目前尚未找到与您匹配的人脉资源"
            self.noDataView.relookBtn.isHidden = true
            return
        }

        self.view.addSubview(topLabel)
        self.view.addSubview(changeBtn)
        self.view.addSubview(myCardBtn)
        self.view.addSubview(lineView)
        
        self.view.addSubview(self.wingLeftImgV)
        self.view.addSubview(self.wingRightImgV)
        
        self.view.addSubview(self.cardActionView)
        self.cardActionView.addSubview(cardContainer)
        self.view.addSubview(self.rematchBtn)
        self.view.addSubview(self.guideView)

        self.topLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(50+k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(22)
        }
        self.changeBtn.snp.makeConstraints { make in
            make.height.equalTo(60)
            make.width.equalTo(130)
            make.bottom.equalToSuperview().offset(-80)
            make.right.equalTo(self.view.snp.centerX)
        }
        self.myCardBtn.snp.makeConstraints { make in
            make.height.equalTo(60)
            make.width.equalTo(140)
            make.bottom.equalToSuperview().offset(-80)
            make.left.equalTo(self.view.snp.centerX)
        }
        self.lineView.snp.makeConstraints { make in
            make.width.equalTo(1)
            make.height.equalTo(13)
            make.centerX.equalToSuperview()
            make.centerY.equalTo(self.changeBtn)
        }
        
        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)
        }
        
        self.cardActionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(102+k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(466.0)
        }
        
        self.cardContainer.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.left.equalTo(36)
            make.right.equalTo(-36)
            make.top.equalToSuperview()
            make.height.equalTo(466.0)
        }
        
        self.rematchBtn.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(48)
            make.bottom.equalTo(-135)
        }
        animaiton()
    }
    
    func animaiton() {
        
        let gap = 8.0
        
        let view3 = YHNameCardInfoView.createCardView()
        view3.backgroundColor = self.thirdCardColor
        view3.y = -YHNameCardInfoView.height
        view3.x = 36+gap*2
        view3.width = YHNameCardInfoView.width-gap*4
        view3.isHidden = self.matchUsersArr.count < 3
        if self.matchUsersArr.count >= 3 {
            if let user = self.matchUsersArr[2] {
                view3.userModel = user
            }
        }
        self.view.addSubview(view3)
        
        let view2 = YHNameCardInfoView.createCardView()
        view2.backgroundColor = self.secondCardColor
        view2.y = -YHNameCardInfoView.height
        view2.x = 36+gap
        view2.width = YHNameCardInfoView.width-gap*2
        view2.isHidden = self.matchUsersArr.count < 2
        self.view.addSubview(view2)
        if self.matchUsersArr.count >= 2 {
            if let user = self.matchUsersArr[1] {
                view2.userModel = user
            }
        }
        
        let view1 = YHNameCardInfoView.createCardView()
        view1.y = -YHNameCardInfoView.height
        view1.x = 36
        view1.width = YHNameCardInfoView.width
        self.view.addSubview(view1)
        if self.matchUsersArr.count >= 0 {
            if let user = self.matchUsersArr[0] {
                view1.userModel = user
            }
        }
        
        var delay1Time = 0.2
        if self.matchUsersArr.count >= 3 {
            delay1Time = 0.2
        } else if self.matchUsersArr.count >= 2 {
            delay1Time = 0.1
        } else if self.matchUsersArr.count >= 1 {
            delay1Time = 0.0
        }
        
        let delay2Time = delay1Time-0.1 >= 0.0 ?  delay1Time-0.1 : 0.0
        let delay3Time = delay2Time-0.1 >= 0.0 ?  delay2Time-0.1 : 0.0

        UIView.animate(withDuration: 0.5, delay: delay3Time, options: [.curveEaseInOut]) {
            view3.y = 102+k_Height_NavigationtBarAndStatuBar+5*2
        } completion: { finish in }
        
        UIView.animate(withDuration: 0.5, delay: delay2Time, options: [.curveEaseInOut]) {
            view2.y = 102+k_Height_NavigationtBarAndStatuBar+5
        } completion: { finish in }
        
        UIView.animate(withDuration: 0.5, delay: delay1Time, options: [.curveEaseInOut]) {
            view1.y = 102+k_Height_NavigationtBarAndStatuBar
        } completion: { 
            [weak self] finish in
            guard let self = self else { return }
            self.cardContainer.isHidden = false
            let showCardGuideKey = "kHasShowCardGuide"
            if let hasShowCardGuide = UserDefaults.standard.object(forKey: showCardGuideKey) as? Bool, hasShowCardGuide == true {
                self.guideView.isHidden = true
                
            } else { // 第一次展示卡片使用指引
                UserDefaults.standard.set(true, forKey: showCardGuideKey)
                UserDefaults.standard.synchronize()
                self.guideView.isHidden = false
                self.view.bringSubviewToFront(self.guideView)
            }
            
            view1.removeFromSuperview()
            view2.removeFromSuperview()
            view3.removeFromSuperview()
        }
    }
}

extension YHMatchResultListViewController: DragCardDataSource {
    
    public func numberOfCards(_ dragCard: DragCardContainer) -> Int {
        return matchUsersArr.count
    }

    public func dragCard(_ dragCard: DragCardContainer, viewForCard index: Int) -> DragCardView {
        
        print("getTopCardAt: \(index)")
        let cardView:YHNameCardInfoView = YHNameCardInfoView.createCardView()
        cardView.allowedDirection = self.allowedDirection
        cardView.tag = 1000+index
        if 0 <= index && index < self.matchUsersArr.count {
            if let userModel = self.matchUsersArr[index] {
                cardView.userModel = userModel
                cardView.sendBlock = {
                    [weak self] text in
                    guard let self = self else { return }
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.addFriendWithText(text!, yhId: userModel.yhId) {
                        success, error in
                        YHHUD.hide()
                        if success {
                            YHHUD.flash(message: "已发送申请，继续查看更多人脉吧~")
                            cardView.bottomBtn.setTitle("已发送好友申请", for: .normal)
                            cardView.bottomBtn.alpha = 0.3
                            cardView.bottomBtn.isUserInteractionEnabled = false
                            userModel.isSendRequest = true
                            
                        } else {
                            var msg = "申请失败"
                            if let errMsg = error?.errorMsg, !errMsg.isEmpty {
                                msg = errMsg
                            }
                            YHHUD.flash(message: msg)
                        }
                    }
                }
            }
        }
        return cardView
    }
}

extension YHMatchResultListViewController: DragCardDelegate {
    public func dragCard(_ dragCard: DragCardContainer, displayTopCardAt index: Int, with cardView: DragCardView) {
        
        print("displayTopCardAt: \(index)")
        
        if cardView is YHNameCardInfoView {
            let cardInfoView = cardView as! YHNameCardInfoView
            cardInfoView.backgroundColor = .white
            if let secondCardView = dragCard.viewWithTag(1000+index+1) as? YHNameCardInfoView {
                secondCardView.backgroundColor = self.secondCardColor
            }
            if let thirdCardView = dragCard.viewWithTag(1000+index+2) as? YHNameCardInfoView {
                thirdCardView.backgroundColor = self.thirdCardColor
            }
        }
    }
    
    public func dragCard(_ dragCard: DragCardContainer, didRemovedTopCardAt index: Int, direction: Direction, with cardView: DragCardView) {
        print("didRemovedTopCardAt: \(index)")
    }

    public func dragCard(_ dragCard: DragCardContainer, didRemovedLast cardView: DragCardView) {
        print("didRemovedLast")
        DispatchQueue.main.asyncAfter(deadline: .now()+0.5, execute: {
            self.noDataView.isHidden = false
            self.noDataView.titleLabel.text = "本轮智能匹配人脉已到底~"
            self.view.bringSubviewToFront(self.noDataView)
            self.rematchBtn.isHidden = false
            self.changeBtn.isHidden = true
            self.myCardBtn.isHidden = true
            self.lineView.isHidden = true
        })
    }

    public func dragCard(_ dragCard: DragCardContainer, didSelectTopCardAt index: Int, with cardView: DragCardView) {
        print("didSelectTopCardAt: \(index)")
        
        if 0 <= index && index < self.matchUsersArr.count {
            if let userModel = self.matchUsersArr[index] {
            }
        }
    }
}
