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

import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridColumn;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.listener.TextHintListener;
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.custom.CLabel;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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 org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.SupplierEvaluationFactor;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.BigDecimalUtils;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.web.entity.Supplier;
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.SupplierEvaluationFactorService;
import com.gx.obe.web.service.SupplierService;
import com.gx.tools.composite.BidFileComposite;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 评议意见录入界面
 * @author chenxw
 */
public class FactorOpinionComposite extends Composite {
    
    private ImageResolver imageResolver = new ImageResolver();
    private Grid supplierGrid;
    private Supplier curSupplier;
    private CLabel supplierNameTitle;
    private Text supplierNameText;
    private Grid factorGrid;
    private Image treeExpandPic = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_expend.png");
    private Image treeClosePic = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_close.png");
    private StyledText evaluation_factor_memo;
    private ELink preFactorBtn;
    private ELink nextFactorBtn;
    private Text opinionText;
    private boolean isSave = true;
    private ImageButton hideOrShowFile_btn;
    private BidFileComposite bidFileComposite;
    private final int bidFileWidth = 650;
//  private final int bidFileWidth = 300;
    private Image menuOpenImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_parent.png");
    private Image menuImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_item.png");
    private EvaluationFactor curFactor;
    private boolean isHide = false;
    private SupplierService supplierService = new SupplierService();
    private SupplierEvaluationFactorService supplierEvaluationFactorService = new SupplierEvaluationFactorService();
    
    private List<Supplier> supplierList;
    private List<EvaluationFactor> factorList;
    private Map<String, EvaluationFactor> childFactorCodeMap;
    private Map<String, Map<String, SupplierEvaluationFactor>> opinionFactorCodeMapSupplierIdMap;
    
    private TenderProjectEntity curProject;
    private EvaluationStep curStep;
    private String curType;
    private List<String> supplierIdList;
    private OpinionListener listener;
    private Composite factorOpinionComposite;
    private boolean isEdit;
    private Label wordCountLabel;
    private List<EvaluationFactor> evaluationFactorList = new ArrayList<EvaluationFactor>();
    private boolean opinion = false;
    private Text supplierOpinionText;
    private StackLayout StackLayout;
    private Composite composite_5;
    private ImageButton opinionBtn;
    private ImageButton supplierOpinionBtn;
    private Composite composite_4;
    
    /**
     * Create the composite.
     * 
     * @param parent
     * @param style
     */
    public FactorOpinionComposite(Composite parent, int style) {
        super(parent, style);
        addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
                imageResolver.disposite();
            }
        });
        GridLayout gridLayout = new GridLayout(3, false);
        gridLayout.horizontalSpacing = 0;
        gridLayout.marginHeight = 0;
        gridLayout.marginWidth = 0;
        setLayout(gridLayout);
        
        Composite composite = new Composite(this, SWT.NONE);
        GridLayout gl_composite = new GridLayout(1, false);
        gl_composite.marginHeight = 0;
        gl_composite.marginWidth = 0;
        composite.setLayout(gl_composite);
        GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
        gd_composite.widthHint = 350;
        composite.setLayoutData(gd_composite);
        
        supplierGrid = new Grid(composite, SWT.H_SCROLL | SWT.V_SCROLL);
        supplierGrid.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                selectionSupplierAction();
            }
        });
        supplierGrid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        supplierGrid.setAutoHeight(true);
        supplierGrid.setAutoWidth(true);
        supplierGrid.setItemHeight(Constants.ROW_HIGHT);
        
        GridColumn gridColumn_2 = new GridColumn(supplierGrid, SWT.CENTER);
        gridColumn_2.setWidth(35);
        gridColumn_2.setMaxmumWidth(35);
        
        GridColumn gridColumn = new GridColumn(supplierGrid, SWT.NONE);
        gridColumn.setWidth(300);
        gridColumn.setWordWrap(true);
        
        ESepator ver = new ESepator(this, SWT.VERTICAL);
        ver.setBackground(ColorConstants.SEP_LIGHT_COLOR);
        ver.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, true, 1, 1));
        
        Composite composite_1 = new Composite(this, SWT.NONE);
        GridLayout gl_composite_1 = new GridLayout(1, false);
        gl_composite_1.verticalSpacing = 0;
        gl_composite_1.marginHeight = 0;
        gl_composite_1.marginWidth = 0;
        composite_1.setLayout(gl_composite_1);
        composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        
        Composite composite_2 = new Composite(composite_1, SWT.NONE);
        composite_2.setLayout(new GridLayout(2, false));
        composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        
        supplierNameTitle = new CLabel(composite_2, SWT.NONE);
        supplierNameTitle.setForeground(ColorConstants.NOTE_TIPS_COLOR);
        supplierNameTitle.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.NORMAL));
        supplierNameTitle.setText("当前供应商：");
        
        supplierNameText = new Text(composite_2, SWT.READ_ONLY);
        supplierNameText.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.NORMAL));
        supplierNameText.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
        supplierNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        
        ESepator hor = new ESepator(composite_1, SWT.HORIZONTAL);
        hor.setBackground(ColorConstants.SEP_LIGHT_COLOR);
        hor.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        
        Composite composite_3 = new Composite(composite_1, SWT.NONE);
        GridLayout gl_composite_3 = new GridLayout(5, false);
        gl_composite_3.horizontalSpacing = 0;
        gl_composite_3.marginHeight = 0;
        gl_composite_3.marginWidth = 0;
        composite_3.setLayout(gl_composite_3);
        composite_3.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        
        factorOpinionComposite = new Composite(composite_3, SWT.NONE);
        GridData gd_factorOpinionComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
        gd_factorOpinionComposite.widthHint = 350;
        factorOpinionComposite.setLayoutData(gd_factorOpinionComposite);
        GridLayout gl_factorOpinionComposite = new GridLayout(1, false);
        gl_factorOpinionComposite.verticalSpacing = 0;
        gl_factorOpinionComposite.marginHeight = 0;
        gl_factorOpinionComposite.marginWidth = 0;
        factorOpinionComposite.setLayout(gl_factorOpinionComposite);
        
        Composite factorGridComposite = new Composite(factorOpinionComposite, SWT.NONE);
        factorGridComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        GridLayout gl_factorGridComposite = new GridLayout(1, false);
        gl_factorGridComposite.marginHeight = 0;
        gl_factorGridComposite.marginWidth = 0;
        factorGridComposite.setLayout(gl_factorGridComposite);
        
        factorGrid = new Grid(factorGridComposite, SWT.H_SCROLL | SWT.V_SCROLL);
        factorGrid.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                selectionFactorAction();
            }
        });
        factorGrid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        factorGrid.setAutoHeight(true);
        factorGrid.setAutoWidth(true);
        factorGrid.setItemHeight(Constants.ROW_HIGHT);
        factorGrid.setTreeLinesVisible(true);
        
        GridColumn gridColumn_1 = new GridColumn(factorGrid, SWT.NONE);
        gridColumn_1.setWidth(250);
        gridColumn_1.setWordWrap(true);
        gridColumn_1.setTree(true);
        gridColumn_1.setTreeIndent(10);
        gridColumn_1.setTreeTogglePic(treeExpandPic, treeClosePic);
        gridColumn_1.setShowTreeTogglePic(true);
        
        ESepator factorHor = new ESepator(factorOpinionComposite, SWT.HORIZONTAL);
        factorHor.setBackground(ColorConstants.SEP_LIGHT_COLOR);
        factorHor.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        
        Composite composite_7 = new Composite(factorOpinionComposite, SWT.NONE);
        GridLayout gl_composite_7 = new GridLayout(1, false);
        gl_composite_7.verticalSpacing = 0;
        gl_composite_7.marginHeight = 0;
        gl_composite_7.marginWidth = 0;
        composite_7.setLayout(gl_composite_7);
        composite_7.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        
        evaluation_factor_memo = new StyledText(composite_7, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY);
        GridData gd_evaluation_factor_memo = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
        gd_evaluation_factor_memo.heightHint = 100;
        evaluation_factor_memo.setLayoutData(gd_evaluation_factor_memo);
        evaluation_factor_memo.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
        
        ESepator factorMemoHor = new ESepator(composite_7, SWT.HORIZONTAL);
        factorMemoHor.setBackground(ColorConstants.SEP_LIGHT_COLOR);
        factorMemoHor.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
        
        Composite composite_9 = new Composite(composite_7, SWT.NONE);
        composite_9.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
        GridLayout gl_composite_9 = new GridLayout(5, false);
        gl_composite_9.marginWidth = 0;
        gl_composite_9.marginHeight = 0;
        gl_composite_9.horizontalSpacing = 0;
        composite_9.setLayout(gl_composite_9);
        composite_9.setBackground(SWTResourceManager.getColor(240, 240, 240));
        composite_9.setBackgroundMode(SWT.INHERIT_FORCE);
        
        opinionBtn = new ImageButton(composite_9, SWT.NONE);
        opinionBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        opinionBtn.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                changeOpinionAction(true);
            }
        });
        opinionBtn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
        opinionBtn.setText(Messages.BidFileComments);
        setanswerBtnCss(opinionBtn);
        
        supplierOpinionBtn = new ImageButton(composite_9, SWT.NONE);
        supplierOpinionBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        supplierOpinionBtn.setLeftMargin(20);
        supplierOpinionBtn.setRightMargin(20);
        supplierOpinionBtn.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                changeOpinionAction(false);
            }
        });
        supplierOpinionBtn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
        supplierOpinionBtn.setText(Messages.BidFileSelfComment);
        setanswerBtnCss(supplierOpinionBtn);
        
        composite_4 = new Composite(composite_9, SWT.NONE);
        composite_4.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
        GridLayout gl_composite_4 = new GridLayout(2, false);
        gl_composite_4.marginHeight = 0;
        gl_composite_4.marginWidth = 0;
        gl_composite_4.horizontalSpacing = 0;
        composite_4.setLayout(gl_composite_4);
        
        wordCountLabel = new Label(composite_4, SWT.CENTER);
        wordCountLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
        wordCountLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
        wordCountLabel.setText("0");
        
        preFactorBtn = new ELink(composite_9, SWT.NONE);
        preFactorBtn.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                previewAction();
            }
        });
        preFactorBtn.setText(Messages.PreviousItem);
        preFactorBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_up.png"));
        
        nextFactorBtn = new ELink(composite_9, SWT.NONE);
        nextFactorBtn.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                nextAction();
            }
        });
        nextFactorBtn.setText(Messages.NextItem);
        nextFactorBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_down.png"));
        
        Composite composite_6 = new Composite(composite_7, SWT.NONE);
        GridLayout gl_composite_6 = new GridLayout(1, false);
        gl_composite_6.marginHeight = 0;
        gl_composite_6.marginWidth = 0;
        composite_6.setLayout(gl_composite_6);
        composite_6.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
        
        composite_5 = new Composite(composite_6, SWT.NONE);
        GridData gd_composite_5 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
        gd_composite_5.heightHint = 150;
        composite_5.setLayoutData(gd_composite_5);
        StackLayout=new StackLayout();
        composite_5.setLayout(StackLayout);
        
        opinionText = new Text(composite_5, SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL);
        opinionText.addModifyListener(new ModifyListener() {
            public void modifyText(ModifyEvent arg0) {
                isSave = false;
                wordCountLabel.setText(ObjectUtils.getObjString(opinionText.getText().length())+"/2000");
                wordCountLabel.getParent().layout();
            }
        });
        opinionText.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent e) {
                saveOpinionAction(true);
            }
        });
        opinionText.setTextLimit(2000);
        StackLayout.topControl = opinionText;
        
        
        supplierOpinionText = new Text(composite_5, SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL);
        supplierOpinionText.setEnabled(false);
        
        
        ESepator file_right_ver = new ESepator(composite_3, SWT.VERTICAL);
        file_right_ver.setBackground(ColorConstants.SEP_LIGHT_COLOR);
        file_right_ver.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, true, 1, 1));
        
        hideOrShowFile_btn = new ImageButton(composite_3, SWT.NONE);
        hideOrShowFile_btn.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                isHide = !isHide;
                hideOrShowFileAction();
            }
        });
        hideOrShowFile_btn.setBackgroundColor(SWTResourceManager.getColor(242, 242, 242));
        hideOrShowFile_btn.setActiveBackgroundColor(SWTResourceManager.getColor(255, 153, 0));
        hideOrShowFile_btn.setRightMargin(0);
        hideOrShowFile_btn.setTopMargin(50);
        hideOrShowFile_btn.setBottomMargin(50);
        hideOrShowFile_btn.setLeftMargin(0);
        hideOrShowFile_btn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
        hideOrShowFile_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/right_arrow.png"));
        
        ESepator file_left_ver = new ESepator(composite_3, SWT.VERTICAL);
        file_left_ver.setBackground(ColorConstants.SEP_LIGHT_COLOR);
        file_left_ver.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, true, 1, 1));
        
        bidFileComposite = new BidFileComposite(composite_3, SWT.NONE);
        GridData gd_bidFileComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
        gd_bidFileComposite.widthHint = bidFileWidth;
        bidFileComposite.setLayoutData(gd_bidFileComposite);
        
        init();
    }
    
    /**
     * @Description: 初始化
     * @author chenxw
     */
    private void init() {
//      wordCountLabel.setText(ObjectUtils.getObjString(opinionText.getText().length()));
    	opinionText.addPaintListener(new TextHintListener(Messages.BidFileComments + "（"+Messages.Button_autoSave+"）", 2000));
//        opinionText.addPaintListener(new PaintListener() {
//            public void paintControl(PaintEvent arg0) {
//                if(opinionText.getText().length() == 0){
//                    arg0.gc.setForeground(SWTResourceManager.getColor(100, 100, 100));
//                    arg0.gc.drawText(Messages.BidFileComments + "（"+Messages.Button_autoSave+"）", 2, 1, false);
//                }
//            }
//        });
        hideOrShowFileAction();
        opinionBtn.setSelection(true);
        WidgetUtils.setControlVisible(composite_4, false);
    }
    
    /**
     * @Description: 刷新
     * @author chenxw
     * @param curProject
     * @param curStep
     * @param curType
     * @param supplierIdList
     * @param factorList
     * @param isEdit
     */
    public void refresh(TenderProjectEntity curProject, EvaluationStep curStep, String curType, List<String> supplierIdList, List<EvaluationFactor> factorList, boolean isEdit) {
        this.curProject = curProject;
        this.curStep = curStep;
        this.curType = curType;
        this.supplierIdList = supplierIdList;
        this.factorList = new ArrayList<EvaluationFactor>(factorList);
        this.isEdit = isEdit;
        
        supplierNameTitle.setText(MessageFormat.format(Messages.Title_currentSupplier, com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, curProject.getTenderType())) + "：");
        supplierNameTitle.getParent().layout();
        refreshSupplierList();
        refreshFactorList();
        
        childFactorCodeMap = getChildFactorCodeMap();
        opinionFactorCodeMapSupplierIdMap = getOpinionFactorCodeMapSupplierIdMap();
        
        refreshSupplierGrid();
    }
    
    /**
     * @Description: 获取供应商列表
     * @author chenxw
     * @return
     */
    private void refreshSupplierList() {
        supplierList = supplierService.getEvaluationStepSupplierList(curProject.getId(), curStep);
        if (null != supplierIdList) {
            CollectionUtils.filter(supplierList, t -> supplierIdList.contains(t.getId()));
        }
        if (null == supplierList) {
            supplierList = new ArrayList<Supplier>();
        }
    }
    
    /**
     * @Description: 获取指标列表
     * @author chenxw
     * @return
     */
    private void refreshFactorList() {
        CollectionUtils.filter(factorList, t -> curType.equals(t.getEvalBidType()));
    }
    
    /**
     * @Description: 获取叶子指标节点列表
     * @author chenxw
     * @return
     */
    private Map<String, EvaluationFactor> getChildFactorCodeMap() {
        Map<String, EvaluationFactor> childFactorCodeMap = new HashMap<String, EvaluationFactor>();
        evaluationFactorList.clear();
        for (final EvaluationFactor evaluationFactor : factorList) {
            recursionChildFactorList(evaluationFactor, childFactorCodeMap);
        }
        return childFactorCodeMap;
    }
    
    /**
     * @Description: 递归叶子指标节点
     * @author chenxw
     * @param evaluationFactor
     * @param childFactorList
     */
    private void recursionChildFactorList(EvaluationFactor evaluationFactor, Map<String, EvaluationFactor> childFactorCodeMap) {
        if (null == evaluationFactor.getFactorCode()) evaluationFactor.setFactorCode(evaluationFactor.getId());
        if (CollectionUtils.isNull(evaluationFactor.getChildFactorList())) {
            childFactorCodeMap.put(evaluationFactor.getFactorCode(), evaluationFactor);
            evaluationFactorList.add(evaluationFactor);
        } else {
            for (EvaluationFactor childFactor : evaluationFactor.getChildFactorList()) {
                recursionChildFactorList(childFactor, childFactorCodeMap);
            }
        }
    }
    
    /**
     * @Description: 获取评议意见
     * @author chenxw
     * @return
     */
    private Map<String, Map<String, SupplierEvaluationFactor>> getOpinionFactorCodeMapSupplierIdMap() {
        List<SupplierEvaluationFactor> evalFactorResultList = supplierEvaluationFactorService.getEntityListByTenderId(curProject.getId());
        if (CollectionUtils.isNull(evalFactorResultList)) {
            return new HashMap<String, Map<String, SupplierEvaluationFactor>>();
        }
        Map<String, Map<String, SupplierEvaluationFactor>> opinionFactorCodeMapSupplierIdMap = new HashMap<String, Map<String, SupplierEvaluationFactor>>();
        for (SupplierEvaluationFactor supplierEvaluationFactor : evalFactorResultList) {
            final String factorCode = supplierEvaluationFactor.getFactorCode();
            if (!childFactorCodeMap.containsKey(factorCode)) {
                continue;
            }
            String supplierId = supplierEvaluationFactor.getSupplierId();
            if (opinionFactorCodeMapSupplierIdMap.containsKey(supplierId)) {
                opinionFactorCodeMapSupplierIdMap.get(supplierId).put(factorCode, supplierEvaluationFactor);
            } else {
                Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = new HashMap<String, SupplierEvaluationFactor>();
                opinionFactorCodeMap.put(factorCode, supplierEvaluationFactor);
                opinionFactorCodeMapSupplierIdMap.put(supplierId, opinionFactorCodeMap);
            }
        }
        return opinionFactorCodeMapSupplierIdMap;
    }
    
    /**
     * @Description: 刷新供应商列表
     * @author chenxw
     */
    private void refreshSupplierGrid() {
        supplierGrid.removeAll();
        int index = 1;
        for (Supplier supplier : supplierList) {
            GridItem gridItem = new GridItem(supplierGrid, SWT.NONE);
            gridItem.setText(0, (index++) + "");
            gridItem.setText(1, supplier.getSupplierName());
            gridItem.setData("supplier", supplier);
        }
        refreshSupplierGridItemImage();
        supplierGrid.setSelection(0);
        selectionSupplierAction();
    }
    
    /**
     * @Description: 刷新供应商表格图片
     * @author chenxw
     */
    private void refreshSupplierGridItemImage() {
        for (GridItem gridItem : supplierGrid.getItems()) {
            Supplier supplier = (Supplier) gridItem.getData("supplier");
            Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = opinionFactorCodeMapSupplierIdMap.get(supplier.getId());
            if (null == opinionFactorCodeMap) {
                gridItem.setImage(1, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/question.png"));
                continue;
            }
            List<SupplierEvaluationFactor> opinionList = new ArrayList<SupplierEvaluationFactor>(opinionFactorCodeMap.values());
            CollectionUtils.filter(opinionList, t -> StringUtils.isNotEmpty(t.getOpinion()));
            
            if (opinionList.size() == childFactorCodeMap.size()) {
                gridItem.setImage(1, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/submit.png"));
            } else if (opinionList.size() == 0) {
                gridItem.setImage(1, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/question.png"));
            } else {
                gridItem.setImage(1, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/warning.png"));
            }
        }
        supplierGrid.layout();
    }
    
    /**
     * @Description: 选择供应商事件
     * @author chenxw
     */
    private void selectionSupplierAction() {
        if (supplierGrid.getSelectionCount() == 0) {
            return;
        }
        curSupplier = (Supplier) supplierGrid.getSelection()[0].getData("supplier");
        supplierNameText.setText(curSupplier.getSupplierName());
        refreshFactorGrid();
    }
    
    /**
     * @Description: 刷新指标树
     * @author chenxw
     */
    private void refreshFactorGrid() {
        factorGrid.removeAll();
        for (EvaluationFactor evaluationFactor : factorList) {
            initChildGridItem(new GridItem(factorGrid, SWT.NONE), evaluationFactor);
        }
        refreshFactorGridItemImage();
        if (factorGrid.getItemCount() > 0 && factorGrid.getSelectionCount() == 0) {
            if (factorGrid.getItem(0).getItemCount() > 0) {
                factorGrid.setSelection(new GridItem[] { factorGrid.getItem(0).getItems()[0] });
            } else {
                factorGrid.setSelection(0);
            }
        }
        selectionFactorAction();
//      factorGridOrientate();
    }
    
    /**
     * @Description: 递归实现指标树
     * @author chenxw
     * @param gridItem
     * @param factor
     */
    private void initChildGridItem(GridItem gridItem, EvaluationFactor factor) {
        gridItem.setText(0, factor.getFactorName());
        gridItem.setData("evaluationFactor", factor);
        if (CollectionUtils.isNull(factor.getChildFactorList())) {
            gridItem.setImage(0, menuImage);
            gridItem.setData("isParent", "false");
        } else {
            gridItem.setImage(0, menuOpenImage);
            gridItem.setData("isParent", "true");
            gridItem.setExpanded(true);
            for (EvaluationFactor evaluationFactor : factor.getChildFactorList()) {
                initChildGridItem(new GridItem(gridItem, SWT.NONE), evaluationFactor);
            }
        }
        if (null != curFactor && factor.getId().equals(curFactor.getId())) {
            factorGrid.setSelection(new GridItem[] { gridItem });
        }
    }
    
    /**
     * @Description: 刷新指标表格图片
     * @author chenxw
     */
    private void refreshFactorGridItemImage() {
        Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = opinionFactorCodeMapSupplierIdMap.get(curSupplier.getId());
        for (GridItem gridItem : factorGrid.getItems()) {
            boolean isParent = "true".equalsIgnoreCase((String) gridItem.getData("isParent"));
            if (isParent) {
                continue;
            }
            gridItem.setImage(0, null);
            if (null == opinionFactorCodeMap) {
                continue;
            }
            EvaluationFactor evaluationFactor = (EvaluationFactor) gridItem.getData("evaluationFactor");
            SupplierEvaluationFactor supplierEvaluationFactor = opinionFactorCodeMap.get(evaluationFactor.getFactorCode());
            if (null == supplierEvaluationFactor) {
                continue;
            }
            if (StringUtils.isEmpty(supplierEvaluationFactor.getOpinion())) {
                continue;
            }
            gridItem.setImage(0, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/submit.png"));
        }
        factorGrid.layout();
        if (null != listener) {
            listener.editOpinionAction();
        }
    }
    
    /**
     * @Description: 选择指标事件
     * @author chenxw
     */
    private void selectionFactorAction() {
        if (factorGrid.getSelectionCount() == 0) {
        	refreshBidFileComposite();
            return;
        }
        boolean isNotParent = "false".equalsIgnoreCase((String) factorGrid.getSelection()[0].getData("isParent"));
        opinionText.setEnabled(isEdit && isNotParent);
        curFactor = (EvaluationFactor) factorGrid.getSelection()[0].getData("evaluationFactor");
        refreshBtnStatus();
        refreshEvaluationFactorMemo();
        refreshOpinionText();
        refreshBidFileComposite();
    }
    
    /**
     * @Description: 刷新按钮
     * @author chenxw
     */
    private void refreshBtnStatus() {
        int selectIndex = factorGrid.getSelectionIndex();
        preFactorBtn.setEnabled(true);
        nextFactorBtn.setEnabled(true);
        if (selectIndex <= 0) {
            preFactorBtn.setEnabled(false);
            preFactorBtn.redraw();
        }
        if (selectIndex == factorGrid.getItemCount() - 1) {
            nextFactorBtn.setEnabled(false);
        }
    }
    
    /**
     * @Description: 刷新评审指标备注
     * @author chenxw
     */
    private void refreshEvaluationFactorMemo() {
        StringBuilder evaluationFactorMemo = new StringBuilder();
        if (curStep.getStepType().equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.DETAIL)) {
            String factorMinScore = NumberFormat.getInstance().format(curFactor.getFactorMinScore());
            String factorMaxScore = NumberFormat.getInstance().format(curFactor.getFactorMaxScore());
            evaluationFactorMemo.append(Messages.ScoreRange + "：[").append(factorMinScore).append("-").append(factorMaxScore).append(Messages.Points + "]");
            if (null != curFactor.getFactorWeight()) {
                evaluationFactorMemo.append("("+Messages.Weight+"").append(BigDecimalUtils.round(curFactor.getFactorWeight(), 2).toString()).append("%)");
            }
            evaluationFactorMemo.append("   ");
        }
        
        int startIndex = evaluationFactorMemo.length();
        StyleRange factorNameTitleStyleRange = getTitleStyleRange(startIndex, Messages.EvalFactor.length() + 1);
        
        StyleRange styleFactorNameRange = new StyleRange();
        styleFactorNameRange.start = startIndex + Messages.EvalFactor.length() + 1;
        styleFactorNameRange.length = curFactor.getFactorName().length();
        styleFactorNameRange.foreground = SWTResourceManager.getColor(20, 20, 20);
        styleFactorNameRange.fontStyle = SWT.NORMAL;
        
        evaluationFactorMemo.append(Messages.EvalFactor + "：").append(curFactor.getFactorName());
        
        StyleRange factorMemoTitleStyleRange = null;
        StyleRange styleFactorMemoRange = null;
        if (null != curFactor.getMemo() && curFactor.getMemo().length() > 0) {
            evaluationFactorMemo.append("\r\n");
            startIndex = evaluationFactorMemo.length();
            factorMemoTitleStyleRange = getTitleStyleRange(startIndex, Messages.EvalExplain.length() + 1);
            evaluationFactorMemo.append(Messages.EvalExplain + "：").append(curFactor.getMemo());
            styleFactorMemoRange = new StyleRange();
            styleFactorMemoRange.start = startIndex + Messages.EvalExplain.length() + 1;
            styleFactorMemoRange.length = curFactor.getMemo().length();
            styleFactorMemoRange.foreground = SWTResourceManager.getColor(100, 100, 100);
            styleFactorMemoRange.fontStyle = SWT.NORMAL;
        }
        
        StyleRange styleScoreRange = new StyleRange();
        styleScoreRange.start = Messages.EvalExplain.length() + 1;
        styleScoreRange.length = evaluationFactorMemo.length() - (Messages.EvalExplain.length() + 1);
        styleScoreRange.foreground = SWTResourceManager.getColor(77, 163, 19);
        styleScoreRange.fontStyle = SWT.BOLD;
        
        evaluation_factor_memo.setText(evaluationFactorMemo.toString());
        evaluation_factor_memo.setStyleRange(getTitleStyleRange(0, Messages.EvalExplain.length() + 1));
        evaluation_factor_memo.setStyleRange(styleScoreRange);
        evaluation_factor_memo.setStyleRange(factorNameTitleStyleRange);
        evaluation_factor_memo.setStyleRange(styleFactorNameRange);
        if (null != factorMemoTitleStyleRange) {
            evaluation_factor_memo.setStyleRange(factorMemoTitleStyleRange);
            evaluation_factor_memo.setStyleRange(styleFactorMemoRange);
        }
    }
    
    /**
     * @Description: 获取StyleRange
     * @author chenxw
     * @param start
     * @param length
     * @return
     */
    private StyleRange getTitleStyleRange(int start, int length) {
        StyleRange styleRange = new StyleRange();
        styleRange.start = start;
        styleRange.length = length;
        styleRange.foreground = SWTResourceManager.getColor(SWT.COLOR_BLUE);
        styleRange.fontStyle = SWT.BOLD;
        return styleRange;
    }
    
    /**
     * @Description: 刷新评议意见
     * @author chenxw
     */
    private void refreshOpinionText() {
        if (opinionFactorCodeMapSupplierIdMap.containsKey(curSupplier.getId())) {
            Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = opinionFactorCodeMapSupplierIdMap.get(curSupplier.getId());
            if (opinionFactorCodeMap.containsKey(curFactor.getFactorCode())) {
                opinionText.setText(ObjectUtils.getObjString(opinionFactorCodeMap.get(curFactor.getFactorCode()).getOpinion()));
                
                String supplierOpinion = ObjectUtils.getObjString(opinionFactorCodeMap.get(curFactor.getFactorCode()).getFactorResponse());
                if(supplierOpinion.length() > 0){
                    supplierOpinionText.setText(ObjectUtils.getObjString(opinionFactorCodeMap.get(curFactor.getFactorCode()).getFactorResponse()));
                    WidgetUtils.setControlVisible(supplierOpinionBtn, true);
                }else{
                    hideSupplierBtn();
                }
            } else {
                opinionText.setText("");
                hideSupplierBtn();
            }
        } else {
            opinionText.setText("");
        }
        opinionText.getParent().layout();
    }
    
    /**
     * @Description: 隐藏自评
     * @author wangx
     */
    private void  hideSupplierBtn(){
        opinion = false;
        StackLayout.topControl = opinionText;
        opinionBtn.setSelection(true);
        supplierOpinionBtn.setSelection(false);
        WidgetUtils.setControlVisible(supplierOpinionBtn, false);
        refrashWordLabel();
    }
    
    /**
     * @Description: 刷新投标文件界面
     * @author chenxw
     */
    private void refreshBidFileComposite() {
        bidFileComposite.refresh(curProject, curSupplier, curFactor, curType);
    }
    
    /**
     * @Description: 保存评议意见
     * @author chenxw
     */
    public void saveOpinionAction(boolean isRefresh) {
        if (null == curSupplier || null == curFactor) {
            return;
        }
        if (isSave) {
            return;
        }
        String opinion = opinionText.getText().trim();
        if (opinionFactorCodeMapSupplierIdMap.containsKey(curSupplier.getId())) {
            Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = opinionFactorCodeMapSupplierIdMap.get(curSupplier.getId());
            if (opinionFactorCodeMap.containsKey(curFactor.getFactorCode())) {
                opinionFactorCodeMap.get(curFactor.getFactorCode()).setOpinion(opinion);
            } else {
                opinionFactorCodeMap.put(curFactor.getFactorCode(), getSupplierEvaluationFactor(opinion));
            }
        } else {
            Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = new HashMap<String, SupplierEvaluationFactor>();
            opinionFactorCodeMap.put(curFactor.getFactorCode(), getSupplierEvaluationFactor(opinion));
            opinionFactorCodeMapSupplierIdMap.put(curSupplier.getId(), opinionFactorCodeMap);
        }
        SupplierEvaluationFactor supplierEvaluationFactor = opinionFactorCodeMapSupplierIdMap.get(curSupplier.getId()).get(curFactor.getFactorCode());
        if (StringUtils.isEmpty(supplierEvaluationFactor.getId())) {
            supplierEvaluationFactor.setId(UuidUtils.getUUID());
            supplierEvaluationFactorService.insert(supplierEvaluationFactor);
        } else {
            supplierEvaluationFactorService.updateAssignProperty(supplierEvaluationFactor, new String[] { "opinion" });
        }
        isSave = true;
        if (isRefresh) {
            refreshFactorGridItemImage();
            refreshSupplierGridItemImage();
        }
    }
    
    /**
     * @Description: 获取评议意见
     * @author chenxw
     * @param opinion
     * @return
     */
    private SupplierEvaluationFactor getSupplierEvaluationFactor(String opinion) {
        SupplierEvaluationFactor supplierEvaluationFactor = new SupplierEvaluationFactor();
        supplierEvaluationFactor.setTenderId(curProject.getId());
        supplierEvaluationFactor.setSupplierId(curSupplier.getId());
        supplierEvaluationFactor.setFactorCode(curFactor.getFactorCode());
        supplierEvaluationFactor.setOpinion(opinion);
        return supplierEvaluationFactor;
    }
    
    /**
     * @Description: 切换清标意见
     * @author wangx
     * @param b 
     */
    private void changeOpinionAction(boolean b){
        //true  是自评
        opinion = b;
        if(opinion){
            opinion = false;
            StackLayout.topControl = opinionText;
            opinionBtn.setSelection(true);
            supplierOpinionBtn.setSelection(false);
            ((GridData)wordCountLabel.getLayoutData()).exclude = false;
            wordCountLabel.setVisible(true);
        }else{
            opinion = true;
            StackLayout.topControl = supplierOpinionText;
            opinionBtn.setSelection(false);
            supplierOpinionBtn.setSelection(true);
            ((GridData)wordCountLabel.getLayoutData()).exclude = true;
            wordCountLabel.setVisible(false);
        }
        composite_5.layout();
    }
    
    /**
     * @Description: 刷新字数
     * @author wangx
     */
    private void refrashWordLabel(){
        if(opinion){
            ((GridData)wordCountLabel.getLayoutData()).exclude = true;
            wordCountLabel.setVisible(false);
        }else{
            ((GridData)wordCountLabel.getLayoutData()).exclude = false;
            wordCountLabel.setVisible(true);
        }
        composite_4.layout();
    }
    
    /**
     * @Description: 查看上一指标
     * @author chenxw
     */
    private void previewAction() {
        opinionText.notifyListeners(SWT.FocusOut, null);
        if (!preFactorBtn.getEnabled()) {
            return;
        }
        factorGrid.setSelection(factorGrid.getSelectionIndex() - 1);
        selectionFactorAction();
        refrashWordLabel();
//      factorGridOrientate();
    }
    
    /**
     * @Description: 查看下一指标
     * @author chenxw
     */
    private void nextAction() {
        opinionText.notifyListeners(SWT.FocusOut, null);
        if (!nextFactorBtn.getEnabled()) {
            return;
        }
        factorGrid.setSelection(factorGrid.getSelectionIndex() + 1);
        selectionFactorAction();
        refrashWordLabel();
//      factorGridOrientate();
    }
    
    /**
     * @Description: 指标树定位
     * @author chenxw
     */
//  private void factorGridOrientate() {
//      Rectangle rectangle = factorGrid.getBounds();
//      factorGrid.scroll(0, 0, 0, 0, rectangle.width, rectangle.height, true);
//      factorGrid.getVerticalBar().setSelection(factorGrid.getSelectionIndex());
//      factorGrid.getVerticalBar().notifyListeners(SWT.Selection, null);
//  }
    
    /**
     * @Description: 设置指标分类的按钮
     * @author wangxiang
     * @param imageBtn
     */
    private void setanswerBtnCss(ImageButton imageBtn) {
        imageBtn.setRightMargin(10);
        imageBtn.setLeftMargin(10);
        imageBtn.setTopMargin(5);
        imageBtn.setBottomMargin(5);
        imageBtn.setRightMargin(20);
        imageBtn.setLeftMargin(20);
        imageBtn.setTopMargin(5);
        imageBtn.setBottomMargin(5);
        imageBtn.setRightMargin(10);
        imageBtn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));

        imageBtn.setForeground(ColorConstants.NOTE_TIPS_COLOR);
        imageBtn.setBackgroundColor(SWTResourceManager.getColor(245, 245, 245));

        imageBtn.setActiveForeground(ColorConstants.SKIN_ACTIVE_FOREGROUND);
        imageBtn.setActiveBackgroundColor(ColorConstants.SKIN_ACTIVE_BG);

        imageBtn.setSelectionForeground(ColorConstants.SKIN_SELECTOIN_FOREGROUND);
        imageBtn.setSelectionBgColor(ColorConstants.SKIN_BG);

    }
    
    /**
     * @Description: 隐藏或显示文件
     * @author chenxw
     */
    private void hideOrShowFileAction() {
        if (isHide) {
            hideOrShowFile_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/left_arrow.png"));
        } else {
            hideOrShowFile_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/right_arrow.png"));
        }
        ((GridData) bidFileComposite.getLayoutData()).exclude = isHide;;
        bidFileComposite.setVisible(!isHide);
        factorGrid.resizeColumnWidth();
        bidFileComposite.getParent().layout();
    }
    
    public boolean isNullFactorOpinion() {
        if (factorList.isEmpty()) {
            return false;
        }
        for (GridItem gridItem : supplierGrid.getItems()) {
            Supplier supplier = (Supplier) gridItem.getData("supplier");
            Map<String, SupplierEvaluationFactor> opinionFactorCodeMap = opinionFactorCodeMapSupplierIdMap.get(supplier.getId());
            if (null == opinionFactorCodeMap) {
                return true;
            }
            List<SupplierEvaluationFactor> opinionList = new ArrayList<SupplierEvaluationFactor>(opinionFactorCodeMap.values());
            CollectionUtils.filter(opinionList, t -> StringUtils.isNotEmpty(t.getOpinion()));
            
            if (opinionList.size() != childFactorCodeMap.size()) {
                return true;
            }
        }
        return false;
    }
    
    public void addOpinionListener(OpinionListener listener) {
        this.listener = listener;
    }
    
    public interface OpinionListener {
        void editOpinionAction();
    }
    
    public List<Supplier> getSupplierList() {
        return supplierList;
    }
    
    public List<EvaluationFactor> getEvaluationFactorList() {
        return evaluationFactorList;
    }
    
    @Override
    protected void checkSubclass() {
        // Disable the check that prevents subclassing of SWT components
    }
    
}
