package nc.ui.hr.baod_orders.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import nc.bs.framework.common.NCLocator;
import nc.itf.hr.SocialInsuranceAllMaintain;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UIButton;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.beans.UIPanel;
import nc.vo.ecpubapp.pattern.data.ValueUtils;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.pub.MathTool;

/**
 * 公积金分摊表修改界面
 * @author YaoYu
 *
 */
public class AccumulationFundAllUpdateDialog extends UIDialog {

	private SocialInsuranceAllMaintain siaMaintain = NCLocator.getInstance().lookup(SocialInsuranceAllMaintain.class);
	private IUAPQueryBS iuap = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private List<Object[]> selectedData;
	private UIPanel btnUIPanel;
	private UIButton btnOK;
	private ActionHandler actionHandler = new ActionHandler();
	private JTable table;
	private String orgCode;
	private String period;

	public AccumulationFundAllUpdateDialog(List<Object[]> selectedData, String orgCode, String period) throws Exception {
		this.selectedData = selectedData;
		this.orgCode = orgCode;
		this.period = period;
		initialize();
		addComponents();
	}

	private void initialize() {
		setLayout(new BorderLayout());
		setSize(new Dimension(1000, 350));
		this.setResizable(true);
		add(this.getBtnUIPanel(), BorderLayout.SOUTH);
		this.addActionListener();
	}

	public UIPanel getBtnUIPanel() {
		if (this.btnUIPanel == null) {
			this.btnUIPanel = new nc.ui.pub.beans.UIPanel();
			this.btnUIPanel.add(this.getBtnOK(), this.getBtnOK().getName());
		}
		return this.btnUIPanel;
	}

	private UIButton getBtnOK() {
		if (this.btnOK == null) {
			this.btnOK = new UIButton();
			this.btnOK.setName("btnOK");
			this.btnOK.setText("确定(Y)");
		}
		return this.btnOK;
	}

	private void addActionListener() {
		this.getBtnOK().addActionListener(this.actionHandler);

	}

	class ActionHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == AccumulationFundAllUpdateDialog.this.getBtnOK()) {
				// 确定按钮执行事件
				AccumulationFundAllUpdateDialog.this.doOKAction();
			}
		}
	}

	/**
	 * 表格渲染
	 * @throws Exception
	 */
	private void addComponents() throws Exception {
		JPanel panel = new JPanel(new BorderLayout());
		List<Object[]> dataList = new ArrayList<Object[]>();
		String[] columnNames = { "表", "成本归属公司", "员工编号", "姓名", "缴费基数", "个人部分", "公司部分", "备注" };
		for (int i = 0; i < selectedData.size(); i++) {
			Object[] data = selectedData.get(i);
			// 获取小标题编号和公司组合字段
			String str = String.valueOf(selectedData.get(i)[7]);
			int index = str.indexOf("-");
			int tableNumber = Integer.parseInt(str.substring(0, index));
			String orgName = str.substring(index + 1);
			Object[] rowData = { getTableName(tableNumber), orgName, data[1], data[2], data[3], data[4], data[5],
					data[6] };
			dataList.add(rowData);
		}

		Object[][] dataArray = new Object[dataList.size()][columnNames.length];
		for (int i = 0; i < dataList.size(); i++) {
			Object[] rowData = dataList.get(i);
			dataArray[i] = rowData;
		}

		DefaultTableModel model = new DefaultTableModel(dataArray, columnNames) {
			@Override
			public boolean isCellEditable(int row, int column) {
				return (column > 3);
			}
		};
		table = new JTable(model);
		// 禁用列拖动功能
		table.getTableHeader().setReorderingAllowed(false);
		// 设置高度
		table.setRowHeight(30);
		TableColumnModel columnModel = table.getColumnModel();
		// 遍历所有列，设置宽度为150像素
		for (int i = 0; i < columnModel.getColumnCount(); i++) {
			if (i >= 10 || i == 1) {
				table.getColumnModel().getColumn(i).setPreferredWidth(150);
			}
		}
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		panel.add(scrollPane, BorderLayout.CENTER);
		panel.add(scrollPane, BorderLayout.CENTER);
		getContentPane().add(panel);
	}

	private void doOKAction() {
		try {
			//判断单元格是否处于编辑状态，Y停止当前表格单元格的编辑状态
			if (table.isEditing()) {  
			    table.getCellEditor().stopCellEditing();  
			}
			// 获取修改后的数据
			for (int i = 0; i < table.getRowCount(); i++) {
				String table_name = ValueUtils.getString(table.getValueAt(i, 0));//表
				String table_org = ValueUtils.getString(table.getValueAt(i, 1));//公司
				String clerkCode = ValueUtils.getString(table.getValueAt(i, 2));//员工编号
				String clerkName = ValueUtils.getString(table.getValueAt(i, 3));//姓名
				//String basicssum = ValueUtils.getString(table.getValueAt(i, 4));//缴纳基数
				UFDouble basicssum = MathTool.nvl(ValueUtils.getUFDouble(table.getValueAt(i, 4))).setScale(2, UFDouble.ROUND_HALF_UP);
				//String staffsum = ValueUtils.getString(table.getValueAt(i, 5));//个人部分
				UFDouble staffsum = MathTool.nvl(ValueUtils.getUFDouble(table.getValueAt(i, 5))).setScale(2, UFDouble.ROUND_HALF_UP);
				//String orgsum = ValueUtils.getString(table.getValueAt(i, 6));//公司部分
				UFDouble orgsum = MathTool.nvl(ValueUtils.getUFDouble(table.getValueAt(i, 6))).setScale(2, UFDouble.ROUND_HALF_UP);

				String mark = ValueUtils.getString(table.getValueAt(i, 7));//备注
				String combinedField = table_name + table_org + clerkCode + clerkName;
				//第一次处理调新增，第二次处理调修改
				if(queryTable(orgCode, period, combinedField)) {
					StringBuilder insertSQL = new StringBuilder("INSERT INTO accumulation_fund VALUES (");
					//改为自己的报表名字,查询的时候需要根据这个做过滤！！！
					insertSQL.append("'").append("公积金分摊表").append("', ");
					insertSQL.append("'").append(orgCode).append("', ");
					insertSQL.append("'").append(period).append("', ");
					insertSQL.append("'").append(combinedField).append("', ");
					insertSQL.append(getString(table_org)).append(", ");
					insertSQL.append(getString(clerkCode)).append(", ");
					insertSQL.append(getString(clerkName)).append(", ");
					insertSQL.append(getString(basicssum)).append(", ");
					insertSQL.append(getString(staffsum)).append(", ");
					insertSQL.append(getString(orgsum)).append(", ");
					insertSQL.append(getString(mark)).append(", ");
					insertSQL.append("sysdate,");
					insertSQL.append("null)");
					siaMaintain.executeBaseDAO(insertSQL.toString());
					
				}else {
					StringBuilder updateSQL = new StringBuilder("UPDATE accumulation_fund");
					updateSQL.append(" SET basicssum = "+getString(basicssum)+",");
					updateSQL.append(" staffsum = "+getString(staffsum)+",");
					updateSQL.append(" orgsum = "+getString(orgsum)+",");
					updateSQL.append(" mark = "+getString(mark)+",");
					updateSQL.append(" ts = sysdate");
					updateSQL.append(" WHERE");
					updateSQL.append(" tablename = '公积金分摊表' and orgcode = '" + orgCode + "' and period = '" + period + "' and combined_field = '" + combinedField + "'");
					siaMaintain.executeBaseDAO(updateSQL.toString());
				}
			}
			//关闭弹框
			this.dispose();
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	/**
	 * 查询中间表是否存在数据
	 * @param orgCode 查询组织
	 * @param period 查询期间
	 * @param combinedField 小标题名字+小标题组织+员工号+姓名组合
	 * @return
	 * @throws Exception
	 */
	private Boolean queryTable(String orgCode, String period,String combinedField) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("select orgcode from accumulation_fund where");
		sql.append(" tablename = '公积金分摊表' and orgcode = '" + orgCode + "' and period = '" + period + "' and combined_field = '" + combinedField + "'");
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) == null) {
			return true;
		} else {
			return false;
		}

	}

	/**
	 * 取对应的小标题名字
	 * @param tableNumber 小标题编号
	 * @return
	 */
	private String getTableName(int tableNumber) {
		switch (tableNumber) {
		case 1:
			return "表一：由个人承担";
		case 2:
			return "表二：由外部公司承担";
		case 3:
			return "表三：由部门承担或全额公司承担";
		case 4:
			return "表四：个人部分已在集团内其他公司扣除";
		case 5:
			return "表五：月薪工资表中当月扣当月缴纳";
		case 6:
			return "表六：实际已缴当月工资个人部分未扣";
		case 7:
			return "表七：实际未缴当月工资个人部分已扣";
		default:
			return "表八：实际集团内其他公司已缴当月工资个人部分已扣";
		}
	}
	
	/**
	 * 将Object转换成适用sql拼接字符
	 * @param value
	 * @return
	 */
	private String getString(Object value) {
		if("".equals(value) || value == null) {
			return null;
		}
		return "'"+value+"'";
		
	}

}
