package com.gx.obe.management.composite;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.graphics.Image;
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.business.enumeration.SupplierEnum;
import com.gx.obe.common.dialog.ImportBidPriceFromExcelDialog;
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.I18N;
import com.gx.obe.components.core.I18NEnum;
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.ExcelCell;
import com.gx.obe.report.poi.ExcelRow;
import com.gx.obe.report.poi.ExcelStyle;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
import com.gx.obe.web.entity.price.BidPrice;
import com.gx.obe.web.entity.price.BidPriceResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.SupplierOpeningResultService;
import com.gx.utils.NowTimeUtils;
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.CellImageRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;

/**
 * @Description: 投标总报价管理
 * @author guoyr
 */
public class BidPriceTableComposite extends Composite implements IBidPriceResultTable{
	
//	private SupplierService supplierService = new SupplierService();
	private SupplierOpeningResultService supplierOpeningResultService;
//	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity projectRule;
	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private KTable bidPriceTable;
	private CommonKtableCModel commKTableModel;
	private String SUPPLIER_NAME;
	private boolean editable;
	private TenderProjectEntity tenderProject;
//	private List<BidPrice> bidPriceList;
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public BidPriceTableComposite(Composite parent, int style) {
		super(parent, style);
		setBackground(ColorConstants.BORDER_LINE_COLOR);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 1;
		gridLayout.marginWidth = 1;
		setLayout(gridLayout);
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setBackgroundMode(SWT.INHERIT_FORCE);
		composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 0;
		composite.setLayout(gl_composite);
		  
		bidPriceTable = new KTable(composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY | SWTX.FILL_WITH_LASTCOL);
		bidPriceTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		supplierOpeningResultService = new SupplierOpeningResultService();
	}
	
	/** 
	 * @Description: 刷新投标报价
	 * @author guoyr
	 * @param tenderProjectEntity
	 * @param tenderProjectRuleEntity
	 * @param supplierList 
	 */
	public void refreshBidPriceResult(TenderProjectEntity tenderProject, TenderProjectRuleEntity projectRule, List<Supplier> supplierList, List<BidPrice> bidPriceList, boolean editable){
		this.tenderProject = tenderProject;
		this.projectRule = null == projectRule ? new TenderProjectRuleEntity() : projectRule;
		this.supplierList = supplierList;
		this.editable = editable;
//		this.bidPriceList = bidPriceList;
		SUPPLIER_NAME = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProject.getTenderType());
		
		refreshBidPriceResultTable();
	}
	
	private void refreshBidPriceResultTable() {
		commKTableModel = new CommonKtableCModel(bidPriceTable, 1, 0, supplierList.size(), 4);
		bidPriceTable.setAutoComputerSurplusWidth(false);
		commKTableModel.setContentRowHeight(Constants.ROW_HIGHT);
		commKTableModel.setColumnWidth(0, 50);
		commKTableModel.setColumnMinWidth(1, 250);
		commKTableModel.setColumnWidth(2, 200);
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender(){
			public Object receiveContent(int row, int col) {
				int currRow = row - commKTableModel.getFixedRowCount();
				if(row < commKTableModel.getFixedRowCount()){
					if(col == 0){
						return Messages.Num ;
					}else if(col == 1){
						return I18N.getString(I18NEnum.SUPPLIERNAME, tenderProject.getTenderType());
					}else if(col == 2){
						return Messages.BidPrice;
					}
				}else {
					if(col == 0){
						return row +"";
					}else{
						Supplier supplier = supplierList.get(currRow);
						if(col == 1){
							return supplier.getSupplierName();
						}else if(col == 2 && null != supplier.getSupplierOpeningResult()){
							SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
							if(null == supplierOpeningResult.getBidPrice()){
								supplierOpeningResult.setBidPrice(supplierOpeningResult.getEvaluationPrice());
							}
							if(null != supplierOpeningResult.getBidPrice()){
								return supplierOpeningResult.getBidPriceWithUnit(projectRule.getEvalPriceUnit());
							}
						}
					}
				}
				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();
				}
				return null;
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		// 设置单元格编辑器
		if(editable){
			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);
		}
		
		final Image editImage = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/edit.png");
		// 设置单元格图片
		CellImageRender cellImageRender = new CellImageRender() {
			public Image receiveCellImage(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					return null;
				}else if(col == 2){
					return editImage;
				}
				return null;
			}
		};
		commKTableModel.setCellImageRender(cellImageRender);
		
		
		// 编辑单元格内容
		CellEditContentRender editContentRender = new CellEditContentRender(){
			public void receiveContent(int row, int col, Object content) {
				if(row >= commKTableModel.getFixedRowCount() && col == 2){
					
					String priceUnitCN = null;
					Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
					SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
					if (null != supplierOpeningResult) {
						priceUnitCN  = supplierOpeningResult.getPriceUnit();
					}
					if (null == priceUnitCN) {
						priceUnitCN = projectRule.getEvalPriceUnit();
					}
					
					BigDecimal bidPriceMoney = MoneyUtils.getMoneyFromText(MoneyUtils.extractDigits(content.toString()), priceUnitCN);
					
					supplierOpeningResult.setBidPrice(bidPriceMoney);
					supplierOpeningResult.setEvaluationPrice(bidPriceMoney);
					
					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);
		
		bidPriceTable.setModel(commKTableModel);
	}
	
	/** 
	 * @Description: 保存
	 * @author guoyr 
	 */
	public boolean saveBidPriceResult(){
		bidPriceTable.closeCellEditor();
		if(null != supplierList && supplierList.size() > 0){
			List<SupplierOpeningResult> supplierOpeningResultList = new ArrayList<SupplierOpeningResult>();
			List<BidPriceResult> bidPriceResultList = new ArrayList<BidPriceResult>();
			Date nowDate = NowTimeUtils.getNowDate();
			for(Supplier supplier : supplierList){
				SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
				supplierOpeningResult.setEvaluationPrice(supplierOpeningResult.getBidPrice());
				BidPriceResult bidPriceResult = null;
				if(null != supplierOpeningResult.getBidPrice()){
					supplierOpeningResult.setBidOpeningStatus(SupplierEnum.OPENBID_SUCCESS);
					supplierOpeningResult.setPriceBidStatus(SupplierEnum.OPENBID_SUCCESS);
					supplierOpeningResult.setBusinessBidStatus(SupplierEnum.OPENBID_SUCCESS);
					supplierOpeningResult.setTechnologyBidStatus(SupplierEnum.OPENBID_SUCCESS);
					if(null == supplierOpeningResult.getRevokeStatus() || !supplierOpeningResult.getRevokeStatus().equals(SupplierEnum.REVOKE_YES)){
						supplierOpeningResult.setRevokeStatus(SupplierEnum.REVOKE_NO);
					}
					if(null == supplierOpeningResult.getBidOpeningTime()){
						supplierOpeningResult.setBidOpeningTime(nowDate);
					}
//					if(bidPriceList.size() > 0 ){
//						bidPriceResult = bidPriceResultService.getSupplierBidPriceResult(bidPriceList.get(0).getId(),supplier.getId());
//					}else{
//						bidPriceResult = bidPriceResultService.getSupplierBidPriceResult(null,supplier.getId());
//					}
//					if(null != bidPriceResult){
//						bidPriceResult.setBidPrice(supplierOpeningResult.getBidPrice());
//						bidPriceResultService.updateAssignProperty(bidPriceResult, new String[]{"bidPrice"});
//					}else{
//						bidPriceResult = new BidPriceResult();
//						bidPriceResult.setBidPrice(supplierOpeningResult.getBidPrice());
//						bidPriceResult.setId(UuidUtils.g);
//						bidPriceResult.setTenderId(supplier.getTenderId());
//						bidPriceResult.setEvaluationPrice(supplierOpeningResult.getBidPrice());
//						bidPriceResultService.insert(bidPriceResult);
//					}
				}
				supplierOpeningResultList.add(supplierOpeningResult);
				bidPriceResultList.add(bidPriceResult);
			}
			if(supplierOpeningResultService.batchSaveOrUpdate(supplierOpeningResultList, new String[]{"id","bidPrice", "evaluationPrice", "bidOpeningStatus", "priceBidStatus", "businessBidStatus", "technologyBidStatus", "bidOpeningTime", "revokeStatus"})>0){
				commKTableModel.setChanged(false);
				return true;
			}
		}
		return false;
	}
	
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	
	/** 
	 * @Description: 导入投标报价
	 * @author guoyr 
	 */
	public void importBidPrice() {
		Excel excel = new Excel();
		ExcelStyle cellStyle = ExcelStyle.getInstents(ExcelStyle.DEFAULT).setFontHeightInPoints(12).setBoldweight(Font.BOLDWEIGHT_BOLD).setBorder(CellStyle.BORDER_THIN);
//		cellStyle.setFillForegroundColor((short) 13);// 设置背景色   
//		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  

		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框   
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框   
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框   
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框  

		

		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中  
		ExcelCell cell = excel.addRow().setHeight(30).addCell();
		
		cell.setValue(SUPPLIER_NAME + Messages.BidPrice).setHead(true);
		cell.setCellStyle(cellStyle);
		ExcelRow row = excel.addRow();
		row.setHeight(25);
		row.addCell().setValue("名称(必填)").setProperty("supplierName").setWidth(300).setHead(true);
		row.addCell().setValue(Messages.BidPrice+ "（" + projectRule.getEvalPriceUnit() + "）").setProperty("bidPrice").setWidth(150).setHead(true);
//		ExcelRow contentRow = excel.addRow();
//		contentRow.setHeight(20);
//		contentRow.addCell().setProperty("supplierName").setHead(false);
//		contentRow.addCell().setProperty("bidPrice").setHead(false);
		for(int i = 0; i < supplierList.size(); i++){
			ExcelRow supplierRow = excel.addRow();
			supplierRow.setHeight(20);
			supplierRow.addCell().setValue(supplierList.get(i).getSupplierName()).setProperty("supplierName").setWidth(300).setHead(true);
			BigDecimal bidPriceString = null;
			if(null != supplierList.get(i) && null != supplierList.get(i).getSupplierOpeningResult() && null != supplierList.get(i).getSupplierOpeningResult().getBidPrice()){
				bidPriceString = supplierList.get(i).getSupplierOpeningResult().getBidPrice();
			}
			supplierRow.addCell().setValue(MoneyUtils.getMoneyFormatByUnit(bidPriceString, null != projectRule ? projectRule.getEvalPriceUnit() : "")).setProperty("bidPrice").setWidth(150).setHead(true);

		}
		ImportBidPriceFromExcelDialog dialog = new ImportBidPriceFromExcelDialog(getShell(), excel, new ImportBidPriceFromExcelDialog.ImportListener() {
			
			public void onImport(List<Map<String, Object>> excelDataList) {
				
				MessageViewDialog messageDialog = new MessageViewDialog(getShell(), -1);
				new ImportSupplierBidPriceThread(excelDataList, messageDialog.getCallBack()).start();
				messageDialog.setTitle("导入"+SUPPLIER_NAME);
				messageDialog.open();
			}
		});
//		dialog.setTitle("导入"+SUPPLIER_NAME);
		dialog.open();
	}
	/** 
	 * @Description: 导入本地Excel文件线程
	 * @author guoyr 
	 */
	class ImportSupplierBidPriceThread implements Runnable{
		
		private Thread thread;
		private List<Map<String, Object>> excelDataList;
		private CallBack callBack;
		
		public ImportSupplierBidPriceThread(List<Map<String, Object>> excelDataList, CallBack callBack){
			this.excelDataList = excelDataList;
			this.callBack = callBack;
		}
		
		public void start(){
			thread = new Thread(this);
			thread.setName("导入本地Excel文件线程");
			thread.start();
		}
		
		public void stop(){
			thread = null;
		}
		
		public void run() {
			if(null != excelDataList && excelDataList.size() > 0){
				callBackMsg("获得"+excelDataList.size()+"家要导入的"+SUPPLIER_NAME+"报价信息！");
				
				//set作为容器存贮当前已经存在的供应商名称
//				Set<String> supplierNameSet = new HashSet<String>();
				Map<String,Integer> supplierNameMap = new HashMap<String,Integer>();
				int index = 0;
				for(Supplier supplier : supplierList){
//					supplierNameSet.add(supplier.getSupplierName().trim());
					supplierNameMap.put(supplier.getSupplierName().trim(), index++);
				}
				List<SupplierOpeningResult> resultList = new ArrayList<SupplierOpeningResult>();
				// 获得投标人的最大序号
				for(Map<String, Object> map : excelDataList){
					// 投标人名称
					String supplierName = ObjectUtils.getObjString(map.get("supplierName"));
					String bidPrice =  ObjectUtils.getObjString(map.get("bidPrice"));
					
					if(null != supplierNameMap.get(supplierName.trim())){
						SupplierOpeningResult supplierOpeningResult = supplierList.get(supplierNameMap.get(supplierName.trim())).getSupplierOpeningResult();
						if(null != bidPrice && !"".equals(bidPrice)){
							try {
								BigDecimal result = MoneyUtils.getMoneyFromText(bidPrice, projectRule.getEvalPriceUnit());
								supplierOpeningResult.setBidPrice(result);
//								supplierOpeningResult.setBidOpeningStatus(SupplierEnum.OPENBID_SUCCESS);
//								supplierOpeningResult.setBidOpeningStatus(SupplierEnum.OPENBID_SUCCESS);
//								supplierOpeningResult.setPriceBidStatus(SupplierEnum.OPENBID_SUCCESS);
//								supplierOpeningResult.setBusinessBidStatus(SupplierEnum.OPENBID_SUCCESS);
//								supplierOpeningResult.setTechnologyBidStatus(SupplierEnum.OPENBID_SUCCESS);
								if(null == supplierOpeningResult.getRevokeStatus() || !supplierOpeningResult.getRevokeStatus().equals(SupplierEnum.REVOKE_YES)){
									supplierOpeningResult.setRevokeStatus(SupplierEnum.REVOKE_NO);
								}
								if(null == supplierOpeningResult.getBidOpeningTime()){
									supplierOpeningResult.setBidOpeningTime(NowTimeUtils.getNowDate());
								}
							} catch (Exception e) {
								supplierOpeningResult.setBidPrice(BigDecimal.ZERO);
							}
						}
						resultList.add(supplierOpeningResult);
					}
				}	
				if(resultList.size() <= 0){
					callBackMsg("×未检测到有效的"+SUPPLIER_NAME+"报价！");
					return ;
				}else{
					int reflence = supplierOpeningResultService.batchSaveOrUpdate(resultList, new String[]{"id","bidPrice", "evaluationPrice", /**"bidOpeningStatus", "bidOpeningTime",**/ "revokeStatus"});
					callBackMsg("\r\n√此次成功导入"+ reflence +Messages.SupplierCouns+SUPPLIER_NAME+"报价！");
				}
				callBackMsg("导入"+SUPPLIER_NAME+"报价结束！");
				if(null != callBack){
					callBack.after();
				}
			}
		}
		
		private void callBackMsg(String msg){
			if(null != callBack){
				callBack.callBackString(msg);
			}
		}
	}
}
