package com.sencorsta.rabs.ui.mid;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.thread.ThreadUtil;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

public class ProgressDialog extends JDialog {
	private final JButton btnClose;
	private String sucTips;
	private String failTips;
	private final JTextArea statusTextArea;
	private JProgressBar progressBar;
	private Runnable runnable;

	public ProgressDialog(Component c, int maxProgress, String title, String sucTips, String failTips) {
		super((Frame) c, title, true);
		this.sucTips = sucTips;
		this.failTips = failTips;
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setSize(new Dimension(800, 300));
		JPanel mainPanel = new JPanel(new BorderLayout());

		JPanel labelPanel = new JPanel(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 1.0;
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbc.insets = new Insets(5, 5, 5, 5);
		statusTextArea = new JTextArea("请稍后...");
		statusTextArea.setEditable(false);
		statusTextArea.setWrapStyleWord(true);
		statusTextArea.setLineWrap(true);
		labelPanel.add(statusTextArea, gbc);
		mainPanel.add(labelPanel, BorderLayout.CENTER);

		progressBar = new JProgressBar(0, maxProgress);
		mainPanel.add(progressBar, BorderLayout.NORTH);

		btnClose = new JButton("确认");
		btnClose.addActionListener(event -> dispose());
		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		buttonPanel.add(btnClose);
		mainPanel.add(buttonPanel, BorderLayout.SOUTH);
		setContentPane(mainPanel);

		setLocationRelativeTo(c);
	}

	public void setJob(Runnable runnable) {
		this.runnable = runnable;
	}

	public void execute() {
		SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
			@Override
			protected Void doInBackground() {
				try {
					ThreadUtil.execute(() -> {
						for (int i = 0; i < progressBar.getMaximum(); i++) {
							ThreadUtil.sleep(100);
							publish(1);
						}
					});
					runnable.run();
					statusTextArea.setText(sucTips);
				} catch (Exception e) {
					statusTextArea.setText(failTips + e.getMessage() + ExceptionUtil.stacktraceToString(e));
				}
				return null;
			}

			@Override
			protected void process(java.util.List<Integer> chunks) {
				for (int progress : chunks) {
					progressBar.setValue(progressBar.getValue() + progress);
				}
			}

			@Override
			protected void done() {
				progressBar.setValue(progressBar.getMaximum());
				btnClose.setVisible(true);
			}
		};
		worker.execute();
	}
}
