/**
 * output package name
 */
package com.kingdee.eas.custom.gggl.client;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;

import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.ctrl.kdf.table.IRow;
import com.kingdee.bos.ctrl.kdf.table.KDTMergeManager;
import com.kingdee.bos.ctrl.kdf.table.KDTable;
import com.kingdee.bos.ctrl.kdf.table.event.KDTDataRequestEvent;
import com.kingdee.bos.ctrl.swing.event.DataChangeEvent;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.ui.face.CoreUIObject;
import com.kingdee.eas.basedata.org.CompanyOrgUnitInfo;
import com.kingdee.eas.common.client.SysContext;
import com.kingdee.eas.custom.gggl.AdvertFactory;
import com.kingdee.eas.custom.gggl.AdvertInfo;
import com.kingdee.eas.custom.gggl.DTypeEnum;
import com.kingdee.eas.custom.gggl.SaleContractE1Collection;
import com.kingdee.eas.custom.gggl.SaleContractE1Factory;
import com.kingdee.eas.fi.gr.rptintegration.util.synchronize.download.BookDataSynOperate.operateType;
import com.kingdee.eas.fm.common.DateHelper;
import com.kingdee.eas.framework.ICoreBase;
import com.kingdee.eas.xr.XRSQLFacadeFactory;
import com.kingdee.jdbc.rowset.IRowSet;

/**
 * output class name
 */
public class AdvertManUI extends AbstractAdvertManUI
{
    private static final Logger logger = CoreUIObject.getLogger(AdvertManUI.class);
    
    /**
     * output class constructor
     */
    public AdvertManUI() throws Exception
    {
        super();
    }
	public void onLoad() throws Exception {
		super.onLoad();
		actionAddNew.setVisible(false);
		actionRemove.setVisible(false);
		actionEdit.setVisible(false);
		actionView.setVisible(false);
		actionPrint.setVisible(false);
		actionPrintPreview.setVisible(false);
		actionQuery.setVisible(false);
		Date date = new Date();
    	int year = Integer.parseInt(DateHelper.DateToString(date).substring(0,4));
    	SpinnerNumberModel startYearLevelModel = new SpinnerNumberModel(2000,2000,2999,1);
    	kdsYear.setModel(startYearLevelModel);
    	kdsYear.setValue(new Integer(year));
//    	kDTable1.getDataRequestManager().setDataRequestMode(KDTDataRequestManager.VIRTUAL_MODE_PAGE);
    	kDTable1.getStyleAttributes().setLocked(true);
    	 setPreferredSize(getMaximumSize());
    	
    	EntityViewInfo view = new EntityViewInfo();
		FilterInfo filInfo = new FilterInfo();
		filInfo.getFilterItems().add(new FilterItemInfo("treeid.id","JQcAAAAAgOrsyXfw" ,CompareType.EQUALS));//这个id是广告位管理里面 对应中庭
		view.setFilter(filInfo);
		kDBizPromptBox1.setEntityViewInfo(view);
		
		this.setUITitle("中庭排期表管理");
		
		
		
    	if(getUIContext().get("ggname")!=null){
    		String ggname=getUIContext().get("ggname").toString();
    		AdvertInfo info11 =  AdvertFactory.getRemoteInstance().getAdvertInfo("where  name='"+ggname+"' ");
    		kDBizPromptBox1.setValue(info11);
    	}
		
		
	}
	
	@Override
	public void loadFields() {
		// TODO Auto-generated method stub
		super.loadFields();
	}
	@Override
	public void onShow() throws Exception {

		super.onShow();
	}
	protected IQueryExecutor getQueryExecutor(IMetaDataPK arg0,EntityViewInfo arg1) {
		CompanyOrgUnitInfo info= SysContext.getSysContext().getCurrentFIUnit();
		EntityViewInfo view = (EntityViewInfo)arg1.clone();
		FilterInfo filInfo = new FilterInfo();
		filInfo.getFilterItems().add(new FilterItemInfo("djType",DTypeEnum.GG_VALUE));
		if(!info.getNumber().toString().equals("HY")){
			filInfo.getFilterItems().add(new FilterItemInfo("company.number",info.getNumber()));
			}
		view.setFilter(filInfo);
		return super.getQueryExecutor(arg0, view);
	}
	@Override
	protected void afterTableFillData(KDTDataRequestEvent e) {
		super.afterTableFillData(e);
//		showTypelist();
	}
	
	//通过单据类型过滤列表界面
	private void showTypelist() {
		//		super.actionRefresh_actionPerformed(e);
		for(int i=0;i<this.tblMain.getRowCount();i++){
			IRow row = this.tblMain.getRow(i);
			if(row.getCell("djType").getValue()!=null){
				String djType = row.getCell("djType").getValue().toString();
				if(djType.equals(DTypeEnum.gg.toString())){
					row.getStyleAttributes().setHided(false);
				}else{
					row.getStyleAttributes().setHided(true);
				}
			}
		}


	}
	
	
	
	
	protected void kdsYear_stateChanged(ChangeEvent e) throws Exception {
		super.kdsYear_stateChanged(e);
		kDTable1.removeRows();
		int year=Integer.parseInt(kdsYear.getValue().toString());
		getAddRow(year);
	}
	protected void kDBizPromptBox1_dataChanged(DataChangeEvent e)throws Exception {
		super.kDBizPromptBox1_dataChanged(e);
		kDTable1.removeRows();
		int year=Integer.parseInt(kdsYear.getValue().toString());
		getAddRow(year);
		
	}
	
	
    /**
     * output 根据广告位新增
     */
    public void getAddRow(int year) throws BOSException, SQLException
    {
    	
    	StringBuffer sql=new StringBuffer();
		sql.append(" SELECT  a.fid id ,a.fnumber numbers,a.fname_l2 names FROM CT_GGL_Advert a  ");
		sql.append(" left join  T_GGL_AdvertTREE tree ON a.FTREEID=tree.fid   ");
		sql.append(" where 1=1 and tree.fid=  'JQcAAAAAgOrsyXfw' "); //中庭
		
         if(kDBizPromptBox1.getValue()!=null){
        	AdvertInfo info =  (AdvertInfo) kDBizPromptBox1.getValue(); 
           sql.append(" and  a.fid='"+info.getId()+"'  ");
		}
         sql.append(" order by a.fnumber ");
		
		IRowSet rowset=XRSQLFacadeFactory.getRemoteInstance().executeQuery(sql.toString(), null);
		while(rowset.next()){
			String id =rowset.getString("id");
			String numbers =rowset.getString("numbers");
			String names =rowset.getString("names");
			getH12( kDTable1,  id, numbers, names,year);
		}
	    mergeThemeRow(kDTable1, "id", 0);
	    mergeThemeRow(kDTable1, "id", 1);
	    mergeThemeRow(kDTable1, "id", 2);
	    mergeThemeRow(kDTable1, "id", 3);
		
    }
    
	
    /**
     * 赋值及根据年月给单元格填充值
     */
    public void getH12(KDTable kdtable,String  id,String number,String name,int year)
    {
    	 DateFormat FORMAT_DAY = new SimpleDateFormat("yyyy-MM-dd");
    	 Map dateMap =  new HashMap();
    	SaleContractE1Collection accol = null;
    	try {
    		accol = SaleContractE1Factory.getRemoteInstance().getSaleContractE1Collection(
    				"select zlStartDate,zlEndDate,ggw.id,ggw.name from where ggw = '"+ id+"' and ( parent.status != '0' and parent.status != '1' and parent.status != '3'  ) ");//
    		for (int i = 0; i < accol.size(); i++) {
    			dateMap =  getBetweenDatesMap(accol.get(i).getZlStartDate(), accol.get(i).getZlEndDate());
    		}

    	} catch (BOSException e) {
			e.printStackTrace();
		}
    	
    	for(int i=1;i<=12;i++){//12个月
    		IRow row=kdtable.addRow();
    		row.getCell("id").setValue(id);
    		row.getCell("number").setValue(number);
    		row.getCell("name").setValue(name);
    		row.getCell("month").setValue(getMonth(i));
    		row.getCell("months").setValue(i);
    		
    		int monthdays= getDaysByYearMonth(year,i);//月份天数
    		for(int j=1;j<=monthdays;j++){
    			if(dateMap.get(year+"-"+i+"-"+j)!=null){
    				row.getCell(""+j+"").getStyleAttributes().setBackground(Color.green);	
    			}
    			row.getCell(""+j+"").setValue(j);//列名和值命名一致
    		}
    	}
    }
    public static String getMonth(int j) {
    	String month="";
    	if(j==1){
    		month="一";
		}else if(j==2){
			month="二";
		}
        else if(j==3){
        	month="三";
		}
         else if(j==4){
        	month="四";
		}
         else if(j==5){
        		month="五";
				
			}
         else if(j==6){
        		month="六";
				
			}
         else if(j==7){
        		month="七";
			}
         else if(j==8){
        		month="八";
			}
         else if(j==9){
        		month="九";
			}
         else if(j==10){
        		month="十";
			}
         else if(j==11){
        		month="十一";
			}
         else if(j==12){
        		month="十二";
			}
    	
    	return month;
    }
    
    /**
     * 获取两个日期之间的日期
     * @param start 开始日期
     * @param end 结束日期
     * @return 日期集合
     */
    private List<Date> getBetweenDates(Date start, Date end) {
        List<Date> result = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }
    
    /**
     * 获取两个日期之间的日期
     * @param start 开始日期
     * @param end 结束日期
     * @return 日期集合
     */
    private Map getBetweenDatesMap(Date start, Date end) {
    	DateFormat FORMAT_DAY = new SimpleDateFormat("yyyy-MM-dd");
    	Map DateMap = new HashMap();
    	
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
        	DateMap.put(tempStart.get(Calendar.YEAR)+"-"+(tempStart.get(Calendar.MONTH)+1)+"-"+tempStart.get(Calendar.DATE) , tempStart);
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
            DateMap.put(tempStart.get(Calendar.YEAR)+"-"+(tempStart.get(Calendar.MONTH)+1)+"-"+tempStart.get(Calendar.DATE) , tempStart);
        }
        return DateMap;
    }
    
    /**
     * 根据年 月 获取对应的月份 天数
     */
    public static int getDaysByYearMonth(int year, int month) {
       Calendar a = Calendar.getInstance();
       a.set(Calendar.YEAR, year);
       a.set(Calendar.MONTH, month - 1);
       a.set(Calendar.DATE, 1);
       a.roll(Calendar.DATE, -1);
       int maxDate = a.get(Calendar.DATE);
       return maxDate;
     }
    

	  /**
	 * 融合主题信息
	 * */
	private void mergeThemeRow(KDTable table,String columnName,int colIndex){
		  String theme = "";
	        String lastTheme = "";
	        KDTMergeManager mm = table.getMergeManager();
	        int rowIndx = 0;
	        int endIndx = 0;
	        for(int i=0 ;i<table.getRowCount();i++){
	        	endIndx = i;
	        	theme = (String)table.getRow(i).getCell(columnName).getValue(); //当前主题
	        	if(i>0){
	        		lastTheme = (String)table.getRow(i-1).getCell(columnName).getValue(); //上一主题
	            	if(theme!=null&&!theme.equals(lastTheme)){ // 获取当前主题 与 上一主题 不相同，所在的行号
	            		mm.mergeBlock(rowIndx, colIndex,endIndx-1, colIndex); // 将最后相同的主题融合
	            		rowIndx = endIndx;
	            	}
	        	}
	        }
	        mm.mergeBlock(rowIndx, colIndex,endIndx, colIndex); // 将最后相同的主题融合
	}
    /**
     * output storeFields method
     */
    public void storeFields()
    {
        super.storeFields();
    }

    /**
     * output tblMain_tableClicked method
     */
    protected void tblMain_tableClicked(com.kingdee.bos.ctrl.kdf.table.event.KDTMouseEvent e) throws Exception
    {
//        super.tblMain_tableClicked(e);
    }

    /**
     * output menuItemImportData_actionPerformed method
     */
    protected void menuItemImportData_actionPerformed(java.awt.event.ActionEvent e) throws Exception
    {
        super.menuItemImportData_actionPerformed(e);
    }

    /**
     * output actionPageSetup_actionPerformed
     */
    public void actionPageSetup_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPageSetup_actionPerformed(e);
    }

    /**
     * output actionExitCurrent_actionPerformed
     */
    public void actionExitCurrent_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExitCurrent_actionPerformed(e);
    }

    /**
     * output actionHelp_actionPerformed
     */
    public void actionHelp_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionHelp_actionPerformed(e);
    }

    /**
     * output actionAbout_actionPerformed
     */
    public void actionAbout_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionAbout_actionPerformed(e);
    }

    /**
     * output actionOnLoad_actionPerformed
     */
    public void actionOnLoad_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionOnLoad_actionPerformed(e);
    }

    /**
     * output actionSendMessage_actionPerformed
     */
    public void actionSendMessage_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionSendMessage_actionPerformed(e);
    }

    /**
     * output actionCalculator_actionPerformed
     */
    public void actionCalculator_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionCalculator_actionPerformed(e);
    }

    /**
     * output actionExport_actionPerformed
     */
    public void actionExport_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExport_actionPerformed(e);
    }

    /**
     * output actionExportSelected_actionPerformed
     */
    public void actionExportSelected_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExportSelected_actionPerformed(e);
    }

    /**
     * output actionRegProduct_actionPerformed
     */
    public void actionRegProduct_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionRegProduct_actionPerformed(e);
    }

    /**
     * output actionPersonalSite_actionPerformed
     */
    public void actionPersonalSite_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPersonalSite_actionPerformed(e);
    }

    /**
     * output actionProcductVal_actionPerformed
     */
    public void actionProcductVal_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionProcductVal_actionPerformed(e);
    }

    /**
     * output actionExportSave_actionPerformed
     */
    public void actionExportSave_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExportSave_actionPerformed(e);
    }

    /**
     * output actionExportSelectedSave_actionPerformed
     */
    public void actionExportSelectedSave_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExportSelectedSave_actionPerformed(e);
    }

    /**
     * output actionKnowStore_actionPerformed
     */
    public void actionKnowStore_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionKnowStore_actionPerformed(e);
    }

    /**
     * output actionAnswer_actionPerformed
     */
    public void actionAnswer_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionAnswer_actionPerformed(e);
    }

    /**
     * output actionRemoteAssist_actionPerformed
     */
    public void actionRemoteAssist_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionRemoteAssist_actionPerformed(e);
    }

    /**
     * output actionPopupCopy_actionPerformed
     */
    public void actionPopupCopy_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPopupCopy_actionPerformed(e);
    }

    /**
     * output actionHTMLForMail_actionPerformed
     */
    public void actionHTMLForMail_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionHTMLForMail_actionPerformed(e);
    }

    /**
     * output actionExcelForMail_actionPerformed
     */
    public void actionExcelForMail_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExcelForMail_actionPerformed(e);
    }

    /**
     * output actionHTMLForRpt_actionPerformed
     */
    public void actionHTMLForRpt_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionHTMLForRpt_actionPerformed(e);
    }

    /**
     * output actionExcelForRpt_actionPerformed
     */
    public void actionExcelForRpt_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExcelForRpt_actionPerformed(e);
    }

    /**
     * output actionLinkForRpt_actionPerformed
     */
    public void actionLinkForRpt_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionLinkForRpt_actionPerformed(e);
    }

    /**
     * output actionPopupPaste_actionPerformed
     */
    public void actionPopupPaste_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPopupPaste_actionPerformed(e);
    }

    /**
     * output actionToolBarCustom_actionPerformed
     */
    public void actionToolBarCustom_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionToolBarCustom_actionPerformed(e);
    }

    /**
     * output actionCloudFeed_actionPerformed
     */
    public void actionCloudFeed_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionCloudFeed_actionPerformed(e);
    }

    /**
     * output actionCloudShare_actionPerformed
     */
    public void actionCloudShare_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionCloudShare_actionPerformed(e);
    }

    /**
     * output actionCloudScreen_actionPerformed
     */
    public void actionCloudScreen_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionCloudScreen_actionPerformed(e);
    }

    /**
     * output actionXunTongFeed_actionPerformed
     */
    public void actionXunTongFeed_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionXunTongFeed_actionPerformed(e);
    }

    /**
     * output actionAddNew_actionPerformed
     */
    public void actionAddNew_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionAddNew_actionPerformed(e);
    }

    /**
     * output actionView_actionPerformed
     */
    public void actionView_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionView_actionPerformed(e);
    }

    /**
     * output actionEdit_actionPerformed
     */
    public void actionEdit_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionEdit_actionPerformed(e);
    }

    /**
     * output actionRemove_actionPerformed
     */
    public void actionRemove_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionRemove_actionPerformed(e);
    }

    /**
     * output actionRefresh_actionPerformed
     */
    public void actionRefresh_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionRefresh_actionPerformed(e);
    }

    /**
     * output actionPrint_actionPerformed
     */
    public void actionPrint_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPrint_actionPerformed(e);
    }

    /**
     * output actionPrintPreview_actionPerformed
     */
    public void actionPrintPreview_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPrintPreview_actionPerformed(e);
    }

    /**
     * output actionLocate_actionPerformed
     */
    public void actionLocate_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionLocate_actionPerformed(e);
    }

    /**
     * output actionQuery_actionPerformed
     */
    public void actionQuery_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionQuery_actionPerformed(e);
    }

    /**
     * output actionImportData_actionPerformed
     */
    public void actionImportData_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionImportData_actionPerformed(e);
    }

    /**
     * output actionAttachment_actionPerformed
     */
    public void actionAttachment_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionAttachment_actionPerformed(e);
    }

    /**
     * output actionExportData_actionPerformed
     */
    public void actionExportData_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionExportData_actionPerformed(e);
    }

    /**
     * output actionToExcel_actionPerformed
     */
    public void actionToExcel_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionToExcel_actionPerformed(e);
    }

    /**
     * output actionStartWorkFlow_actionPerformed
     */
    public void actionStartWorkFlow_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionStartWorkFlow_actionPerformed(e);
    }

    /**
     * output actionPublishReport_actionPerformed
     */
    public void actionPublishReport_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionPublishReport_actionPerformed(e);
    }

    /**
     * output actionCancel_actionPerformed
     */
    public void actionCancel_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionCancel_actionPerformed(e);
    }

    /**
     * output actionCancelCancel_actionPerformed
     */
    public void actionCancelCancel_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionCancelCancel_actionPerformed(e);
    }

    /**
     * output actionQueryScheme_actionPerformed
     */
    public void actionQueryScheme_actionPerformed(ActionEvent e) throws Exception
    {
        super.actionQueryScheme_actionPerformed(e);
    }

	protected ICoreBase getBizInterface() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	protected String getEditUIName() {
		return null;
	}

}