package com.gx.obe.management.composite;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.CellStyle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.gx.obe.ColorConstants;
import com.gx.obe.common.dialog.ImportFromExcelDialog;
import com.gx.obe.common.dialog.ImportFromExcelDialog.ImportListener;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.dialog.MessageViewDialog;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.util.MoneyUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.report.poi.Excel;
import com.gx.obe.report.poi.ExcelRow;
import com.gx.obe.report.poi.ExcelStyle;
import com.gx.obe.util.utils.BigDecimalUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.SupplierService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.editors.KTableCellEditorText;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;
import de.kupzog.ktable.renderers.CellEditContentRender;
import de.kupzog.ktable.renderers.CellEditorRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;

/**
 * @Description: 标书费管理
 * @author guoyr
 */
public class TenderFeeComposite extends Composite {
	
	private SupplierService supplierService = new SupplierService();
	private TenderProjectEntity tenderProjectEntity;
//	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	private EButton save_btn;
	private String priceUnit = Messages.Money_yuan;
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public TenderFeeComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		this.tenderProjectEntity = (TenderProjectEntity)parent.getData("tenderProjectEntity");
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setLayout(new GridLayout(1, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		ELink importTenderFeeBtn = new ELink(composite, SWT.NONE);
		importTenderFeeBtn.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
		importTenderFeeBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				importTenderFeeAction();
			}
		});
		importTenderFeeBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/download.png"));
		importTenderFeeBtn.setText("导入标书费");
		importTenderFeeBtn.setVisible(false);
		
		Composite composite_1 = new Composite(this, SWT.NONE);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_composite_1 = new GridLayout(1, false);
		gl_composite_1.marginHeight = 1;
		gl_composite_1.marginWidth = 1;
		composite_1.setLayout(gl_composite_1);
		composite_1.setBackground(SWTResourceManager.getColor(211, 211, 211));
		Composite parentComposite = new Composite(composite_1, SWT.NONE);
		parentComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		parentComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_parentComposite = new GridLayout(1, false);
		gl_parentComposite.verticalSpacing = 0;
		gl_parentComposite.horizontalSpacing = 0;
		gl_parentComposite.marginHeight = 0;
		gl_parentComposite.marginWidth = 0;
		parentComposite.setLayout(gl_parentComposite);
		
		resultKTable = new KTable(parentComposite, SWTX.AUTO_SCROLL |  SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY | SWTX.FILL_WITH_LASTCOL);
		resultKTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Composite composite_2 = new Composite(this, SWT.NONE);
		composite_2.setLayout(new GridLayout(1, false));
		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		save_btn = new EButton(composite_2, SWT.NONE);
		save_btn.setBackground(ColorConstants.SKIN_BG);
		save_btn.setForeground(ColorConstants.SKIN_FOREGROUND);
		save_btn.setActiveBorderColor(ColorConstants.SKIN_ACTIVE_BG);
		save_btn.setActiveBgColor(ColorConstants.SKIN_ACTIVE_BG);
		save_btn.setActiveForeground(ColorConstants.SKIN_ACTIVE_FOREGROUND);
		save_btn.setArcWidth(6);
		save_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				saveAction();
			}
		});
		save_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		GridData gd_savebutton_1 = new GridData(SWT.CENTER, SWT.FILL, true, true, 1, 1);
		gd_savebutton_1.heightHint = 35;
		gd_savebutton_1.widthHint = 200;
		save_btn.setLayoutData(gd_savebutton_1);
		save_btn.setText(Messages.Button_save);
		
		init();
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		// 获得项目规则
//		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
//		if(null == tenderProjectRuleEntity){
//			tenderProjectRuleEntity = new TenderProjectRuleEntity();
//		}
		// 获得项目下的投标人
		supplierList = supplierService.getSupplierList(tenderProjectEntity.getId());
		if(null == supplierList){
			supplierList = new ArrayList<Supplier>();
		}
		
		drawKTable();
	}
	
	/**
	 * @Description: 绘制表格
	 * @author guoyr 
	 */
	private void drawKTable(){
		commKTableModel = new CommonKtableCModel(resultKTable, 1, 0, supplierList.size(), 4);
		
		commKTableModel.setContentRowHeight(Constants.ROW_HIGHT);
		commKTableModel.setColumnWidth(0, 50);
		commKTableModel.setColumnMaxWidth(0, 50);
		commKTableModel.setColumnMinWidth(1, 200);
		commKTableModel.setColumnMinWidth(2, 200);
		resultKTable.setAutoComputerSurplusWidth(false);
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender(){
			public Object receiveContent(int row, int col) {
				if(row < commKTableModel.getFixedRowCount()){
					if(col == 0){
						return Messages.Num;
					}else if(col == 1){
						return MessageFormat.format(Messages.NameFormat, com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType()));
					}else if(col == 2){
						return "标书费("+priceUnit+")";
					}
				}else {
					Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
					if(col == 0){
						return row+"";
					}else if(col == 1){
						return supplier.getSupplierName();
					}else if(col == 2 && null != supplier.getTenderFee()){
						return MoneyUtils.getMoneyFormatByUnit(supplier.getTenderFee(), priceUnit);
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格渲染器
		CellRender cellRender = new CellRender(){
			public Object receiveCellRender(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					return new FixedCellRenderer();
				}else{
					if(col == 2){
						return new TextCellRenderer();
					}else {
						return null;
					}
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		// 设置单元格编辑器
        final KTableCellEditorText text = new KTableCellEditorText();
		text.setSingleClickEdit(true);
		CellEditorRender cellEditorRender = new CellEditorRender(){
			public Object receiveCellEditor(int row, int col) {
				if(row >= commKTableModel.getFixedRowCount() && col == 2){
					return text;
				}
				return null;
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		
		// 编辑单元格内容
		CellEditContentRender editContentRender = new CellEditContentRender(){
			public void receiveContent(int row, int col, Object content) {
				if(row >= commKTableModel.getFixedRowCount() && col == 2){
					Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
					BigDecimal result = MoneyUtils.getMoneyFromText((String)content, priceUnit);
					supplier.setTenderFee(result);
					commKTableModel.setChanged(true);
				}
			}
		};
		commKTableModel.setCellEditContentRender(editContentRender);
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender(){
			public int receiveCellAlignment(int row, int col) {
				if(row < commKTableModel.getFixedRowCount()){
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				}else{
					if(col == 0){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					}else if(col == 1){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}else{
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_RIGHT;
					}
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		resultKTable.setModel(commKTableModel);
	}
	
	/**
	 * @Description: 保存
	 */
	private void saveAction(){
		resultKTable.closeCellEditor();
		if(!save_btn.getEnabled()){
			return ;
		}
		if(null != supplierList && supplierList.size() > 0){
			if(supplierService.batchSaveOrUpdate(supplierList, new String[]{"tenderFee"}) > 0){
				MessageDialog.openShortMessage(Messages.Tips_saveSuccess);
				commKTableModel.setChanged(false);
			}else {
				MessageDialog.openError(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveFail);
			}
		}
	}
	
	/**
	 * @Description: 导入标书费
	 * @author guoyr
	 */
	private void importTenderFeeAction(){
		Excel excel = new Excel();
		excel.addRow().setHeight(30).addCell().setValue("标书费").setHead(true);
		ExcelRow row = excel.addRow();
		row.setHeight(25);
		row.addCell().setValue("投标人称").setProperty("supplierName").setWidth(300).setHead(true);
		row.addCell().setValue("标书费("+priceUnit+")").setProperty("tenderFee").setWidth(200).setHead(true);
		final Map<String, Supplier> supplierMap = setExcelRowContent(excel);
		final ImportFromExcelDialog dialog = new ImportFromExcelDialog(getShell(), excel, new ImportListener(){
			public void onImport(List<Map<String, Object>> excelDataList) {
				MessageViewDialog messageDialog = new MessageViewDialog(getShell(), -1);
				new ImportTenderFeeThread(excelDataList, supplierMap, messageDialog.getCallBack()).start();
				messageDialog.setTitle("导入标书费");
				messageDialog.open();
				
				resultKTable.redraw();
			}
		});
		dialog.setTitle("导入标书费");
		dialog.open();
	}
	
	/**
	 * @Description: 设置Excel行内容
	 * @author guoyr
	 * @param excel
	 * @return
	 */
	private Map<String, Supplier> setExcelRowContent(Excel excel){
		Map<String, Supplier> supplierMap = new HashMap<String, Supplier>();
		if(null != supplierList && supplierList.size() > 0){
			// 遍历投标人集合
			for(Supplier supplier : supplierList){
				String supplierName = ObjectUtils.getObjString(supplier.getSupplierName());
				// 创建Excel行
				ExcelRow supplierRow = excel.addRow();
				// 设置行高
				supplierRow.setHeight(25);
				// 投标人名称列
				supplierRow.addCell().setValue(supplierName).setProperty("supplierName").setWidth(300).setHead(true).setCellStyle(ExcelStyle.getInstents(ExcelStyle.R_HEAD).setBorder(CellStyle.BORDER_THIN));
				// 标书费列
				String tenderFee = null != supplier.getTenderFee() ? MoneyUtils.getMoneyFormatByUnit(supplier.getTenderFee(), priceUnit) : "";
				supplierRow.addCell().setValue(tenderFee).setProperty("tenderFee").setWidth(200).setHead(false);
				supplierMap.put(supplierName, supplier);
			}
		}
		return supplierMap;
	}
	
	/**
	 * @Description: 导入标书费线程
	 * @author guoyr
	 */
	class ImportTenderFeeThread implements Runnable{
		
		private Thread thread;
		private List<Map<String, Object>> excelDataList;
		private Map<String, Supplier> supplierMap;
		private CallBack callBack;
		
		public ImportTenderFeeThread(List<Map<String, Object>> excelDataList, Map<String, Supplier> supplierMap, CallBack callBack){
			this.excelDataList = excelDataList;
			this.supplierMap = supplierMap;
			this.callBack = callBack;
		}
		
		public void start(){
			thread = new Thread(this);
			thread.setName("导入标书费线程");
			thread.start();
		}
		
		public void stop(){
			thread = null;
		}
		
		public void run() {
			String SUPPLIER_NAME = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType());
			if(null != excelDataList && excelDataList.size() > 0){
				callBackMsg("获得"+excelDataList.size()+Messages.SupplierCouns+SUPPLIER_NAME+"的标书费！");
				List<Supplier> finalSupplierList = new ArrayList<Supplier>();
				for(Map<String, Object> excelDataMap : excelDataList){
					String supplierName = ObjectUtils.getObjString(excelDataMap.get("supplierName"));
					Supplier supplier = null != supplierMap ? supplierMap.get(supplierName) : null;
					if(null != supplier){
						callBackMsg("√读取【"+supplierName+"】的标书费成功！");
						BigDecimal tenderFee = ObjectUtils.getObjBigDecimal(excelDataMap.get("tenderFee"));
						if(null != tenderFee && StringUtils.equals(CommonEnum.WAN_YUAN, priceUnit)){
							tenderFee = BigDecimalUtils.mul(tenderFee, new BigDecimal(10000));
						}
						supplier.setTenderFee(tenderFee);
						finalSupplierList.add(supplier);
					}else {
						callBackMsg("×【"+supplierName+"】Excel数据转换实体对象失败！");
					}
				}
				if(null != finalSupplierList && finalSupplierList.size() > 0){
					// 批量更新数据时，第二个参数是指定忽略字段，第三个是指定更新字段。
					if(supplierService.batchUpdateProperty(finalSupplierList, new String[]{"tenderFee"}) > 0){
						callBackMsg("√导入"+finalSupplierList.size()+Messages.SupplierCouns+SUPPLIER_NAME+"的标书费成功！");
					}else {
						callBackMsg("×导入"+finalSupplierList.size()+Messages.SupplierCouns+SUPPLIER_NAME+"的标书费失败！");
					}
				}
			}else {
				callBackMsg("×未检测到有效"+SUPPLIER_NAME+"的标书费！");
			}
			callBackMsg("导入标书费结束！");
			if(null != callBack){
				callBack.after();
			}
		}
		
		private void callBackMsg(String msg){
			if(null != callBack){
				callBack.callBackString(msg);
			}
		}
	}
	
	@Override
	protected void checkSubclass() {
	}
}
