package com.tofly.ghrq_route.common.ui.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.Gson;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.module.map.MapServiceTool;
import com.tofly.ghrq_route.module.map.controller.MapController;
import com.tofly.ghrq_route.module.map.controller.MapServiceCallback;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.LayerResultBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalysisResultBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalysisResultBean.ResultBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalysisResultBean.ResultBean.SummaryBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalysisResultBean.ResultBean.SummaryBean.LayersummaryBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalyzeFindTaskBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalyzeMustShutFeatureBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeDetailFindBean;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeDetailQueryBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.module.user.domain.UserOnlineMapDataBean;
import com.tofly.ghrq_route.common.ui.adapter.ListLayerSummaryAdapter;
import com.tofly.ghrq_route.common.util.net.http.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PipeAnalyzeResultBottomSheet extends CoordinatorLayout {
    @BindView(R.id.layout_line_params)
    LinearLayout layoutLineParams;
    @BindView(R.id.text_line_type)
    TextView textLineType;
    @BindView(R.id.text_line_no)
    TextView textLineNo;
    @BindView(R.id.main_hint_text)
    TextView mainHintText;
    @BindView(R.id.layout_start_analyze)
    LinearLayout layoutStartAnalyze;
    /*@BindView(R.id.check_commit_point)
    CheckBox checkCommitPoint;*/
    @BindView(R.id.btn_start_analyze)
    Button btnStartAnalyze;
    @BindView(R.id.reuslts_list_view)
    ExpandableListView resultsListView;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.text_cancel)
    TextView textCancel;

    private Context mContext;
    private PipeAnalysisResultBean mResultBean;
    private ListLayerSummaryAdapter summaryAdapter;
    private Map<Integer, Boolean> mHeadOpenedMap = new HashMap<>();//是否已点击
    private List<LayerResultBean> layerResultBeanList;
    private Runnable runnable1;
    private PipeAnalyzeCallback pipeAnalyzeCallback;
    private OnPipeAnalyzeStartClicked pipeAnalyzeStartClicked;
    private OnPipeAnalyzeCancelClicked pipeAnalyzeCancelClicked;

    private DBDaoHelper dbDaoHelper;

    protected BottomSheetBehavior<PipeAnalyzeResultBottomSheet> behavior;

    private MapController mapController;

    private MapView mapView;

    private ArcGISMapImageLayer mPipeAnalyzeLayer;

    private boolean bShowProgress = false;

    private MapServiceTool mapServiceTool;

    private static final int TOQUERYDETAIL = 1;
    private static final int TOTOAST = 2;

    public static final int PEEK_HEIGHT = 56;
    public static final int HEIGHT = 300;

    public interface PipeAnalyzeCallback {
        void showFeatureByCallout(Feature feature, List<Field> fields, String tableName);
        void hideCallout();
    }

    public interface OnPipeAnalyzeStartClicked{
        void onStartlCliked(/*boolean bCommitPoint*/);
    }

    public interface OnPipeAnalyzeCancelClicked{
        void onCancelCliked();
    }

    public PipeAnalyzeResultBottomSheet(Context context) {
        this(context, null);
    }

    public PipeAnalyzeResultBottomSheet(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PipeAnalyzeResultBottomSheet(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        this.dbDaoHelper = DBDaoHelper.getInstance();
        mapServiceTool = MapServiceTool.getInstance();
        initView();
        initData();
        initListener();
    }

    public void onStart(){
        setHeight();
        //initBehavior();
        progressBar.setVisibility(GONE);
        mainHintText.setVisibility(VISIBLE);
        layoutStartAnalyze.setVisibility(GONE);
    }

    public void onStop(){
        //behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
    }

    public void setMapController(MapController mapController, MapView mapView){
        this.mapController = mapController;
        this.mapView = mapView;
    }

    public void showProgress(int visibility){
        progressBar.setVisibility(visibility);
    }

    public boolean isShowProgress() {
        return bShowProgress;
    }

    public void setShowProgressCancelBtn(){
        bShowProgress = true;
        showProgressAndCanceBtn();
    }

    public boolean showProgressAndCanceBtn(){
        showProgress(bShowProgress ? VISIBLE : GONE);
        textCancel.setVisibility(bShowProgress ? VISIBLE : GONE);
        return bShowProgress;
    }

    public void hideProgressAndCanceBtn() {
        showProgress(GONE);
        textCancel.setVisibility(GONE);
    }

    private void setHeight() {
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        layoutParams.height = BaseApp.dip2px(HEIGHT);
        setLayoutParams(layoutParams);
    }

    /*private void initBehavior() {
        behavior = BottomSheetBehavior.from(this);
        behavior.setHideable(false);
        post(new Runnable() {
            @Override
            public void run() {
                behavior.setPeekHeight(ScreenUtils.dip2px(mContext, HEIGHT));
            }
        });
        initBehaviorListener();
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }*/

    protected void initBehaviorListener() {

    }

    private void initView() {
        View rootView = inflate(mContext, R.layout.fragment_pipe_analyze_results, this);
        ButterKnife.bind(this, rootView);
        progressBar.setVisibility(GONE);
        mainHintText.setVisibility(VISIBLE);
        layoutStartAnalyze.setVisibility(GONE);
    }

    private void initData() {
        boolean bDataOk = false;
        if (mResultBean != null) {
            ResultBean results = mResultBean.getResult();
            if (results != null) {
                SummaryBean summary = results.getSummary();
                if (summary != null) {
                    List<LayersummaryBean> layersummary = summary.getLayersummary();
                    if (layersummary != null && layersummary.size() > 0) {
                        summaryAdapter = new ListLayerSummaryAdapter(mContext, layersummary);
                        resultsListView.setAdapter(summaryAdapter);
                        bDataOk = true;
                    }
                }
            }
        }
        if (bDataOk) {
            mainHintText.setVisibility(View.GONE);
            resultsListView.setVisibility(View.VISIBLE);
        } else {
            mainHintText.setVisibility(View.VISIBLE);
            resultsListView.setVisibility(View.GONE);
        }
    }

    private void initListener() {
        resultsListView.setOnGroupClickListener((parent, v, groupPosition, id) -> {
            Boolean aBoolean = mHeadOpenedMap.get(groupPosition);
            if (!aBoolean) {
                LayersummaryBean layersummaryBean = (LayersummaryBean) summaryAdapter.getGroup(groupPosition);
                if (layersummaryBean.getLayerdbname().equals(MUST_SHUT_VALVE_DBLAYER_DBNAME)){
                    loadShutValveDetails(parent, v, groupPosition, layersummaryBean);
                }else {
                    loadDetailMessage(parent, v, groupPosition);
                }
            }

            return false;
        });

        btnStartAnalyze.setOnClickListener(v -> {
            if (pipeAnalyzeStartClicked != null) {
                //boolean bCommitPoint = checkCommitPoint.isChecked();
                pipeAnalyzeStartClicked.onStartlCliked();
            }
        });

        textCancel.setOnClickListener(v -> {
            if (pipeAnalyzeCancelClicked != null)
                pipeAnalyzeCancelClicked.onCancelCliked();
        });
    }

    private String getPipeUrl(){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        String pipe_query_url =  NetRequestURL.ONLINE_PIPE_INTERNAL;
        UserOnlineMapDataBean.MAP_CODE_KEY MAP_PIPE =
                UserOnlineMapDataBean.MAP_CODE_KEY.Code(UserOnlineMapDataBean.MAP_CODE_KEY.MAP_CODE_PIPE.getCode());
        UserOnlineMapDataBean pipeDataBean =
                dbDaoHelper.getUserOnlineMapData(userBean.getUserid(), MAP_PIPE.getCode());
        if (pipeDataBean != null) {
            String pipe_url = pipeDataBean.getCval();
            if (pipe_url != null && !pipe_url.isEmpty()){
                pipe_query_url = NetRequestURL.getReplaceUrl(pipe_url);
            }
        }
        return pipe_query_url;
    }

    private String getBurstUrl(){
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        String burst_query_url =  NetRequestURL.ONLINE_BURST_INTERNAL;
        UserOnlineMapDataBean.MAP_CODE_KEY MAP_BURST =
                UserOnlineMapDataBean.MAP_CODE_KEY.Code(UserOnlineMapDataBean.MAP_CODE_KEY.MAP_CODE_BURST.getCode());
        UserOnlineMapDataBean burstDataBean =
                dbDaoHelper.getUserOnlineMapData(userBean.getUserid(), MAP_BURST.getCode());
        if (burstDataBean != null) {
            String burst_url = burstDataBean.getCval();
            if (burst_url != null && !burst_url.isEmpty()){
                burst_query_url = NetRequestURL.getReplaceUrl(burst_url);
            }
        }
        return burst_query_url;
    }

    /**
     * Gis网路请求接口
     * Created by li on 2016/9/9.
     */
    public interface GisCallback {
        void success(String result);
        void error(String result);
        void netError(String result);
    }

    private void loadShutValveDetails(final AdapterView<?> parent, final View view, final int position, final LayersummaryBean layersummaryBean){
        mapController.setOnlineQueryWithKeyCallback((isSuccess, errStr, result) -> {
            List<PipeAnalyzeMustShutFeatureBean> featureResult = (List<PipeAnalyzeMustShutFeatureBean>) result;
            if (featureResult != null){
                //loadShutValveDetail(oids, features);
                loadValveLayerId(featureResult, layersummaryBean, position);
            }

        });
        if (mPipeAnalyzeLayer != null)
            mapController.query_pipe_online_mustshut(mapView, mPipeAnalyzeLayer);
    }

    private void loadDetailMessage(final AdapterView<?> parent, final View view, final int position) {
        runnable1 = () -> {
            ListLayerSummaryAdapter.PipeDetailViewHolder holder =
                    (ListLayerSummaryAdapter.PipeDetailViewHolder) view.getTag();
            final LinearLayout resultAreaLayout = holder.getResultAreaLayout();
            final ListView mDetailList = resultAreaLayout.findViewById(R.id.pipeanasis_pipenet_result_listview);
            final LinearLayout collapseLayout = holder.getCollapseLayout();
            LayersummaryBean layersummaryBean = (LayersummaryBean) summaryAdapter.getGroup(position);
            final String layerdbname = layersummaryBean.getLayerdbname();

            String pipe_query_url = getPipeUrl();
            String urlQuery = getBurstUrl();
            String job_url = NetRequestURL.getBurstJobUrl(urlQuery, mResultBean.getJobId());

            mapServiceTool.pipeAnalyzeFindTask(mContext, job_url, layerdbname, new MapServiceCallback() {
                @Override
                public void onPipeAnalyzeFindTask(boolean isSuccess, int errorCode, String errMsg, List<PipeAnalyzeFindTaskBean> taskBeans) {
                    super.onPipeAnalyzeFindTask(isSuccess, errorCode, errMsg, taskBeans);
                    if (isSuccess) {
                        final String pipe_url = pipe_query_url;
                        if (taskBeans != null) {
                            if (layerResultBeanList != null && layerResultBeanList.size() > 0) {
                                PipeDetailFindBean pipeDetailFindBean = getPipeDetailFindBean(
                                        resultAreaLayout, mDetailList, taskBeans, collapseLayout);
                                loadDetailByOid(pipe_url, position, pipeDetailFindBean);
                            } else {
                                HttpUtil httpUtil = new HttpUtil(mContext);
                                httpUtil.execute_get(pipe_query_url + "?f=pjson", new GisCallback() {
                                    @Override
                                    public void success(String result) {
                                        layerResultBeanList = null;
                                        try {
                                            JSONObject jsonObject = new JSONObject(result);
                                            JSONArray layers1 = jsonObject.getJSONArray("layers");
                                            layerResultBeanList = new ArrayList<>();
                                            Gson gson = new Gson();
                                            for (int i = 0; i < layers1.length(); i++) {
                                                JSONObject object = layers1.getJSONObject(i);
                                                String layerResult = object.toString();
                                                LayerResultBean layerResultBean = gson.fromJson(layerResult, LayerResultBean.class);
                                                layerResultBeanList.add(layerResultBean);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                            clossProgAndToast(e.getMessage());
                                        }
                                        if (layerResultBeanList != null && layerResultBeanList.size() > 0) {
                                            PipeDetailFindBean pipeDetailFindBean = getPipeDetailFindBean(
                                                    resultAreaLayout, mDetailList, taskBeans, collapseLayout);
                                            loadDetailByOid(pipe_url, position, pipeDetailFindBean);
                                        }
                                    }

                                    @Override
                                    public void error(String result) {
                                        Log.w("TAG", "error: result = " + result);
                                        clossProgAndToast(result);

                                    }

                                    @Override
                                    public void netError(String result) {
                                        Log.w("TAG", "error: result = " + result);
                                        clossProgAndToast(result);
                                    }
                                });
                            }
                        } else {
                            clossProgAndToast("查询结果为空");
                        }
                    }else {
                        clossProgAndToast("查询结果为空");
                    }
                }
            });
        };
        runnable1.run();
    }

    @NonNull
    private PipeDetailFindBean getPipeDetailFindBean(LinearLayout resultAreaLayout, ListView mDetailList
            , List<PipeAnalyzeFindTaskBean> taskBeans, LinearLayout collapseLayout) {
        PipeDetailFindBean pipeDetailFindBean = new PipeDetailFindBean();
        List<Long> oids = new ArrayList<>();
        pipeDetailFindBean.setOids(oids);
        pipeDetailFindBean.setResultAreaLayout(resultAreaLayout);
        pipeDetailFindBean.setmDetailList(mDetailList);
        pipeDetailFindBean.setCollapseLayout(collapseLayout);

        if (taskBeans.size() > 0){
            String layername = taskBeans.get(0).getAttributes().getLayername();
            LayerResultBean findResultBean = null;
            for (LayerResultBean layerResultBean : layerResultBeanList) {
                String name = layerResultBean.getName();
                if (name.equals(layername)){
                    findResultBean = layerResultBean;
                    break;
                }
            }
            if (findResultBean != null) {
                int layerId = findResultBean.getId();
                String name = findResultBean.getName();
                pipeDetailFindBean.setLayerId(layerId);
                pipeDetailFindBean.setLayerName(name);
                for (PipeAnalyzeFindTaskBean taskBean : taskBeans) {
                    String oid = String.valueOf(taskBean.getAttributes().getSourceoid());
                    oids.add(Long.valueOf(oid));
                }
            }
        }
        return pipeDetailFindBean;
    }

    private void clossProgAndToast(String s) {
        Message msg = Message.obtain();
        msg.obj = s;
        msg.what = TOTOAST;
        handler.sendMessage(msg);
    }

    private void initOpenedMap(List<LayersummaryBean> layersummary) {
        if (layersummary != null && layersummary.size() > 0) {
            mHeadOpenedMap.clear();
            int size = layersummary.size();
            for (int i = 0; i < size; i++) {
                mHeadOpenedMap.put(i, false);
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (what == TOQUERYDETAIL) {
                PipeDetailQueryBean pdq = (PipeDetailQueryBean) msg.obj;
                final int position = msg.arg1;
                List<Feature> fetures = pdq.getFetures();
                final List<Field> fields = pdq.getFields();
                final String tableName = pdq.getTableName();
                summaryAdapter.updateChildData(position, fetures);
                resultsListView.collapseGroup(position);
                resultsListView.expandGroup(position);
                resultsListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
                    Object child = parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
                    if (child instanceof Feature) {
                        Feature feature = (Feature) child;
                        pipeAnalyzeCallback.showFeatureByCallout(feature, fields, tableName);
                    } else {
                        Toast.makeText(mContext, "结果错误！", Toast.LENGTH_SHORT).show();
                    }
                    return false;
                });
                mHeadOpenedMap.put(position, true);
            } else if (what == TOTOAST) {
                Toast.makeText(mContext, (CharSequence) msg.obj, Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void loadDetailByOid(String pipe_query_url, int position, PipeDetailFindBean pipeDfb) {
        int layerId = pipeDfb.getLayerId();
        List<Long> oids = pipeDfb.getOids();
        LinearLayout resultAreaLayout = pipeDfb.getResultAreaLayout();
        ListView mDetailList = pipeDfb.getmDetailList();
        LinearLayout collapseLayout = pipeDfb.getCollapseLayout();
        String tableName = pipeDfb.getLayerName();

        String urlQuery = pipe_query_url + "/" + layerId;
        final ServiceFeatureTable hydrantsTable = new ServiceFeatureTable(urlQuery);
        QueryParameters queryParameters = new QueryParameters();
        List<Long> objectids = queryParameters.getObjectIds();
        objectids.addAll(oids);
        final ListenableFuture<FeatureQueryResult> future = hydrantsTable.queryFeaturesAsync(queryParameters, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
        future.addDoneListener(() -> {
            List<Feature> fetures = new ArrayList<>();
            List<Field> fields = null;
            try {
                FeatureQueryResult queryResult = future.get();
                fields = queryResult.getFields();
                for (GeoElement element : queryResult) {
                    if (element instanceof Feature) {
                        Feature f = (Feature) element;
                        fetures.add(f);
                    }
                }
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }

            if (fetures.size() > 0) {
                PipeDetailQueryBean pipeDetailQueryBean = new PipeDetailQueryBean();
                pipeDetailQueryBean.setResultAreaLayout(resultAreaLayout);
                pipeDetailQueryBean.setmDetailList(mDetailList);
                pipeDetailQueryBean.setFetures(fetures);
                pipeDetailQueryBean.setFields(fields);
                pipeDetailQueryBean.setTableName(tableName);
                pipeDetailQueryBean.setCollapseLayout(collapseLayout);
                Message msg = Message.obtain();
                msg.arg1 = position;
                msg.what = TOQUERYDETAIL;
                msg.obj = pipeDetailQueryBean;
                handler.sendMessage(msg);
            } else {
                clossProgAndToast("Query为空！");
            }
        });
    }

    private void loadValveLayerId(final List<PipeAnalyzeMustShutFeatureBean> featureResult, final LayersummaryBean layersummaryBean, final int position){
        if (layerResultBeanList == null || layerResultBeanList.size() == 0){
            String pipe_query_url = getPipeUrl();
            HttpUtil httpUtil = new HttpUtil(mContext);
            httpUtil.execute_get(pipe_query_url + "?f=pjson", new GisCallback() {
                @Override
                public void success(String result) {
                    layerResultBeanList = null;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray layers1 = jsonObject.getJSONArray("layers");
                        layerResultBeanList = new ArrayList<>();
                        Gson gson = new Gson();
                        for (int i = 0; i < layers1.length(); i++) {
                            JSONObject object = layers1.getJSONObject(i);
                            String layerResult = object.toString();
                            LayerResultBean layerResultBean = gson.fromJson(layerResult, LayerResultBean.class);
                            layerResultBeanList.add(layerResultBean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        clossProgAndToast(e.getMessage());
                    }
                    loadShutValveDetail(featureResult, layersummaryBean, position);
                }

                @Override
                public void error(String result) {
                    clossProgAndToast(result);
                }

                @Override
                public void netError(String result) {
                    clossProgAndToast(result);
                }
            });
        }else {
            loadShutValveDetail(featureResult, layersummaryBean, position);
        }
    }

    private void loadShutValveDetail(List<PipeAnalyzeMustShutFeatureBean> fResult , final LayersummaryBean layersummaryBean, final int position){
        int layerId = -1;
        for (LayerResultBean resultBean : layerResultBeanList){
            if (resultBean.getName().equals(VALVE_LAYER_NAME)){
                layerId = resultBean.getId();
                break;
            }
        }

        List<Long> oids = new ArrayList<>();
        List<Feature> oldFeatures = new ArrayList<>();
        for (PipeAnalyzeMustShutFeatureBean feature : fResult) {
            String strOid = feature.getAttributes().getSourceoid();
            oids.add(Long.valueOf(strOid));
        }

        String pipe_query_url = getPipeUrl();
        List<Feature> features = new ArrayList<>();
        String urlQuery = pipe_query_url + "/" + layerId;
        ServiceFeatureTable hydrantsTable = new ServiceFeatureTable(urlQuery);
        QueryParameters parameters = new QueryParameters();
        List<Long> objectids = parameters.getObjectIds();
        objectids.addAll(oids);
        final ListenableFuture<FeatureQueryResult> future = hydrantsTable.queryFeaturesAsync(parameters, ServiceFeatureTable.QueryFeatureFields.LOAD_ALL);
        future.addDoneListener(() -> {
            try {
                FeatureQueryResult featureResult = future.get();
                for (Object element : featureResult) {
                    if (element instanceof Feature) {
                        Feature f = (Feature) element;
                        features.add(f);
                    }
                }
            } catch (Exception e) {
                features.clear();
                features.addAll(oldFeatures);
            }

            if (features.size() > 0){
                layersummaryBean.setCount(features.size());
                PipeDetailQueryBean pipeDetailQueryBean = new PipeDetailQueryBean();
                pipeDetailQueryBean.setFetures(features);
/*                List<Field> fields = fResult.getFields();
                pipeDetailQueryBean.setFields(fields);*/
                pipeDetailQueryBean.setTableName(VALVE_LAYER_NAME);
                Message msg = Message.obtain();
                msg.arg1 = position;
                msg.what = TOQUERYDETAIL;
                msg.obj = pipeDetailQueryBean;
                handler.sendMessage(msg);
            }else {
                Toast.makeText(mContext, "没有数据！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setPipeAnasCallback(PipeAnalyzeCallback pipeAnalyzeCallback) {
        this.pipeAnalyzeCallback = pipeAnalyzeCallback;
    }

    public void setOnPipeAnalyzeStartClicked(OnPipeAnalyzeStartClicked onstartClicked){
        this.pipeAnalyzeStartClicked = onstartClicked;
    }

    public void setOnPipeAnalyzeCancelClicked(OnPipeAnalyzeCancelClicked onCancelClicked){
        this.pipeAnalyzeCancelClicked = onCancelClicked;
    }

    public void showStartPipeAnalyzeLayout(String tableName, String lineNo){
        layoutLineParams.setVisibility(VISIBLE);
        textLineType.setText(tableName);
        textLineNo.setText(lineNo);
        layoutStartAnalyze.setVisibility(VISIBLE);
        mainHintText.setVisibility(GONE);
        resultsListView.setVisibility(View.GONE);
    }

    public void showStartPipeAnalyzeLayout(){
        mainHintText.setVisibility(GONE);
        layoutStartAnalyze.setVisibility(VISIBLE);
    }

    public void hideStartPipeAnalyzeLayout(){
        layoutStartAnalyze.setVisibility(GONE);
    }

    public static final String MUST_SHUT_VALVE_DBLAYER_DBNAME = "MUST_SHUT_VALVE";
    public static final String MUST_SHUT_VALVE_LAYER_NAME = "必关阀";
    public static final String VALVE_LAYER_NAME = "阀门";
    public void updateData(PipeAnalysisResultBean resultBean, ArcGISMapImageLayer serviceLayer) {
        mResultBean = resultBean;
        mPipeAnalyzeLayer = serviceLayer;
        hideStartPipeAnalyzeLayout();
        boolean bDataOk = false;
        if (mResultBean != null) {
            ResultBean results = mResultBean.getResult();
            if (results != null) {
                SummaryBean summary = results.getSummary();
                if (summary != null) {
                    List<LayersummaryBean> layersummary = summary.getLayersummary();
                    if (layersummary != null && layersummary.size() > 0) {
                        LayersummaryBean shutValveSummary = new LayersummaryBean();
                        shutValveSummary.setGeometrytype("esriGeometryPoint");
                        shutValveSummary.setLayername(MUST_SHUT_VALVE_LAYER_NAME);
                        shutValveSummary.setLayerdbname(MUST_SHUT_VALVE_DBLAYER_DBNAME);
                        layersummary.add(shutValveSummary);

                        initOpenedMap(layersummary);
                        if (summaryAdapter == null) {
                            summaryAdapter = new ListLayerSummaryAdapter(mContext, layersummary);
                            resultsListView.setAdapter(summaryAdapter);
                        } else {
                            summaryAdapter.updateGroupData(layersummary);
                            for (int i = 0; i < layersummary.size(); i++) {
                                resultsListView.collapseGroup(i);
                                resultsListView.expandGroup(i);
                            }
                        }
                        bDataOk = true;
                    }
                }
            }
        }
        try {
            if (bDataOk) {
                mainHintText.setVisibility(View.GONE);
                layoutStartAnalyze.setVisibility(GONE);
                resultsListView.setVisibility(View.VISIBLE);
                if (mResultBean != null){
                    ResultBean results = mResultBean.getResult();
                    String selectString = results.getSelectedfeature();
                    if (selectString != null && !selectString.isEmpty()){
                        String[] args = selectString.split(":");
                        if (args != null && args.length >= 2){
                            layoutLineParams.setVisibility(VISIBLE);
                            textLineType.setText(args[0]);
                            textLineNo.setText(args[1]);
                        }
                    }
                }
            } else {
                mainHintText.setVisibility(View.GONE);
                if (resultBean != null)
                    layoutStartAnalyze.setVisibility(VISIBLE);
                resultsListView.setVisibility(View.GONE);
                //layoutLineParams.setVisibility(GONE);
                if (summaryAdapter != null){
                    summaryAdapter.clearAllData();
                }
            }
        } catch (Exception e) {
            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
