import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.json.JSONObject;

public class ConfigGui extends JFrame {
    private static final long serialVersionUID = -6324130816194166022L;

    // 输入框
    private JTextField textField;
    private ConfigurationPanel mPanel;

    private StockBean bean;

    private JSONObject fileJson;
    String fCode = "";
    String fCount = "";
    String fCost = "";
    String fMax = "";
    String fMin = "";
    //自动刷新
    private boolean isAuto = false;
    //定时任务
    private Timer timer;

    public ConfigGui() {
        // 获取数据
        bean = TrayUpdate.list.get(0);

        try {
            String r = FileUtil.readTxtFile();
            if (r == null || r.equals("")) {
                fileJson = new JSONObject();
            } else {
                fileJson = new JSONObject(r);
            }

            fCode = fileJson.getString("code");
            fCount = fileJson.getString("count");
            fCost = fileJson.getString("cost");
            fMax = fileJson.getString("max");
            fMin = fileJson.getString("min");

        } catch (Exception e) {
        }

        // 设置窗口属性
        setTitle("Stock Code Config");
        setSize(500, 400);
        setResizable(false);

        mPanel = new ConfigurationPanel();
        add(mPanel, BorderLayout.CENTER);

        //彻底关闭窗口
//		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //关闭窗口时停止任务
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (timer != null) {
                    timer.cancel();
                }
            }
        });
    }


    /**
     * 面板配置
     */
    class ConfigurationPanel extends JPanel implements ActionListener {

        private static final long serialVersionUID = 1L;
        private JTextField countText;
        private JTextField costText;
        private JTextField maxText;
        private JTextField minText;
        private JButton autoBtn;

        public ConfigurationPanel() {

            // 代码设置层
            JPanel codePanel = new JPanel();
            JLabel codeDesc = new JLabel("Stock Code: ");
            textField = new JTextField(8);
            textField.setText(fCode);
            JButton btn = new JButton("START");
            btn.setActionCommand("code");
            btn.addActionListener(this);

            FlowLayout codeLayout = new FlowLayout();
            codePanel.setBackground(Color.decode("#dfdfdf"));
            codePanel.setLayout(codeLayout);
            codePanel.add(codeDesc);
            codePanel.add(textField);
            codePanel.add(btn);

            //大盘行情
            JPanel daPanel = new JPanel();
            JLabel daLabel = new JLabel("上证   " + getSH() + "          深证   " + getSZ());
            FlowLayout daLayout = new FlowLayout();
            daPanel.setBackground(Color.decode("#afafaf"));
            daPanel.setLayout(daLayout);
            daPanel.add(daLabel);


            // 股票信息层1
            JPanel stockPanel = new JPanel();
            JLabel nameLabel = new JLabel(
                    TrayUpdate.getToolTips(TrayUpdate.list) + "  "
                            + bean.getCurPrice());
            FlowLayout nameLayout = new FlowLayout();
            stockPanel.setBackground(Color.decode("#afafaf"));
            stockPanel.setLayout(nameLayout);
            stockPanel.add(nameLabel);

            // 股票信息层2
            JPanel infoPanel = new JPanel();
            JLabel jName1 = new JLabel("今开   " + bean.getTdPrice());
            JLabel jName2 = new JLabel("昨收   " + bean.getYtdPrice());
            JLabel jName3 = new JLabel("最高   " + bean.getMaxPrice());
            JLabel jName4 = new JLabel("最低   " + bean.getMinPrice());
            JLabel jName5 = new JLabel("成交数   " + bean.getDealCount());
            JLabel jName6 = new JLabel("成交额   " + bean.getDealMoney());

            GridLayout infoLayout = new GridLayout(2, 3, 1, 5);
            infoPanel.setBackground(Color.decode("#dfdfdf"));
            infoPanel.setLayout(infoLayout);
            infoPanel.add(jName1);
            infoPanel.add(jName3);
            infoPanel.add(jName5);
            infoPanel.add(jName2);
            infoPanel.add(jName4);
            infoPanel.add(jName6);

            // 股票信息层3
            JPanel pricePanel = new JPanel();
            JLabel buy1 = new JLabel("买一   " + bean.getBuy1Price() + "  "
                    + bean.getBuy1Count());
            JLabel buy2 = new JLabel("买二   " + bean.getBuy2Price() + "  "
                    + bean.getBuy2Count());
            JLabel buy3 = new JLabel("买三   " + bean.getBuy3Price() + "  "
                    + bean.getBuy3Count());
            JLabel buy4 = new JLabel("买四   " + bean.getBuy4Price() + "  "
                    + bean.getBuy4Count());
            JLabel buy5 = new JLabel("买五   " + bean.getBuy5Price() + "  "
                    + bean.getBuy5Count());

            JLabel sale1 = new JLabel("卖一   " + bean.getSale1Price() + "  "
                    + bean.getSale1Count());
            JLabel sale2 = new JLabel("卖二   " + bean.getSale2Price() + "  "
                    + bean.getSale2Count());
            JLabel sale3 = new JLabel("卖三   " + bean.getSale3Price() + "  "
                    + bean.getSale3Count());
            JLabel sale4 = new JLabel("卖四   " + bean.getSale4Price() + "  "
                    + bean.getSale4Count());
            JLabel sale5 = new JLabel("卖五   " + bean.getSale5Price() + "  "
                    + bean.getSale5Count());

            GridLayout priceLayout = new GridLayout(5, 2, 30, 5);
            pricePanel.setBackground(Color.decode("#afafaf"));
            pricePanel.setLayout(priceLayout);
            pricePanel.add(buy1);
            pricePanel.add(sale1);
            pricePanel.add(buy2);
            pricePanel.add(sale2);
            pricePanel.add(buy3);
            pricePanel.add(sale3);
            pricePanel.add(buy4);
            pricePanel.add(sale4);
            pricePanel.add(buy5);
            pricePanel.add(sale5);

            // 收益层
            JPanel earnPanel = new JPanel();
            int count = fCount.equals("") ? 0 : Integer.parseInt(fCount);
            float cost = fCost.equals("") ? 0 : Float.parseFloat(fCost);
            float cur = Float.parseFloat(TrayUpdate.currentPrice(bean
                    .getCurPrice()));
            String earn = "持有   " + count + "       成本   " + cost
                    + "       收益   " + count * (cur - cost);
            JLabel earnLabel = new JLabel(earn);
            FlowLayout earnLayout = new FlowLayout();
            earnPanel.setBackground(Color.decode("#dfdfdf"));
            earnPanel.setLayout(earnLayout);
            earnPanel.add(earnLabel);

            JPanel myPanel = new JPanel();
            JLabel countLable = new JLabel("持有");
            countText = new JTextField(8);
            countText.setText(fCount);
            JLabel costLable = new JLabel("    成本");
            costText = new JTextField(8);
            costText.setText(fCost);
            JButton myBtn = new JButton("  SET  ");
            myBtn.setActionCommand("my");
            myBtn.addActionListener(this);

            FlowLayout myLayout = new FlowLayout();
            myPanel.setBackground(Color.decode("#dfdfdf"));
            myPanel.setLayout(myLayout);
            myPanel.add(countLable);
            myPanel.add(countText);
            myPanel.add(costLable);
            myPanel.add(costText);
            myPanel.add(myBtn);

            JPanel limitPanel = new JPanel();
            JLabel maxLable = new JLabel("上限");
            maxText = new JTextField(8);
            maxText.setText(fMax);
            JLabel minLable = new JLabel("    下限");
            minText = new JTextField(8);
            minText.setText(fMin);
            JButton limitBtn = new JButton("WARN");
            limitBtn.setActionCommand("limit");
            limitBtn.addActionListener(this);

            FlowLayout limitLayout = new FlowLayout();
            limitPanel.setBackground(Color.decode("#afafaf"));
            limitPanel.setLayout(limitLayout);
            limitPanel.add(maxLable);
            limitPanel.add(maxText);
            limitPanel.add(minLable);
            limitPanel.add(minText);
            limitPanel.add(limitBtn);

            //控制自动刷新按钮
            JPanel refreshPanel = new JPanel();
            String str = "";
            if (!isAuto) {
                str = "RUN";
            } else {
                str = "STOP";
            }
            autoBtn = new JButton(str);
            autoBtn.setActionCommand("auto");
            autoBtn.addActionListener(this);

            FlowLayout autoLayout = new FlowLayout();
            refreshPanel.setLayout(autoLayout);
            refreshPanel.add(autoBtn);

            // 合并层
            JPanel mainPanel = new JPanel();
            BoxLayout mainGrid = new BoxLayout(mainPanel, BoxLayout.Y_AXIS);
            mainPanel.setLayout(mainGrid);
            mainPanel.add(codePanel);
            mainPanel.add(daPanel);
            mainPanel.add(stockPanel);
            mainPanel.add(infoPanel);
            mainPanel.add(pricePanel);
            mainPanel.add(earnPanel);
            mainPanel.add(myPanel);
            mainPanel.add(limitPanel);
            mainPanel.add(refreshPanel);
            add(mainPanel);

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // 关闭停市控制，再次刷新实时数据
            TrayUpdate.isStop = false;

            // 按钮响应--设置股票代码
            if ("code".equals(e.getActionCommand())) {
                String input = textField.getText().toString().trim();
                if (!input.equals("")) {
                    // 输入的代码试错
                    String code = HttpUtil.verifyCode(input);
                    if (code != null) {
                        // 更新正确代码
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", code);
                        FileUtil.contentToTxt(jsonObject.toString());

                        TrayUpdate.code = code;

                    }
                }

                // 关闭窗口
                dispose();
            }

            // 按钮响应--设置持仓数据
            if ("my".equals(e.getActionCommand())) {
                String count = countText.getText().toString().trim();
                String cost = costText.getText().toString().trim();

                if (!"".equals(count) && !"".equals(cost)) {
                    try {
                        String r = FileUtil.readTxtFile();
                        JSONObject jsonObject;
                        if (r == null || r.equals("")) {
                            jsonObject = new JSONObject();
                        } else {
                            jsonObject = new JSONObject(r);
                        }

                        jsonObject.put("count", count);
                        jsonObject.put("cost", cost);
                        FileUtil.contentToTxt(jsonObject.toString());

                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }

            // 按钮响应--设置预警
            if ("limit".equals(e.getActionCommand())) {
                String max = maxText.getText().toString().trim();
                String min = minText.getText().toString().trim();

                if (!"".equals(max) && !"".equals(min)) {
                    try {
                        String r = FileUtil.readTxtFile();
                        JSONObject jsonObject;
                        if (r == null || r.equals("")) {
                            jsonObject = new JSONObject();
                        } else {
                            jsonObject = new JSONObject(r);
                        }

                        jsonObject.put("max", max);
                        jsonObject.put("min", min);
                        jsonObject.put("maxW", 0);
                        jsonObject.put("minW", 0);
                        FileUtil.contentToTxt(jsonObject.toString());

                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }


            // 按钮响应--自动刷新控件
            if ("auto".equals(e.getActionCommand())) {
                if (isAuto) {
                    isAuto = false;
                    timer.cancel();
                    autoBtn.setText("RUN");
                } else {
                    isAuto = true;
                    autoRefreshTask();
                }
            }

        }
    }

    /**
     * 自动刷新行情的任务
     */
    public void autoRefreshTask() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                bean = TrayUpdate.list.get(0);
                mPanel.removeAll();

                mPanel = new ConfigurationPanel();
                add(mPanel, BorderLayout.CENTER);

                mPanel.revalidate();
                mPanel.repaint();
            }
        }, new Date(), 2000);
    }

    public String getSH() {
        try {
            ArrayList<StockBean> list = HttpUtil.StockHttp("sh000001");
            return list.get(0).getCurPrice();
        } catch (Exception e) {
            return "";
        }
    }

    public String getSZ() {
        try {
            ArrayList<StockBean> list = HttpUtil.StockHttp("sz399001");
            return list.get(0).getCurPrice();
        } catch (Exception e) {
            return "";
        }
    }


}
