//
//  YHMySignatureDetailViewController.swift
//  galaxy
//
//  Created by EDY on 2024/3/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SafariServices

class YHMySignatureDetailViewController: YHBaseViewController {

    var bottomView: UIView!
    var bottomButton: UIButton!
    var tableView: UITableView!
    var dataSource: [YHWorkItemListModel]?
    var viewModel: YHMySignatureDetailViewModel?
    var timer = Timer()

    var id: Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHMySignatureDetailViewModel()
        gk_navTitle = "我的签字"
        setView()
        getData()
        // Do any additional setup after loading the view.
    }
    
    func startTimer() {
        let queue = DispatchQueue.global()
        timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { _ in
            queue.async {
                self.checkSignatureState()
            }
        }
    }
    
    func checkSignatureState() {
        viewModel?.requestSignCallBack("\(id)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success ?? false {
                timer.invalidate()
                //刷新文件状态
            }
        })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    func getData() {
        viewModel?.requestSignatureDetail("\(id)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            self.tableView.reloadData()
        })
    }
    
    func updateDataSource() {
       
        self.tableView.reloadData()
    }
    
    func setView() {
        tableView = {
            let tableView = UITableView(frame:.zero, style:.plain)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHMyFileMethodTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = UIView()
            bottom.backgroundColor = .white
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        
        bottomButton = {
            let button = UIButton(type: .custom)
//            button.backgroundColor =  UIColor(hex:0x2274ee)
            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 = kCornerRadius6
            button.clipsToBounds = true
            button.addTarget(self, action: #selector(submit), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(bottomButton)
        bottomButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
            make.left.equalTo(16)
        }
        
        bottomButton.layoutIfNeeded()
        bottomButton.addYinHeGradualLayer()
    }
    
    @objc func submit() {
        let url = URL(string: "https://baidu.com/")!
        let safariViewController = SFSafariViewController(url: url)
        safariViewController.dismissButtonStyle = .close
        safariViewController.delegate = self
        self.navigationController?.pushViewController(safariViewController)
    }
}

extension YHMySignatureDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHMyFileMethodTableViewCell.self)
        cell.block = {[weak self] type in
            guard let self = self else { return }
            switch type {
            case .sign:
                viewModel?.requestSignaturePageURL("\(id)", callBackBlock: {[weak self] success, error in
                    guard let self = self else { return }
                    if error?.errorCode == 1008611 {
                        
                        YHCommonAlertView.show("实名认证", "为保证签署有效，请先实名认证", "取消", "去认证") {
                            self.viewModel?.requestSignaturePersonalURL(callBackBlock: {[weak self] success, error in
                                guard let self = self else { return }
                                let url = URL(string: self.viewModel?.personalUrl)!
                                let safariViewController = SFSafariViewController(url: url)
                                safariViewController.dismissButtonStyle = .close
                                safariViewController.delegate = self
                                self.navigationController?.pushViewController(safariViewController)
//                                let vc = YHNewWebViewController()
//                                vc.url = self.viewModel?.personalUrl ?? ""
//                                self.navigationController?.pushViewController(vc)
                            })
                        }
                    } else {
                        if success ?? false {
//                            self.startTimer()
                            let url = URL(string: self.viewModel?.pageUrl)!
                            let safariViewController = SFSafariViewController(url: url)
                            safariViewController.dismissButtonStyle = .close
                            safariViewController.delegate = self
                            self.navigationController?.pushViewController(safariViewController)
//                            let vc = YHNewWebViewController()
//                            vc.url = self.viewModel?.pageUrl ?? ""
//                            self.navigationController?.pushViewController(vc)
                        } else {
                            YHHUD.flash(message: error?.errorMsg ?? "")
                        }
                    }
                })
            case .downLoad:
                printLog("下载")
            case .look:
                printLog("查看")
            }
        }
        cell.backgroundColor = .clear
        cell.contentView.backgroundColor = .clear
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(180)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
}

extension YHMySignatureDetailViewController: SFSafariViewControllerDelegate {
    // MARK: 点击左上角的完成
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        viewModel?.requestSignCallBack("\(id)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success ?? false {
//                timer.invalidate()
                //刷新文件状态
                
            }
            controller.navigationController?.popViewController()
        })
    }

    // MARK: 加载完成
    func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
        print(#function)
    }
    
    // MARK: 点击右下角调用Safari浏览器打开
    func safariViewControllerWillOpenInBrowser(_ controller: SFSafariViewController) {
        print(#function)
    }
}
