package co.dc.aptiv;

import co.dc.commons.utils.DateTimeUtil;
import co.dc.aptiv.pojo.UserPojo;
import co.dc.aptiv.utils.KeyboardUtil;
import co.dc.aptiv.utils.ResetJButton;

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;

/**
 * @describe: 用户管理
 * @author: liuxinglong
 * @version: 2018/4/17 15:21
 */
public class UserFrame extends JFrame {

    private static final int SINGLE_SELECTION = 0;

    private JPanel contentPane;

    private String selectedId = "0";
    private int selectedRowIndex = -1;
    private JTable jt;
    private JScrollPane jsp;

    boolean tijiao = false;
    MyDialog_modifypassword myDialog_modifypassword;
    String prepass;
    String nowpass;
    MyDialog_modifypower myDialog_modifypower;
    long powerid = 0;
    MyDialog_adduser myDialog_adduser;
    String sloginname;
    String sloginpassword;
    String srealname;
    private UserPojo userPojo = new UserPojo();


    /**
     * Create the frame.
     */
    public UserFrame() {
        /*
         * 根据当前用户权限来加载数据
         */
        //获取当前登录的用户信息
        userPojo = AptivApp.session;

        setResizable(false);
        setUndecorated(true);
        setTitle("德尔福激光工控V1.2");
        setAlwaysOnTop(!isAlwaysOnTop());

        setBounds(100, 100, 1024, 768);
        setLocationRelativeTo(null);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setBackground(Color.white);
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel psnel1 = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Image image = new ImageIcon(MainFrame.class.getResource("/co/dc/aptiv/img/head.png")).getImage();
                g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
            }
        };
        psnel1.setBounds(0, 0, 1024, 78);
        psnel1.setLayout(null);
        contentPane.add(psnel1);

        JButton btnNewButton = new ResetJButton("/co/dc/aptiv/img/return-normal.png", "/co/dc/aptiv/img/return-hover.png", "/co/dc/aptiv/img/return-hover.png");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new MainFrame().setVisible(true);
                UserFrame.this.dispose();
            }
        });
        btnNewButton.setBounds(894, 0, 130, 53);
        psnel1.add(btnNewButton);

        JButton button_2 = new JButton("修改密码");
        //字体样式
//		button_2.setFont(new Font("微软雅黑",Font.PLAIN,16));
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                // 取得用户所选单行
                selectedRowIndex = jt.getSelectedRow();
                //判断是否点中“行”
                if (selectedRowIndex >= 0) {
                    // 取单元格数据,row是行号,column是列号
                    selectedId = jt.getValueAt(selectedRowIndex, 1) + "";
                }
                if (!"0".equals(selectedId)) {
                    //弹框填写密码后提交
                    tijiao = false;
                    if (myDialog_modifypassword == null) {
                        myDialog_modifypassword = new MyDialog_modifypassword(UserFrame.this, true);
                    }
                    myDialog_modifypassword.show();
                    if (tijiao) {
                        int upid = AptivApp.userService.updatepass(Long.parseLong(selectedId), prepass, nowpass);
                        if (upid > 0) {
                            JOptionPane.showMessageDialog(UserFrame.this, "修改成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(UserFrame.this, "密码有误,修改失败.", "提示", JOptionPane.ERROR_MESSAGE);
                        }
                        tijiao = false;
                    }
                } else {
                    JOptionPane.showMessageDialog(UserFrame.this, "请至少选一行进行操作.", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        button_2.setBounds(77, 140, 127, 45);
        contentPane.add(button_2);

        if (userPojo.getPowers().indexOf("管理用户") >= 0) {
            JButton btnNewButton_1 = new JButton("添加用户");
            //字体样式
//			btnNewButton_1.setFont(new Font("微软雅黑",Font.PLAIN,16));
            btnNewButton_1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    tijiao = false;
                    if (myDialog_adduser == null) {
                        myDialog_adduser = new MyDialog_adduser(UserFrame.this, true);
                    }
                    myDialog_adduser.show();
                    if (tijiao) {
                        if (!AptivApp.userService.checkloginname(sloginname)) {
                            JOptionPane.showMessageDialog(UserFrame.this, "登录名已存在,请更换.", "提示", JOptionPane.WARNING_MESSAGE);
                        } else {
                            UserPojo uPojo = new UserPojo();
                            uPojo.setLoginname(sloginname);
                            uPojo.setPassword(sloginpassword);
                            uPojo.setRoleid(2);
                            uPojo.setRealname(srealname);
                            uPojo.setLoginstatus("0");
                            uPojo.setDelflag("0");
                            long upid = AptivApp.userService.save(uPojo);
                            if (upid > 0) {
                                JOptionPane.showMessageDialog(UserFrame.this, "添加成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                                contentPane.remove(jsp);
                                //删除表格并且刷新界面
                                contentPane.repaint();
                                //再次加载表格
                                loadjtable();
                            } else {
                                JOptionPane.showMessageDialog(UserFrame.this, "添加失败.", "提示", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                        tijiao = false;
                    }
                }
            });
            btnNewButton_1.setBounds(246, 140, 127, 45);
            contentPane.add(btnNewButton_1);
        }
        if (userPojo.getPowers().indexOf("管理用户") >= 0) {
            JButton button = new JButton("删除用户");
            //字体样式
//			button.setFont(new Font("微软雅黑",Font.PLAIN,16));
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    // 取得用户所选单行
                    selectedRowIndex = jt.getSelectedRow();
                    //判断是否点中“行”
                    if (selectedRowIndex >= 0) {
                        // 取单元格数据,row是行号,column是列号
                        selectedId = jt.getValueAt(selectedRowIndex, 1) + "";
                    }
                    if (!"0".equals(selectedId)) {
                        //弹框确定删除？然后删除
                        int val = JOptionPane.showConfirmDialog(UserFrame.this, "确定执行删除？", "提示", 2);
                        if (val == JOptionPane.YES_OPTION) {
                            int upid = AptivApp.userService.deluser(userPojo, Long.parseLong(selectedId));
                            if (upid > 0) {
                                JOptionPane.showMessageDialog(UserFrame.this, "删除成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                                contentPane.remove(jsp);
                                //删除表格并且刷新界面
                                contentPane.repaint();
                                //再次加载表格
                                loadjtable();
                            } else {
                                JOptionPane.showMessageDialog(UserFrame.this, "删除失败.", "提示", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(UserFrame.this, "请至少选一行进行操作.", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            });
            button.setBounds(415, 140, 127, 45);
            contentPane.add(button);
        }
        if (userPojo.getPowers().indexOf("管理用户") >= 0) {
            JButton button_1 = new JButton("修改权限");
            //字体样式
//			button_1.setFont(new Font("微软雅黑",Font.PLAIN,16));
            button_1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    // 取得用户所选单行
                    selectedRowIndex = jt.getSelectedRow();
                    //判断是否点中“行”
                    if (selectedRowIndex >= 0) {
                        // 取单元格数据,row是行号,column是列号
                        selectedId = jt.getValueAt(selectedRowIndex, 1) + "";
                    }
                    if (!"0".equals(selectedId)) {
                        //弹框并且可单选角色提交
                        tijiao = false;
                        if (myDialog_modifypower == null) {
                            myDialog_modifypower = new MyDialog_modifypower(UserFrame.this, true);
                        }
                        myDialog_modifypower.show();
                        if (tijiao) {
                            int upid = AptivApp.userService.updaterole(userPojo, Long.parseLong(selectedId), powerid);
                            if (upid > 0) {
                                powerid = 0;
                                JOptionPane.showMessageDialog(UserFrame.this, "修改成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                                //删除表格
                                contentPane.remove(jt);
                                //加载表格
                                loadjtable();
                            } else {
                                JOptionPane.showMessageDialog(UserFrame.this, "修改失败.", "提示", JOptionPane.ERROR_MESSAGE);
                            }
                            tijiao = false;
                        }
                    } else {
                        JOptionPane.showMessageDialog(UserFrame.this, "请至少选一行进行操作.", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            });
            button_1.setBounds(581, 140, 127, 45);
            contentPane.add(button_1);
        }

        /*
         * 加载表格和数据
         */
        loadjtable();
    }

    /**
     * 加载表格和数据的方法
     */
    public void loadjtable() {

        /*
         * 根据当前用户权限来加载数据
         */
        List<UserPojo> userPojos = new ArrayList<UserPojo>();
        userPojos = AptivApp.userService.getuserinfo(userPojo, 2);
        Object[][] cellData = new Object[userPojos.size()][6];
        for (int i = 0; i < cellData.length; i++) {
            cellData[i][0] = i + 1;
            cellData[i][1] = userPojos.get(i).getId();
            cellData[i][2] = userPojos.get(i).getLoginname();
            cellData[i][3] = userPojos.get(i).getRealname();
            cellData[i][4] = userPojos.get(i).getRolename();
            cellData[i][5] = userPojos.get(i).getPowers();
        }
        String[] columnNames = {"序号", "编号", "登录名", "创建时间", "权限", "权限内容"};
        jt = new JTable(cellData, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

//		jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jt.getColumnModel().getColumn(0).setPreferredWidth(30);
        jt.getColumnModel().getColumn(1).setPreferredWidth(20);
        jt.getColumnModel().getColumn(2).setPreferredWidth(100);
        jt.getColumnModel().getColumn(3).setPreferredWidth(100);
        jt.getColumnModel().getColumn(4).setPreferredWidth(100);
        jt.getColumnModel().getColumn(5).setPreferredWidth(400);

        jt.setSurrendersFocusOnKeystroke(true);
        //单选
        jt.setSelectionMode(SINGLE_SELECTION);
        //充满
        jt.setFillsViewportHeight(true);
        /*
         * 行设置
         */
        //行的高度
        jt.setRowHeight(30);
//		jt.setFont(new Font("微软雅黑",Font.PLAIN,16));//行字体样式
        //单元格内容居中
//        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
//        tcr.setHorizontalAlignment(SwingConstants.CENTER);
//        jt.setDefaultRenderer(Object.class, tcr);
        /*
         * 表头设置
         */
        //得到表头
        JTableHeader header = jt.getTableHeader();
//		header.setFont(new Font("微软雅黑",Font.PLAIN,16));//表头字体样式
        //设置表头的高度
        header.setPreferredSize(new Dimension(header.getWidth(), 30));
        DefaultTableCellRenderer hr = (DefaultTableCellRenderer) header.getDefaultRenderer();
        //表头内容居左
        hr.setHorizontalAlignment(DefaultTableCellRenderer.LEFT);


        jsp = new JScrollPane(jt, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsp.setViewportBorder(new CompoundBorder());
        jsp.setBounds(77, 205, 833, 510);
        contentPane.add(jsp);
    }

    /**
     * 修改密码的自定义弹框
     *
     * @author lyy
     */
    class MyDialog_modifypassword extends Dialog implements ActionListener {
        //加载面板
        JLabel label1 = new JLabel("旧密码");
        JLabel label2 = new JLabel("新密码");
        KeyboardUtil kk = KeyboardUtil.getInstance();
        KeyboardUtil kk2 = KeyboardUtil.getInstance();
        JTextField rows = new JPasswordField(50);

        JTextField columns = new JPasswordField(50);
        JButton ok = new JButton("确定");
        JButton cancel = new JButton("取消");

        MyDialog_modifypassword(UserFrame parent, boolean modal) {
            super(parent, modal);

            //复原密码数据
            prepass = "";
            nowpass = "";

            setTitle("密码修改");
            setSize(300, 200);
            setLocationRelativeTo(parent);
            setResizable(false);
//         setUndecorated(true);
            this.addWindowListener(new WindowListener() {
                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                    myDialog_modifypassword.dispose();
                    myDialog_modifypassword = null;
                }

                public void windowClosed(WindowEvent e) {
                }

                public void windowActivated(WindowEvent e) {
                }
            });

            setLayout(null);
            add(label1);
            add(label2);
            label1.setBounds(26, 36, 65, 20);
            label2.setBounds(26, 80, 65, 20);
            kk.register(rows,true);
            add(rows);
            kk2.register(columns,true);
            add(columns);
            rows.setBounds(86, 30, 165, 34);
            columns.setBounds(86, 74, 165, 34);
            add(ok);
            add(cancel);
            ok.setBounds(40, 140, 80, 40);
            cancel.setBounds(150, 140, 80, 40);
            ok.addActionListener(this);
            cancel.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            tijiao = false;
            if (e.getSource() == ok) {
                prepass = rows.getText();
                nowpass = columns.getText();
                tijiao = true;
            }
            dispose();
            myDialog_modifypassword = null;
        }
    }

    /**
     * 用户添加的自定义弹框
     *
     * @author lyy
     */
    class MyDialog_adduser extends Dialog implements ActionListener {
        //加载面板
        JLabel label = new JLabel("登录名");
        JLabel label_1 = new JLabel("密 码");
        JTextField textField = new JTextField();
        KeyboardUtil kk = KeyboardUtil.getInstance();
        KeyboardUtil kk2 = KeyboardUtil.getInstance();
        JTextField textField_1 = new JPasswordField();
        JButton ok = new JButton("确定");
        JButton cancel = new JButton("取消");

        MyDialog_adduser(UserFrame parent, boolean modal) {
            super(parent, modal);

            setTitle("用户添加");
            setSize(300, 225);
            setLocationRelativeTo(parent);
            setResizable(false);
//         setUndecorated(true);
            this.addWindowListener(new WindowListener() {
                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                    myDialog_adduser.dispose();
                    myDialog_adduser = null;
                }

                public void windowClosed(WindowEvent e) {
                }

                public void windowActivated(WindowEvent e) {
                }
            });
            setLayout(null);
            add(label);
            add(label_1);
            kk.register(textField);
            label.setBounds(20, 50, 54, 15);
            label_1.setBounds(24, 97, 54, 15);
            add(textField);
            kk2.register(textField_1,true);
            textField.setBounds(68, 38, 199, 40);
            textField.setColumns(10);
            add(textField_1);
            textField_1.setBounds(68, 85, 199, 40);
            textField_1.setColumns(10);
            add(ok);
            add(cancel);
            ok.setBounds(43, 150, 80, 40);
            cancel.setBounds(165, 150, 80, 40);
            ok.addActionListener(this);
            cancel.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            tijiao = false;
            if (e.getSource() == ok) {
                sloginname = textField.getText();
                sloginpassword = textField_1.getText();
                srealname = DateTimeUtil.getDateString();
                if (!sloginname.equals("") && !sloginpassword.equals("") && !srealname.equals("")) {
                    tijiao = true;
                    dispose();
                    myDialog_adduser = null;
                } else {
                    JOptionPane.showMessageDialog(UserFrame.this, "请填写完整.", "提示", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                dispose();
                myDialog_adduser = null;
            }
        }
    }

    /**
     * 修改权限的自定义弹框
     *
     * @author lyy
     */
    class MyDialog_modifypower extends Dialog implements ActionListener {
        //加载面板
        JRadioButton rdbtnNewRadioButton = new JRadioButton("管理员");
        JRadioButton radioButton = new JRadioButton("操作员");
        ButtonGroup buttonGroup = new ButtonGroup();

        JButton ok = new JButton("确定");
        JButton cancel = new JButton("取消");

        MyDialog_modifypower(UserFrame parent, boolean modal) {
            super(parent, modal);

//         setUndecorated(true);
            this.addWindowListener(new WindowListener() {
                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                    myDialog_modifypower.dispose();
                    myDialog_modifypower = null;
                }

                public void windowClosed(WindowEvent e) {
                }

                public void windowActivated(WindowEvent e) {
                }
            });
            setTitle("权限修改");
            setSize(300, 180);
            setLocationRelativeTo(parent);
            setResizable(false);
            setLayout(null);

            add(rdbtnNewRadioButton);
            rdbtnNewRadioButton.setSelected(true);
            rdbtnNewRadioButton.setToolTipText("管理用户、修改权限、修改密码、添加用户、删除用户");
            rdbtnNewRadioButton.setBounds(50, 25, 80, 29);

            add(radioButton);
            radioButton.setToolTipText("修改密码");
            radioButton.setBounds(50, 55, 160, 40);

            buttonGroup.add(rdbtnNewRadioButton);
            buttonGroup.add(radioButton);

            add(ok);
            add(cancel);
            ok.setBounds(40, 102, 80, 40);
            cancel.setBounds(153, 102, 80, 40);
            ok.addActionListener(this);
            cancel.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == ok) {
                if (rdbtnNewRadioButton.isSelected()) {
                    powerid = 1;
                }
                if (radioButton.isSelected()) {
                    powerid = 2;
                }
                tijiao = true;
            }
            dispose();
            myDialog_modifypower = null;
        }
    }
}
