//
//  YHVisaPaymentVC.swift
//  galaxy
//
//  Created by davidhuangA on 2024/8/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHVisaPaymentVC: YHBaseViewController {
    let items : [String] = ["1","2","3"]
    
    
    var orderID: Int = 0
    
    lazy var viewModel: YHVisaPaymentViewModel = {
        let vm = YHVisaPaymentViewModel()
        return vm
    }()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.estimatedSectionHeaderHeight = 16.0
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHVisaPaymentTipsCell.self, forCellReuseIdentifier: YHVisaPaymentTipsCell.cellReuseIdentifier)
        tableView.register(YHVisaPayTypeCell.self, forCellReuseIdentifier: YHVisaPayTypeCell.cellReuseIdentifier)
        tableView.register(YHPayMembersCell.self, forCellReuseIdentifier: YHPayMembersCell.cellReuseIdentifier)
        return tableView
    }()
    
    
    //我已知悉，确认
    lazy var rewardBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("我已全部缴费，下一步", for: .normal)
        button.setTitle("缴费结果更新中，请耐心等待", for: .disabled)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.white, for: .disabled)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickNextBtn), for: .touchUpInside)
        button.backgroundColor = UIColor.brandMainColor
        button.isHidden = true
        return button
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(self.rewardBtn)
        self.rewardBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(44)
        }
        view.layer.zPosition = 10
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
}

private extension YHVisaPaymentVC {
    func loadData() {
        let params: [String : Any] = ["order_id": orderID]
        viewModel.getVisaPaymentList(params) { success, error in
            if success {
                
            } else {
                
            }
            self.tableView.reloadData()
            
            self.getPayUpdateStatus()
        }
        
        
    }
    
    func postPaymentResult() {
        let params: [String : Any] = ["order_id": orderID]
        viewModel.postPaymentResult(params) { success, error in
            if success {
                YHHUD.flash(message: "预计会在1个工作日内更新缴费结果")
            } else {
                
            }
            self.getPayUpdateStatus()
        }
    }
    
    
    func getPayUpdateStatus() {
        let params: [String : Any] = ["order_id": orderID]
        viewModel.getPaymentUpdateStatus(params) { success, error in
            if success {
                
            } else {
                
            }
            self.setButtonRightStatus()
        }
        
    }
    
    
    func setupUI() {
        gk_navTitle = "签证缴费"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        view.backgroundColor = UIColor.contentBkgColor
        
        if orderID == 0 {
            if let id = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                self.orderID = (id as? Int) ?? 0
            }
        }

        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        disableSureButton()
    }
    
    
    @objc func clickNextBtn() {
        if self.viewModel.isAllMemberPay() {
            //跳转
            let vc = YHTravelDocsPreparationListViewController()
            vc.orderId = orderID
            self.navigationController?.push(vc, removeClass: YHTravelDocsPreparationListViewController.self)
        } else {
            postPaymentResult()
        }
    }
    
    func disableSureButton(_ flag : Bool = true) {
        if flag {
            rewardBtn.isHidden = false
            rewardBtn.isEnabled = false
            rewardBtn.backgroundColor = UIColor.brandMainColor30
            
        } else {
            rewardBtn.isHidden = false
            rewardBtn.isEnabled = true
            rewardBtn.backgroundColor = UIColor.brandMainColor
        }
        
    }
    
    func setButtonRightStatus() {
        if viewModel.updateStatusModel.status == 1 {
            if self.viewModel.isAllMemberPay() {
                disableSureButton(false)
                rewardBtn.setTitle("我已全部缴费，下一步", for: .normal)
            } else {
                disableSureButton()
            }
        } else {
            disableSureButton(false)
            if self.viewModel.isAllMemberPay() {
                rewardBtn.setTitle("我已全部缴费，下一步", for: .normal)
            } else {
                rewardBtn.setTitle("我已全部缴费，更新缴费结果", for: .normal)
            }
        }
    }
}


extension YHVisaPaymentVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if 0 <= indexPath.section && indexPath.section < items.count {
            if indexPath.section == 0 {
                let warningCell = tableView.dequeueReusableCell(withIdentifier: YHVisaPaymentTipsCell.cellReuseIdentifier, for: indexPath)
                return warningCell
            } else if indexPath.section == 1 {
                let approveCell = tableView.dequeueReusableCell(withIdentifier: YHVisaPayTypeCell.cellReuseIdentifier, for: indexPath) as! YHVisaPayTypeCell
                approveCell.dataModel = self.viewModel.visaPaymentData
                return approveCell
                
            } else if indexPath.section == 2 {
                let approveCell = tableView.dequeueReusableCell(withIdentifier: YHPayMembersCell.cellReuseIdentifier, for: indexPath) as! YHPayMembersCell
                approveCell.dataModel = self.viewModel.visaPaymentData
                return approveCell
            } else {
                
            }
        }
            
        let approveCell = tableView.dequeueReusableCell(withIdentifier: YHVisaPayTypeCell.cellReuseIdentifier, for: indexPath)
        return approveCell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return YHVisaPaymentTipsCell.cellH
        }
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 16.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}
