package com.gx.obe.evaluation.step.resutl.composite;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.utils.FileDialogUtils;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.core.widgets.ImageButton;
import org.eclipse.swt.core.widgets.RectangleRadioButton;
import org.eclipse.swt.custom.StackLayout;
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.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

import com.gx.obe.ColorConstants;
import com.gx.obe.action.bean.Action;
import com.gx.obe.business.enumeration.UserEnum;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.dialog.MessageViewDialog;
import com.gx.obe.common.widget.dialog.ProgressDialog;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.enumeration.EvaluationFactorEnum;
import com.gx.obe.evaluation.step.composite.CompareEvaluationTableComposite;
import com.gx.obe.evaluation.step.composite.PriceEditAndResultComposite;
import com.gx.obe.evaluation.step.dataset.ClearCommentsDataSet;
import com.gx.obe.evaluation.step.thread.ImportSupplierFactorOpinionThread;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.auth.AuthUser;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.evaluation.EvaluationFactorService;
import com.gx.obe.web.service.evaluation.EvaluationGroupService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
import com.report.excel.ExcelGenerateAdapter;
import com.report.excel.ExcelReportUtil;
import com.report.excel.ReportDataSet;
import com.swtdesigner.ResourceManager;

public class PreEvaluationResultComposite extends Composite {
    
    private SupplierService supplierService = new SupplierService();
    private EvaluationStepService evaluationStepService = new EvaluationStepService();
    private EvaluationFactorService evaluationFactorService = new EvaluationFactorService();
    private EvaluationGroupService evaluationGroupService = new EvaluationGroupService();
    
    private Composite topComposite;
    private Composite switchComposite;
    private Composite evaluationTableComposite;
    private ImageButton curButton;
    private Map<String, List<String>> supplierIdListEvalBidTypeMap;
    private TenderProjectEntity curTender;
    private EvaluationStep curStep;
    private Composite opinionResultLink;
    private CompareEvaluationTableComposite busOpinionResultComposite;
    private CompareEvaluationTableComposite tecOpinionResultComposite;
    private PriceEditAndResultComposite priceEditAndResultComposite;
    private StackLayout stackLayout = new StackLayout();
    private String evalBidType;
    private AuthUser curUser;
	private ESepator expert_tab;
    
    /**
     * Create the composite.
     * 
     * @param parent
     * @param style
     * @param action 
     */
    public PreEvaluationResultComposite(Composite parent, int style, Action action) {
        super(parent, style);
        GridLayout gridLayout = new GridLayout(1, false);
        gridLayout.horizontalSpacing = 0;
        gridLayout.verticalSpacing = 0;
        gridLayout.marginHeight = 0;
        gridLayout.marginWidth = 0;
        setLayout(gridLayout);
        
        this.curTender = (TenderProjectEntity) action.getTenderProject();
        this.curStep = (EvaluationStep) action.getData("evaluationStep");
        this.curUser = (AuthUser) action.getData("curUser");
        
        Composite composite = new Composite(this, SWT.NONE);
        GridLayout gl_composite = new GridLayout(2, false);
        gl_composite.marginWidth = 0;
        gl_composite.verticalSpacing = 0;
        gl_composite.horizontalSpacing = 0;
        gl_composite.marginHeight = 0;
        composite.setLayout(gl_composite);
        composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        
        topComposite = new Composite(composite, SWT.NONE);
        topComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        GridLayout gl_topComposite = new GridLayout(2, false);
        gl_topComposite.marginHeight = 0;
        gl_topComposite.marginWidth = 0;
        topComposite.setLayout(gl_topComposite);
        
        switchComposite = new Composite(topComposite, SWT.NONE);
        switchComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		RowLayout rl_expert_list_composite = new RowLayout(SWT.HORIZONTAL);
		rl_expert_list_composite.marginLeft = 0;
		rl_expert_list_composite.marginBottom = 0;
		rl_expert_list_composite.spacing = 5;
		switchComposite.setLayout(rl_expert_list_composite);
        
        opinionResultLink = new Composite(topComposite, SWT.NONE);
        opinionResultLink.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
        opinionResultLink.setLayout(new GridLayout(2, false));
        
        ELink exportOpinionResultLink = new ELink(opinionResultLink, SWT.NONE);
        exportOpinionResultLink.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                exportOpinionResultAction();
            }
        });
        exportOpinionResultLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/export.png"));
        exportOpinionResultLink.setText(MessageFormat.format(Messages.Button_exportFormat, Messages.BidFileComments));
        
        ELink importOpinionResultLink = new ELink(opinionResultLink, SWT.NONE);
        importOpinionResultLink.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                importOpinionResultAction();
            }
        });
        importOpinionResultLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/import.png"));
        importOpinionResultLink.setText(MessageFormat.format(Messages.Button_importFormat, Messages.BidFileComments));
        
        expert_tab = new ESepator(composite, SWT.NONE);
		expert_tab.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
		expert_tab.setBackground(ColorConstants.SKIN_BG);
		expert_tab.setLineWidth(2);
		
        evaluationTableComposite = new Composite(composite, SWT.NONE);
//        evaluationTableComposite.setBackground(ColorConstants.BORDER_LINE_COLOR);
        stackLayout.marginHeight = 0;
        stackLayout.marginWidth = 0;
        evaluationTableComposite.setLayout(stackLayout);
        evaluationTableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
        
        init();
    }
    
    /**
     * @Description: 初始化
     * @author chenxw
     */
    private void init() {
        for (Control control : switchComposite.getChildren()) {
            control.dispose();
        }
        
        String userId = null;
        if (null != curUser) {
            userId = curUser.getId();
        }
        String stepId = null;
        if (null != curStep) {
            stepId = curStep.getId();
        }
        supplierIdListEvalBidTypeMap = evaluationGroupService.getSupplierIdListEvalBidTypeMapByUserId(curTender.getId(), userId, stepId);
        if (null == curStep) {
            List<EvaluationStep> preEvaluationStep = evaluationStepService.getEvaluationStepListByType(curTender.getId(), com.gx.obe.components.core.enumeration.EvaluationStepEnum.PRE_EVALUATION);
            for (EvaluationStep evaluationStep : preEvaluationStep) {
                createEvaluationImageButton(evaluationStep);
            }
        } else {
            createEvaluationImageButton(curStep);
        }
        Control[] children = switchComposite.getChildren();
        if (children.length == 0) {
        	WidgetUtils.setControlVisible(switchComposite, false);
        } else {
            if (children.length == 1) {
            	WidgetUtils.setControlVisible(switchComposite, false);
            } else {
            	WidgetUtils.setControlVisible(switchComposite, true);
            }
            switchComposite.layout();
            curButton = (ImageButton) children[0];
            curButton.notifyListeners(SWT.MouseUp, null);
        }
        
        
        boolean hideOpinionResult = EvaluationFactorEnum.EVAL_BID_PRICE.equals(evalBidType) || !UserEnum.ROLE_TYPE_EVALUATION_MANAGER.equals(Constants.USER.getUserType());
        WidgetUtils.setControlVisible(opinionResultLink, !hideOpinionResult);
        
        WidgetUtils.setControlVisible(topComposite, (switchComposite.getVisible()||opinionResultLink.getVisible()));
        WidgetUtils.setControlVisible(expert_tab, (switchComposite.getVisible()||opinionResultLink.getVisible()));
        
    }
    
    private void createEvaluationImageButton(EvaluationStep evaluationStep) {
        if (EvaluationFactorEnum.EVAL_BID_DETAIL.equals(evaluationStep.getEvalBidType())) {
            createImageButton(Messages.Business, EvaluationFactorEnum.EVAL_BID_BUS, evaluationStep);
            createImageButton(Messages.Technology, EvaluationFactorEnum.EVAL_BID_TEC, evaluationStep);
        } else if (EvaluationFactorEnum.EVAL_BID_BUS.equals(evaluationStep.getEvalBidType())) {
            createImageButton(Messages.Business, EvaluationFactorEnum.EVAL_BID_BUS, evaluationStep);
        } else if (EvaluationFactorEnum.EVAL_BID_TEC.equals(evaluationStep.getEvalBidType())) {
            createImageButton(Messages.Technology, EvaluationFactorEnum.EVAL_BID_TEC, evaluationStep);
        } else if (EvaluationFactorEnum.EVAL_BID_PRICE.equals(evaluationStep.getEvalBidType())) {
            createImageButton(Messages.QuotedPrice, EvaluationFactorEnum.EVAL_BID_PRICE, evaluationStep);
        }
    }
    
    /**
     * @Description: 获取供应商列表
     * @author chenxw
     * @return
     */
    private List<Supplier> getSupplierList(List<String> supplierIdList, EvaluationStep preStep) {
        if (null == preStep) {
            return new ArrayList<Supplier>();
        }
        List<Supplier> supplierList = supplierService.getEvaluationStepSupplierList(curTender.getId(), preStep);
        if (null == supplierList) {
            supplierList = new ArrayList<Supplier>();
        }
        List<Supplier> list = new ArrayList<Supplier>(supplierList);
        CollectionUtils.filter(list, t -> null == supplierIdList || supplierIdList.contains(t.getId()));
        return list;
    }
    
    /**
     * @Description: 获取指标列表
     * @author chenxw
     * @return
     */
    private List<EvaluationFactor> getFactorList(String curType, EvaluationStep preStep) {
        if (null == preStep) {
            return new ArrayList<EvaluationFactor>();
        }
        List<EvaluationFactor> factorList = new ArrayList<EvaluationFactor>();
        Integer factorType = preStep.getEvaluationParamByKey(com.gx.obe.components.core.enumeration.EvaluationStepEnum.FACTOR_TYPE, Integer.class);
        if (null == factorType) {
            factorType = com.gx.obe.components.core.enumeration.EvaluationStepEnum.FACTOR_COMPLIANCE | com.gx.obe.components.core.enumeration.EvaluationStepEnum.FACTOR_SCORE;
        }
        if ((factorType & com.gx.obe.components.core.enumeration.EvaluationStepEnum.FACTOR_COMPLIANCE) != 0) {
            List<EvaluationStep> complianceEvaluationStepList = evaluationStepService.getEvaluationStepListByType(curTender.getId(), com.gx.obe.components.core.enumeration.EvaluationStepEnum.COMPLIANCE);
            for (EvaluationStep evaluationStep : complianceEvaluationStepList) {
                List<EvaluationFactor> evaluationStepFactorTreeList = evaluationFactorService.getEvaluationStepFactorTreeList(curTender.getId(), evaluationStep);
                factorList.addAll(evaluationStepFactorTreeList);
            }
        }
        if ((factorType & com.gx.obe.components.core.enumeration.EvaluationStepEnum.FACTOR_SCORE) != 0) {
            List<EvaluationStep> detailEvaluationStepList = evaluationStepService.getEvaluationStepListByType(curTender.getId(), com.gx.obe.components.core.enumeration.EvaluationStepEnum.DETAIL);
            for (EvaluationStep evaluationStep : detailEvaluationStepList) {
                List<EvaluationFactor> evaluationStepFactorTreeList = evaluationFactorService.getEvaluationStepFactorTreeList(curTender.getId(), evaluationStep);
                factorList.addAll(evaluationStepFactorTreeList);
            }
        }
        List<EvaluationFactor> list = new ArrayList<EvaluationFactor>(factorList);
        CollectionUtils.filter(list, t -> curType.equals(t.getEvalBidType()));
        return list;
    }
    
    /**
     * @Description: 获得按钮
     * @author chenxw
     * @param name
     * @param evalBidType
     * @return
     */
    private ImageButton createImageButton(String name, final String _evalBidType, final EvaluationStep preStep) {
        final RectangleRadioButton button = new RectangleRadioButton(switchComposite, SWT.NONE);
        button.setText(name);
        button.setLeftMargin(20);
        button.setRightMargin(20);
        button.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                curButton.setSelection(false);
                curButton = button;
                curButton.setSelection(true);
                evalBidType = _evalBidType;
                refreshEvaluationTableComposite(preStep);
            }
        });
        return button;
    }
    
    private void refreshEvaluationTableComposite(EvaluationStep preStep) {
        if (evalBidType.equals(EvaluationFactorEnum.EVAL_BID_BUS)) {
            if (null == busOpinionResultComposite || busOpinionResultComposite.isDisposed()) {
                busOpinionResultComposite = new CompareEvaluationTableComposite(evaluationTableComposite, SWT.NONE, true, false);
            }
            stackLayout.topControl = busOpinionResultComposite;
            busOpinionResultComposite.refresh(curTender, getSupplierList(supplierIdListEvalBidTypeMap.get(evalBidType), preStep), getFactorList(evalBidType, preStep));
        } else if (evalBidType.equals(EvaluationFactorEnum.EVAL_BID_TEC)) {
            if (null == tecOpinionResultComposite || tecOpinionResultComposite.isDisposed()) {
                tecOpinionResultComposite = new CompareEvaluationTableComposite(evaluationTableComposite, SWT.NONE, true, false);
            }
            stackLayout.topControl = tecOpinionResultComposite;
            tecOpinionResultComposite.refresh(curTender, getSupplierList(supplierIdListEvalBidTypeMap.get(evalBidType), preStep), getFactorList(evalBidType, preStep));
        } else if (evalBidType.equals(EvaluationFactorEnum.EVAL_BID_PRICE)) {
            if (null == priceEditAndResultComposite || priceEditAndResultComposite.isDisposed()) {
                priceEditAndResultComposite = new PriceEditAndResultComposite(evaluationTableComposite, SWT.NONE);
            }
            stackLayout.topControl = priceEditAndResultComposite;
            priceEditAndResultComposite.refresh(curTender, getSupplierList(null, preStep), false);
        }
        evaluationTableComposite.layout();
    }
    
    /**
     * @Description: 导出清标评议意见
     * @author chenxw
     */
    private void exportOpinionResultAction() {
        File templateFile = FileConstants.getResourceFile("ClearBidCommentContent.xlsx");
        if (!templateFile.exists()) return;
        String directorySavePath = FileDialogUtils.getDirectorySavePath(Messages.Tips_selectExportDic, "[" + curTender.getTenderNo() + "]" + curTender.getTenderName());
        if (StringUtils.isEmpty(directorySavePath)) return;
        String fileName = "";
        if (evalBidType.equals(EvaluationFactorEnum.EVAL_BID_BUS)) {
			fileName = Messages.BidFileComments+"-"+Messages.Business+".xlsx";
		} else if (evalBidType.equals(EvaluationFactorEnum.EVAL_BID_TEC)) {
			fileName = Messages.BidFileComments+"-"+Messages.Technology+".xlsx";
		}
        directorySavePath = directorySavePath.concat(File.separator).concat(fileName);
        ProgressDialog synchShell = new ProgressDialog(getShell(), MessageFormat.format(Messages.Button_exportFormat, Messages.BidFileComments));
        getExcelReportThread(templateFile, directorySavePath, synchShell).start();
        synchShell.open();
    }
    
    /**
     * @Description: 获取导出报表线程
     * @author chenxw
     * @param templateFile
     * @param directorySavePath
     * @param synchShell
     * @return
     */
    private Thread getExcelReportThread(final File templateFile, final String directorySavePath, final ProgressDialog synchShell) {
        return new Thread(new Runnable() {
            public void run() {
                ExcelReportUtil.generate(templateFile.getAbsolutePath(), directorySavePath, new ExcelGenerateAdapter() {
                    public List<ReportDataSet> initReportDataSetList(String dataSetName, Map<String, String> paramMap, Map<String, String> enumMap) {
                        ClearCommentsDataSet dataSet = new ClearCommentsDataSet();
                        dataSet.init(curTender);
                        dataSet.setSupplierList(getSupplierList(supplierIdListEvalBidTypeMap.get(evalBidType), curStep));
                        dataSet.setEvaluationFactorList(getAllChildFactors(getFactorList(evalBidType, curStep)));
                        return dataSet.getDateSetList(paramMap, enumMap);
                    }
                    
                    public void afterGenerate(String reportPath) {
                        Display.getDefault().syncExec(new Runnable() {
                            public void run() {
                                if (null != synchShell) {
                                    synchShell.close();
                                }
                                MessageDialog.openShortMessage(Messages.Tips_exportSuccess);
                            }
                        });
                    }
                });
            }
        });
    }
    
    /**
     * @Description: 递归获得所有子节点指标
     * @author chenxw
     * @param factors
     */
    private List<EvaluationFactor> getAllChildFactors(List<EvaluationFactor> factors) {
        List<EvaluationFactor> allChildFactors = new ArrayList<EvaluationFactor>();
        for (EvaluationFactor factor : factors) {
            if (CollectionUtils.isNull(factor.getChildFactorList())) {
                allChildFactors.add(factor);
            } else {
                allChildFactors.addAll(getAllChildFactors(factor.getChildFactorList()));
            }
        }
        return allChildFactors;
    }
    
    /**
     * @Description: 导入清标评议意见
     * @author chenxw
     */
    private void importOpinionResultAction() {
        final String excelFilePath = FileDialogUtils.getFileNames(SWT.MULTI, MessageFormat.format(Messages.Button_importFormat, Messages.BidFileComments), new String[] { "*.xls;*.xlsx" }, new String[] { "excel" });
        if (StringUtils.isEmpty(excelFilePath)) {
            return;
        }
        
        MessageViewDialog dialog = new MessageViewDialog(getShell(), -1);
        new ImportSupplierFactorOpinionThread(curTender.getId(), excelFilePath, dialog.getCallBack()).start();
        dialog.setTitle(MessageFormat.format(Messages.Button_importFormat, Messages.BidFileComments));
        dialog.open();
        
        curButton.notifyListeners(SWT.MouseUp, null);
    }
    
    @Override
    protected void checkSubclass() {
        // Disable the check that prevents subclassing of SWT components
    }
}
