package co.dc.aptiv;

import co.dc.commons.utils.DateTimeUtil;
import co.dc.aptiv.pojo.MaterielPojo;
import co.dc.aptiv.pojo.UserPojo;
import co.dc.aptiv.utils.KeyboardUtil;
import co.dc.aptiv.utils.ResetJButton;
import org.springframework.util.StringUtils;

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
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.List;

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

    private static final int SINGLE_SELECTION = 0;

    private JPanel contentPane;

    /**
     * 当前选中行的id
     */
    private String selectedId;
    /**
     * 当前选中行
     */
    private int selectedRowIndex = -1;
    /**
     * 表格
     */
    private JTable jt;
    private JScrollPane jsp;

    /**
     * 是否提交
     */
    private boolean flag = false;
    /**
     * 添加物料自定义弹框
     */
    private MyAddMateriel myAddMateriel;
    /**
     * 修改物料自定义弹框
     */
    private MyUpdateMateriel myUpdateMateriel;
    /**
     * 缓存dpn
     */
    String dpnVal;
    /**
     * 缓存cpn
     */
    String cpnVal;
    /**
     * 缓存type
     */
    String typeVal;
    /**
     * 当前用户
     */
    private UserPojo userPojo;


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

        setResizable(false);
        setUndecorated(true);
        setTitle("德尔福激光工控V1.1");
        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);
                MaterielFrame.this.dispose();
            }
        });
        btnNewButton.setBounds(894, 0, 130, 53);
        psnel1.add(btnNewButton);


        //添加物料
        if (userPojo.getRoleid() == 1) {
            JButton btnNewButton_1 = new JButton("添加物料");
            btnNewButton_1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    flag = false;
                    if (myAddMateriel == null) {
                        myAddMateriel = new MyAddMateriel(MaterielFrame.this, true);
                    }
                    myAddMateriel.show();
                    if (flag) {
                        MaterielPojo materielPojo = new MaterielPojo();
                        materielPojo.setDpn(dpnVal);
                        materielPojo.setCpn(cpnVal);
                        materielPojo.setType(typeVal);
                        materielPojo.setDelFlag(0);
                        materielPojo.setCreateTime(DateTimeUtil.getDateTimeString());
                        materielPojo.setModifyTime(DateTimeUtil.getDateTimeString());
                        long upid = AptivApp.materielService.saveMateriel(materielPojo);
                        if (upid > 0) {
                            JOptionPane.showMessageDialog(MaterielFrame.this, "添加成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                            contentPane.remove(jsp);
                            //删除表格并且刷新界面
                            contentPane.repaint();
                            //再次加载表格
                            loadjtable();
                        } else {
                            JOptionPane.showMessageDialog(MaterielFrame.this, "添加失败.", "提示", JOptionPane.ERROR_MESSAGE);
                        }
                        flag = false;
                    }
                }
            });
            btnNewButton_1.setBounds(246, 140, 127, 45);
            contentPane.add(btnNewButton_1);
        }

        //删除物料
        if (userPojo.getRoleid() == 1) {
            JButton button = new JButton("删除物料");
            //字体样式
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    // 取得用户所选单行
                    selectedRowIndex = jt.getSelectedRow();
                    //判断是否点中“行”
                    if (selectedRowIndex >= 0) {
                        // 取单元格数据,row是行号,column是列号
                        selectedId = jt.getValueAt(selectedRowIndex, 1) + "";
                    }
                    if (!StringUtils.isEmpty(selectedId)) {
                        //弹框确定删除？然后删除
                        int val = JOptionPane.showConfirmDialog(MaterielFrame.this, "删除物料有可能导致生产统计显示不正常，确定执行删除？", "提示", 2);
                        if (val == JOptionPane.YES_OPTION) {
                            int upid = AptivApp.materielService.deleteById(Long.parseLong(selectedId));
                            if (upid > 0) {
                                JOptionPane.showMessageDialog(MaterielFrame.this, "删除成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                                contentPane.remove(jsp);
                                //删除表格并且刷新界面
                                contentPane.repaint();
                                //再次加载表格
                                loadjtable();
                            } else {
                                JOptionPane.showMessageDialog(MaterielFrame.this, "删除失败.", "提示", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "请至少选一行进行操作.", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            });
            button.setBounds(415, 140, 127, 45);
            contentPane.add(button);
        }

        //修改物料
        if (userPojo.getRoleid() == 1) {
            JButton button_1 = new JButton("修改物料");
            button_1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    // 取得用户所选单行
                    selectedRowIndex = jt.getSelectedRow();
                    //判断是否点中“行”
                    if (selectedRowIndex >= 0) {
                        // 取单元格数据,row是行号,column是列号
                        selectedId = jt.getValueAt(selectedRowIndex, 1) + "";
                    }
                    if (!StringUtils.isEmpty(selectedId)) {
                        //弹框并且可单选角色提交
                        flag = false;
                        if (myUpdateMateriel == null) {
                            MaterielPojo materielPojo = AptivApp.materielService.findById(Long.parseLong(selectedId));
                            myUpdateMateriel = new MyUpdateMateriel(MaterielFrame.this, true, materielPojo);
                        }
                        myUpdateMateriel.show();
                        if (flag) {
                            MaterielPojo materielPojo = AptivApp.materielService.findById(Long.parseLong(selectedId));
                            materielPojo.setCpn(cpnVal);
                            materielPojo.setDpn(dpnVal);
                            materielPojo.setType(typeVal);
                            materielPojo.setModifyTime(DateTimeUtil.getDateTimeString());
                            int upid = AptivApp.materielService.updateMaterielpojo(materielPojo);
                            if (upid > 0) {
                                JOptionPane.showMessageDialog(MaterielFrame.this, "修改成功.", "提示", JOptionPane.INFORMATION_MESSAGE);
                                contentPane.remove(jsp);
                                //删除表格并且刷新界面
                                contentPane.repaint();
                                //再次加载表格
                                loadjtable();
                            } else {
                                JOptionPane.showMessageDialog(MaterielFrame.this, "修改失败.", "提示", JOptionPane.ERROR_MESSAGE);
                            }
                            flag = false;
                        }
                    } else {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "请至少选一行进行操作.", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            });
            button_1.setBounds(581, 140, 127, 45);
            contentPane.add(button_1);
        }

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

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

        /*
         * 根据当前用户权限来加载数据
         */
        List<MaterielPojo> materielPojos = AptivApp.materielService.listAll();
        Object[][] cellData = new Object[materielPojos.size()][7];
        for (int i = 0; i < cellData.length; i++) {
            cellData[i][0] = i + 1;
            cellData[i][1] = materielPojos.get(i).getId();
            cellData[i][2] = materielPojos.get(i).getDpn();
            cellData[i][3] = materielPojos.get(i).getCpn();
            cellData[i][4] = materielPojos.get(i).getType();
            cellData[i][5] = materielPojos.get(i).getCreateTime();
            cellData[i][6] = materielPojos.get(i).getModifyTime();
        }
        String[] columnNames = {"序号", "", "DPN", "CPN", "TYPE", "创建时间", "修改时间"};
        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(20);
        jt.getColumnModel().getColumn(1).setPreferredWidth(100);
        jt.getColumnModel().getColumn(2).setPreferredWidth(100);
        jt.getColumnModel().getColumn(3).setPreferredWidth(100);
        jt.getColumnModel().getColumn(4).setPreferredWidth(30);
        jt.getColumnModel().getColumn(5).setPreferredWidth(200);
        jt.getColumnModel().getColumn(6).setPreferredWidth(200);
        //隐藏指定列
        hideColumn(jt, 1);
        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 MyAddMateriel extends Dialog implements ActionListener {
        JLabel DPN = new JLabel("DPN");
        JLabel CPN = new JLabel("CPN");
        JLabel TYPE = new JLabel("TYPE");
        JTextField dpnText = new JTextField();
        JTextField cpnText = new JTextField();
        JTextField typeText = new JTextField();
        KeyboardUtil dpnKey = KeyboardUtil.getInstance();
        KeyboardUtil cpnKey = KeyboardUtil.getInstance();
        KeyboardUtil typeKey = KeyboardUtil.getInstance();
        JButton ok = new JButton("确定");
        JButton cancel = new JButton("取消");

        MyAddMateriel(MaterielFrame parent, boolean modal) {
            super(parent, modal);
            setTitle("物料添加");
            setSize(300, 260);
            setLocationRelativeTo(parent);
            setResizable(false);
            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) {
                    myAddMateriel.dispose();
                    myAddMateriel = null;
                }

                public void windowClosed(WindowEvent e) {
                }

                public void windowActivated(WindowEvent e) {
                }
            });
            setLayout(null);
            add(DPN);
            add(CPN);
            add(TYPE);
            dpnKey.register(dpnText);
            cpnKey.register(cpnText);
            typeKey.register(typeText);
            DPN.setBounds(20, 50, 54, 15);
            CPN.setBounds(20, 97, 54, 15);
            TYPE.setBounds(20, 144, 54, 15);
            add(dpnText);
            dpnText.setBounds(68, 38, 199, 40);
            dpnText.setColumns(10);
            add(cpnText);
            cpnText.setBounds(68, 85, 199, 40);
            cpnText.setColumns(10);
            add(typeText);
            typeText.setBounds(68, 132, 199, 40);
            typeText.setColumns(10);
            add(ok);
            add(cancel);
            ok.setBounds(43, 200, 80, 40);
            cancel.setBounds(165, 200, 80, 40);
            ok.addActionListener(this);
            cancel.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            flag = false;
            if (e.getSource() == ok) {
                dpnVal = dpnText.getText();
                cpnVal = cpnText.getText();
                typeVal = typeText.getText();
                //如果type位数等于1 位，进行补位
                if (typeVal.length() == 1) {
                    typeVal = typeVal + " ";
                }
                if (!StringUtils.isEmpty(dpnVal) && !StringUtils.isEmpty(cpnVal) && !StringUtils.isEmpty(typeVal)) {
                    int dpni = AptivApp.materielService.isExistByParam("dpn", dpnVal, 8, 0);
                    int cpni = AptivApp.materielService.isExistByParam("cpn", cpnVal, 10, 0);
                    int typei = AptivApp.materielService.isExistByParam("type", typeVal, 2, 0);
                    if (dpni == 1) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "DPN已存在，请新填写DPN", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (dpni == 2) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "DPN的位数不等于8位", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (cpni == 1) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "CPN已存在，请新填写CPN", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (cpni == 2) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "CPN的位数不等于10位", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (typei == 1) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "TYPE已存在，请新填写TYPE", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (typei == 2) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "TYPE的位数超过2位", "提示", JOptionPane.ERROR_MESSAGE);
                    } else {
                        flag = true;
                        dispose();
                        myAddMateriel = null;
                    }
                } else {
                    JOptionPane.showMessageDialog(MaterielFrame.this, "请填写完整.", "提示", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                dispose();
                myAddMateriel = null;
            }
        }
    }

    /**
     * 修改权限的自定义弹框
     *
     * @author lyy
     */
    class MyUpdateMateriel extends Dialog implements ActionListener {
        JLabel DPN = new JLabel("DPN");
        JLabel CPN = new JLabel("CPN");
        JLabel TYPE = new JLabel("TYPE");
        JTextField dpnText = new JTextField();
        JTextField cpnText = new JTextField();
        JTextField typeText = new JTextField();
        KeyboardUtil dpnKey = KeyboardUtil.getInstance();
        KeyboardUtil cpnKey = KeyboardUtil.getInstance();
        KeyboardUtil typeKey = KeyboardUtil.getInstance();
        JButton ok = new JButton("确定");
        JButton cancel = new JButton("取消");
        MaterielPojo materiel = null;

        MyUpdateMateriel(MaterielFrame parent, boolean modal, MaterielPojo materielPojo) {
            super(parent, modal);
            materiel = materielPojo;
            setTitle("物料修改");
            setSize(300, 260);
            setLocationRelativeTo(parent);
            setResizable(false);
            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) {
                    myUpdateMateriel.dispose();
                    myUpdateMateriel = null;
                }

                public void windowClosed(WindowEvent e) {
                }

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

            setLayout(null);
            add(DPN);
            add(CPN);
            add(TYPE);
            dpnKey.register(dpnText);
            cpnKey.register(cpnText);
            typeKey.register(typeText);
            DPN.setBounds(20, 50, 54, 15);
            CPN.setBounds(20, 97, 54, 15);
            TYPE.setBounds(20, 144, 54, 15);
            add(dpnText);
            dpnText.setBounds(68, 38, 199, 40);
            dpnText.setColumns(10);
            add(cpnText);
            cpnText.setBounds(68, 85, 199, 40);
            cpnText.setColumns(10);
            add(typeText);
            typeText.setBounds(68, 132, 199, 40);
            typeText.setColumns(10);
            add(ok);
            add(cancel);
            ok.setBounds(43, 200, 80, 40);
            cancel.setBounds(165, 200, 80, 40);
            ok.addActionListener(this);
            cancel.addActionListener(this);
            dpnText.setText(materielPojo.getDpn());
            cpnText.setText(materielPojo.getCpn());
            typeText.setText(materielPojo.getType().trim());
        }

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == ok) {
                dpnVal = dpnText.getText();
                cpnVal = cpnText.getText();
                typeVal = typeText.getText();
                //如果type位数等于1 位，进行补位
                if (typeVal.length() == 1) {
                    typeVal = typeVal + " ";
                }
                if (!StringUtils.isEmpty(dpnVal) && !StringUtils.isEmpty(cpnVal) && !StringUtils.isEmpty(typeVal)) {
                    int dpni = AptivApp.materielService.isExistByParam("dpn", dpnVal, 8, materiel.getId());
                    int cpni = AptivApp.materielService.isExistByParam("cpn", cpnVal, 10, materiel.getId());
                    int typei = AptivApp.materielService.isExistByParam("type", typeVal, 2, materiel.getId());
                    if (dpni == 1) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "DPN已存在，请新填写DPN", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (dpni == 2) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "DPN的位数不等于8位", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (cpni == 1) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "CPN已存在，请新填写CPN", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (cpni == 2) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "CPN的位数不等于10位", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (typei == 1) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "TYPE已存在，请新填写TYPE", "提示", JOptionPane.ERROR_MESSAGE);
                    } else if (typei == 2) {
                        JOptionPane.showMessageDialog(MaterielFrame.this, "TYPE的位数超过2位", "提示", JOptionPane.ERROR_MESSAGE);
                    } else {
                        flag = true;
                        dispose();
                        myUpdateMateriel = null;
                    }
                } else {
                    JOptionPane.showMessageDialog(MaterielFrame.this, "请填写完整.", "提示", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                dispose();
                myUpdateMateriel = null;
            }
        }
    }


    /**
     * 隐藏指定列 lxl
     *
     * @param table 要隐藏的表
     * @param index 要隐藏的列
     */
    public static void hideColumn(JTable table, int index) {
        TableColumn tc = table.getColumnModel().getColumn(index);
        tc.setMaxWidth(0);
        tc.setPreferredWidth(0);
        tc.setMinWidth(0);
        tc.setWidth(0);
        table.getTableHeader().getColumnModel().getColumn(index).setMaxWidth(0);
        table.getTableHeader().getColumnModel().getColumn(index).setMinWidth(0);
    }

}
