package com.suzhou.carmanager.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.suzhou.carmanager.AppHelper;
import com.suzhou.carmanager.Constants;
import com.suzhou.carmanager.R;
import com.suzhou.carmanager.adapter.LogPhotoAdapter;
import com.suzhou.carmanager.adapter.OrderAdapter;
import com.suzhou.carmanager.base.BaseActivity;
import com.suzhou.carmanager.entity.AssignOrderLog;
import com.suzhou.carmanager.entity.FileInfo;
import com.suzhou.carmanager.entity.NetMessageVO;
import com.suzhou.carmanager.entity.OperateBtn;
import com.suzhou.carmanager.entity.Order;
import com.suzhou.carmanager.entity.Task;
import com.suzhou.carmanager.entity.UploadFile;
import com.suzhou.carmanager.location.BLocationManager;
import com.suzhou.carmanager.location.Location;
import com.suzhou.carmanager.manager.UploadManager;
import com.suzhou.carmanager.network.CarApiManager;
import com.suzhou.carmanager.network.HttpData;
import com.suzhou.carmanager.network.RxJava.MySubscriber;
import com.suzhou.carmanager.stepview.StepItemData;
import com.suzhou.carmanager.stepview.StepViewLayout;
import com.suzhou.carmanager.utils.IntentUtils;
import com.suzhou.carmanager.utils.JavaUtils;
import com.suzhou.carmanager.utils.ParseJsonUtils;
import com.suzhou.carmanager.utils.UIUtils;
import com.suzhou.carmanager.view.DividerItemDecoration;
import com.suzhou.carmanager.view.GridSpacingItemDecoration;
import com.suzhou.carmanager.view.NavigationTopBar;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import tv.xingtu.photopicker.intent.PhotoPreviewIntent;

/**
 * Created by Administrator on 2016/12/25.
 */
public class TaskDetailActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener{

    private static final String TAG = TaskDetailActivity.class.getSimpleName();
    private Context _context;
    private NavigationTopBar _navigationTopBar;
    private RecyclerView _recyclerView;
    private OrderAdapter _orderAdapter;
    private ArrayList<Order> _orders = new ArrayList<>();

    private SwipeRefreshLayout _swipeRefreshLayout;

    private RelativeLayout _assignActionLayout;
    private TextView _assignAction; //运单操作
    private TextView _assignCostPrice;

    private Task _task = new Task();
    private ASSIGN_STATUS _currentAssignStatus;

    private ArrayList<TImage> _photosData = new ArrayList<>();
    private UploadManager _uploadManager;
    private ProgressDialog _progressDialog;
    private Timer mCheckUploadProgressTimer;
    private TimerTask mCheckUploadProgressTimerTask;

    private Order _currentOrder = null;
    private OperateBtn _currentOperateBtn = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_task_detail);
        _context = TaskDetailActivity.this;

        _uploadManager = new UploadManager();

        _swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

        _swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

        _swipeRefreshLayout.setOnRefreshListener(this);

        _assignActionLayout = (RelativeLayout) findViewById(R.id.detail_assign_action_layout);
        _assignAction = (TextView) findViewById(R.id.detail_assign_action);
        _assignCostPrice = (TextView) findViewById(R.id.detail_price_cost);
        _assignAction.setOnClickListener(this);

        _navigationTopBar = (NavigationTopBar) getSupportFragmentManager().findFragmentByTag(NavigationTopBar.class.getSimpleName());
        _navigationTopBar.setViewVisibility(NavigationTopBar.NAVIGATION_VIEWS.RIGHT, View.GONE);
        _navigationTopBar.setViewVisibility(NavigationTopBar.NAVIGATION_VIEWS.RIGHT_BARGE_TEXT, View.GONE);
        _navigationTopBar.setViewVisibility(NavigationTopBar.NAVIGATION_VIEWS.LEFT, View.VISIBLE);
        _navigationTopBar.setText(NavigationTopBar.NAVIGATION_VIEWS.TITLE, R.string.activity_task_detail_title);
        _navigationTopBar.setClickListener(NavigationTopBar.NAVIGATION_VIEWS.LEFT, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        _recyclerView = (RecyclerView) findViewById(R.id.detail_order_recycle_view);
        _recyclerView.setLayoutManager(new LinearLayoutManager(_context));

        DividerItemDecoration itemDecoration = new DividerItemDecoration(_context, LinearLayoutManager.VERTICAL, R.drawable.recycle_item_divider_8);
        _recyclerView.addItemDecoration(itemDecoration);

        _orderAdapter = new OrderAdapter(_context, _orders);

        _orderAdapter.setOrderActionClickListener(new OrderAdapter.OrderActionClickListener() {
            @Override
            public void onItemClick(Order order) {
                Intent intent = new Intent(_context, OrderDetailActivity.class);
                intent.putExtra(Constants.ASSIGN_ID, _task.getAssignId());
                intent.putExtra(Constants.ORDER_NO, order.getOrderCode());
                startActivity(intent);
            }
//            @Override
//            public void onPostExceptionClick(Order order) {
//                Intent intent = new Intent(TaskDetailActivity.this, PostExceptionActivity.class);
//                intent.putExtra(Constants.EXCEPTION_ID, _task.getAssignId());
//                intent.putExtra(Constants.EXCEPTION_NO, order.getOrderCode());
//                intent.putExtra(Constants.EXCEPTION_TYPE, 2);
//                startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
//            }
//
//            @Override
//            public void onOrderStatusClick(final Order order, final OperateBtn operateBtn) {
//                handlerOperateBtn(order, operateBtn);
//            }
//
//            @Override
//            public void onCheckFileClick(Order order) {
//                Intent intent = new Intent(TaskDetailActivity.this, FileListActivity.class);
//                intent.putExtra(Constants.FILE_LIST, (Serializable) order.getFileList());
//                startActivity(intent);
//            }
//
//            @Override
//            public void onCallPhoneClick(final String phoneNumber) {
//                UIUtils.showPromptDialog(_context, null, phoneNumber, "呼叫", "取消",
//                        null,
//                        new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                IntentUtils.call(TaskDetailActivity.this, phoneNumber);
//                            }
//                        }, true);
//            }
        });

        String assignId = getIntent().getStringExtra(Constants.ASSIGN_ID);
        getOrderDetail(assignId);
    }

    private void setHeader(RecyclerView view, Task task, List<Order> orders) {
        View header = LayoutInflater.from(this).inflate(R.layout.view_header_assign, view, false);
        TextView assignIdText = (TextView) header.findViewById(R.id.detail_assign_id);
        TextView orderCountsText = (TextView) header.findViewById(R.id.detail_order_counts);
        TextView assignStatusText = (TextView) header.findViewById(R.id.detail_assign_status);
        TextView assignTypeText = (TextView) header.findViewById(R.id.detail_assign_type_name);
        TextView pickTimeText = (TextView) header.findViewById(R.id.detail_assign_pickup_time);
        TextView deliverTimeText = (TextView) header.findViewById(R.id.detail_assign_delivery_time);
        TextView totalNumText = (TextView) header.findViewById(R.id.detail_assign_total_num);
        TextView totalWeightText = (TextView) header.findViewById(R.id.detail_assign_total_weight);
        TextView exceptionMsgText = (TextView) header.findViewById(R.id.detail_assign_exception_msg);
        TextView addressText = (TextView) header.findViewById(R.id.detail_address);


        if (task.getHasException() == 1) { //有一场
            if (task.getExceptionMsg() != null && !task.getExceptionMsg().isEmpty()) {
                exceptionMsgText.setVisibility(View.VISIBLE);
                exceptionMsgText.setText(task.getExceptionMsg());
            }
        }

        orderCountsText.setText(String.format(getString(R.string.detail_text_order_number), orders.size()));
        assignStatusText.setText(task.getTransStatusName());
        assignIdText.setText(String.format(getString(R.string.detail_text_assign_code), task.getAssignCode()));
        assignTypeText.setText(String.format(getString(R.string.detail_text_assign_type), task.getSupervisedStatusName()));
        pickTimeText.setText(task.getPickupTimeStr());
        deliverTimeText.setText(task.getDeliveryTimeStr());
        _assignCostPrice.setText(JavaUtils.formatNumber(task.getDriverCostPrice()));
//        pickTimeText.setText(String.format(getString(R.string.detail_text_pick_up_time), task.getPickupTimeStr()));
//        deliverTimeText.setText(String.format(getString(R.string.detail_text_deliver_time), task.getDeliveryTimeStr()));
        totalNumText.setText(String.format(getString(R.string.detail_text_total_number), task.getTotalNumber()));
        totalWeightText.setText(String.format(getString(R.string.detail_text_total_weight), String.valueOf(task.getTotalWeight())));
        addressText.setText(task.getTransCompanyName());

        _orderAdapter.setHeaderView(header);
    }

    private void setFooter(RecyclerView view, List<AssignOrderLog> logs) {
        View footer = LayoutInflater.from(this).inflate(R.layout.view_footer_logs, view, false);

        final StepViewLayout logsStepView = (StepViewLayout) footer.findViewById(R.id.footer_logs_step_view);
        initLogsStepView(logsStepView, logs);

        LinearLayout expandAction = (LinearLayout) footer.findViewById(R.id.logs_expand_action);

//        expandAction.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                int lastItem = ((LinearLayoutManager) _recyclerView.getLayoutManager()).findLastVisibleItemPosition();
//
//                if (logsStepView.getVisibility() == View.GONE) {
//                    logsExpandImage.setImageResource(R.drawable.icon_top_arrow);
//                    logsStepView.setVisibility(View.VISIBLE);
//
//                    moveToPosition((LinearLayoutManager) _recyclerView.getLayoutManager(), lastItem);
//                } else {
//                    logsExpandImage.setImageResource(R.drawable.icon_bottom_arrow);
//                    logsStepView.setVisibility(View.GONE);
//
//                    moveToPosition((LinearLayoutManager) _recyclerView.getLayoutManager(), lastItem - 1);
//                }
//            }
//        });
        _orderAdapter.setFooterView(footer);
    }

    public void moveToPosition(LinearLayoutManager manager, int n) {
//        manager.scrollToPositionWithOffset(n, 0);
//        manager.setStackFromEnd(true);
    }

    @Override
    public void takeSuccess(TResult result) {
        Log.i(TAG,"takeSuccess：" + result.getImage().getCompressPath());
        _photosData.addAll(result.getImages()) ;
        uploadImagesToServer(result.getImages());

    }

    private void initLogsStepView(StepViewLayout stepViewLayout, List<AssignOrderLog> logs) {
        final List<StepItemData> log_datas = new ArrayList<>();

        for (int i = logs.size() - 1; i >= 0; i --) {
            StepItemData log_data = new StepItemData();
            log_data.setMsg(logs.get(i).getContent());
            log_data.setDate(logs.get(i).getLogTimeStr());
            log_data.setLogType(logs.get(i).getLogType());

//            List<FileInfo> fileInfos = new ArrayList<>();
//            for (int j = 0; j < 10; j ++) {
//                FileInfo fileInfo = new FileInfo();
//                fileInfo.setFileUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488690978374&di=81239c11bd0851379e9415d40ab55f6c&imgtype=0&src=http%3A%2F%2Fwww.sdshangcai.com%2Fuploads%2F1459575085.jpg");
//                fileInfos.add(fileInfo);
//                log_data.setFileList(fileInfos);
//            }

            log_data.setFileList(logs.get(i).getFileList());
            log_datas.add(log_data);
        }

        stepViewLayout.setDataAndView(log_datas, R.layout.custom_logs_text_layout, new StepViewLayout.InflateContentListener() {
            @Override
            public void onContentInflate(int position, View contentView) {
                StepItemData data = log_datas.get(position);
                TextView topLogText = (TextView) contentView.findViewById(R.id.top_log_text);
                topLogText.setText(data.getMsg());

                TextView bottomLogText = (TextView) contentView.findViewById(R.id.bottom_log_text);
                bottomLogText.setVisibility(View.VISIBLE);
                bottomLogText.setText(data.getDate());

                if (data.getFileList() != null && data.getFileList().size() > 0) {
                    RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.logs_photo_list);

                    GridLayoutManager gridLayoutManager = new GridLayoutManager(_context, 5);
                    recyclerView.setLayoutManager(gridLayoutManager);
                    recyclerView.addItemDecoration(new GridSpacingItemDecoration(5, 10, false));
                    LogPhotoAdapter logPhotoAdapter = new LogPhotoAdapter(_context, data.getFileList());
                    logPhotoAdapter.setLogPhotoItemClickListener(new LogPhotoAdapter.LogPhotoItemClickListener() {
                        @Override
                        public void onItemClick(List<FileInfo> fileInfos, int position) {
                            ArrayList<String> data = new ArrayList<>();
                            for (int i = 0; i < fileInfos.size(); i ++) {
                                data.add(fileInfos.get(i).getFileUrl());
                            }

                            PhotoPreviewIntent intent = new PhotoPreviewIntent(_context);
                            intent.setCurrentItem(position);
                            intent.setPhotoPaths(data);
                            startActivity(intent);
                        }
                    });

                    recyclerView.setAdapter(logPhotoAdapter);
                }

                if (data.getLogType() == 2) {
                    topLogText.setTextColor(getResources().getColor(R.color.colorAccent));
                    bottomLogText.setTextColor(getResources().getColor(R.color.colorAccent));
                }
            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(com.jph.takephoto.R.string.msg_operation_canceled));
    }

    private ArrayList<Order> generateData() {
        ArrayList<Order> orders = new ArrayList<>();

        for (int i = 0; i < 10; i ++) {
            Order order = new Order();
            order.setOrderCode("FX-1021321312");

            orders.add(order);
        }

        return orders;
    }

    public void setAssignView(final Task task, final List<AssignOrderLog> logs, final List<Order> orders) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setHeader(_recyclerView, task, orders);
                setFooter(_recyclerView, logs);

                _recyclerView.setAdapter(_orderAdapter);
            }
        });
    }

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    protected int getFragmentContentId() {
        return 0;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.detail_assign_action: //确认运单、发布异常
                UIUtils.showPromptDialog(_context, "提示", "是否确认运单", "确定", "取消",
                        null,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Location location = BLocationManager.getInstance().getLatestLocation();
                                confirmOrder(_task, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));

                            }
                        }, true);

//                if (_assignAction.getText().toString().equals("确认运单")) {
//                    UIUtils.showPromptDialog(_context, "提示", "是否确认运单", "确定", "取消",
//                            null,
//                            new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    Location location = BLocationManager.getInstance().getLatestLocation();
//                                    confirmOrder(_task, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
//
//                                }
//                            }, true);
//                } else if (_assignAction.getText().toString().equals("发布异常")) {
//                    Intent intent = new Intent(TaskDetailActivity.this, PostExceptionActivity.class);
//                    intent.putExtra(Constants.EXCEPTION_ID, _task.getAssignId());
//                    intent.putExtra(Constants.EXCEPTION_NO, _task.getAssignCode());
//                    intent.putExtra(Constants.EXCEPTION_TYPE, 1);
//                    startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
//                }

                break;
        }
    }

    @Override
    public void onRefresh() {
        getOrderDetail(_task.getAssignId());
    }

    //运单状态枚举
    public enum ASSIGN_STATUS {
        UN_CONFIRM, CONFIRMED, PICKING, RUNNING, COMPLETED, EXCEPTION, ACTIONS
    }

    public enum ORDER_STATUS {

    }

    //运单状态改变逻辑
    private void changeAssignStatus(ASSIGN_STATUS assign_status) {

        _currentAssignStatus = assign_status;

        switch (assign_status) {
            case UN_CONFIRM:
                _assignActionLayout.setVisibility(View.VISIBLE);
//                _assignAction.setText("确认运单");
                break;

            case CONFIRMED:
                _assignActionLayout.setVisibility(View.GONE);
//                _assignAction.setText("发布异常");
                break;

            case COMPLETED:
                _assignActionLayout.setVisibility(View.GONE);
//                _assignAction.setText("订单完成");
                break;

            case ACTIONS:

                _assignActionLayout.setVisibility(View.GONE);
//                _assignAction.setText("发布异常");
                break;
        }
    }

    public ASSIGN_STATUS getCurrentAssignStatus() {
        return _currentAssignStatus;
    }

    private List<Order> handlerExpand(List<Order> orders) {

        for (int i = 0; i < _orderAdapter.getData().size(); i ++) {
            for (int j = 0; j < orders.size(); j ++) {
                if (_orderAdapter.getData().get(i).getOrderCode().equals(orders.get(j).getOrderCode())) {
                    orders.get(j).setIsExpand(_orderAdapter.getData().get(i).getIsExpand());
                }
            }
        }

        return orders;
    }

    private void handlerOperateBtn(final Order order, final OperateBtn operateBtn) {
        final Location location = BLocationManager.getInstance().getLatestLocation();
        _currentOrder = order;
        _currentOperateBtn = operateBtn;

        switch (operateBtn.getBtnType()) {
            case Constants.HAS_PICK_FILE://已取文件
                UIUtils.showPromptDialog(_context, "提示", "确定已取文件？", "是", "否", null,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                        operateBtn.getBtnType(), -1, new JsonArray());
                            }
                        }, true);

                break;

            case Constants.HAS_REACH_PICK://到达提货地
                UIUtils.showPromptDialog(_context, "提示", "确定到达提货地？", "是", "否", null,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                        operateBtn.getBtnType(), -1, new JsonArray());
                            }
                        }, true);
                break;
            case Constants.FINISH_PICKUP_GOODS://完成提货
                UIUtils.showPromptDialog(_context, "提示", "确定完成提货？", "是", "否",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        },
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                        operateBtn.getBtnType(), -1, new JsonArray());
                            }
                        }, true);
                break;
            case Constants.FINISH_PICKUP_GOODS_OK://完成提货

                UIUtils.showPromptDialog(_context, "货物破损？", "上传破损图片", "无破损", "上传",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Intent intent = new Intent(TaskDetailActivity.this, PostExceptionActivity.class);
                            intent.putExtra(Constants.EXCEPTION_ID, _task.getAssignId());
                            intent.putExtra(Constants.EXCEPTION_NO, order.getOrderCode());
                            intent.putExtra(Constants.EXCEPTION_DETAIL, "CARGO_BROKEN");
                            intent.putExtra(Constants.EXCEPTION_TYPE, 2);
                            intent.putExtra(Constants.EXCEPTION_OPERATE_TYPE, operateBtn.getBtnType());
                            startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
                        }
                    },
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                    operateBtn.getBtnType(), 1, new JsonArray());
                        }
                    }, true);
                break;

            case Constants.REACH_TERMINAL://到达场站
                UIUtils.showPromptDialog(_context, "提示", "确定到达场站？", "是", "否",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        },
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                        operateBtn.getBtnType(), -1, new JsonArray());
                            }
                        }, true);
                break;

            case Constants.FOR_INSPECTION://入查验库
                UIUtils.showPromptDialog(_context, "提示", "确定入查验库？", "是", "否", null,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                        operateBtn.getBtnType(), -1, new JsonArray());
                            }
                        }, true);
                break;

            case Constants.HAS_DELIVERED://到达送货地
                UIUtils.showPromptDialog(_context, "提示", "确定到达送货地？", "是", "否", null,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                        operateBtn.getBtnType(), -1, new JsonArray());
                            }
                        }, true);
                break;

            case Constants.HAS_COMPLETED://完成送货,上传单证
                UIUtils.showPromptDialog(_context, "提示", "请上传客户签收单？", "是", "否",
                        null,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                                Uri imageUri = Uri.fromFile(file);
                                CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
                                getTakePhoto().onEnableCompress(compressConfig, true);
                                getTakePhoto().onPickFromCapture(imageUri);

                            }
                        }, true);
                break;

            case Constants.HAS_COMPLETED_GOODS_OK://完成送货，货物是否完损
                UIUtils.showPromptDialog(_context, "货物破损？", "上传破损图片", "无破损", "上传",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(TaskDetailActivity.this, PostExceptionActivity.class);
                            intent.putExtra(Constants.EXCEPTION_ID, _task.getAssignId());
                            intent.putExtra(Constants.EXCEPTION_NO, order.getOrderCode());
                            intent.putExtra(Constants.EXCEPTION_DETAIL, "CARGO_BROKEN");
                            intent.putExtra(Constants.EXCEPTION_TYPE, 2);
                            intent.putExtra(Constants.EXCEPTION_OPERATE_TYPE, operateBtn.getBtnType());
                            startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
                        }
                    },
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            final Location location = BLocationManager.getInstance().getLatestLocation();
                            operateOrder(_task.getAssignId(), order.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                    operateBtn.getBtnType(), 1, new JsonArray());



                        }
                    }, false);
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelCheckUploadProgressTimeTask();
    }

    private void getOrderDetail(String assignId) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {

                Task task = ParseJsonUtils.getObjectFromJson(o.data.getAsJsonObject(), Task.class);
                List<AssignOrderLog> logs = task.getAssignOrderLogs();
                List<Order> orders = task.getOrdersList();

                handlerExpand(orders);
                _orderAdapter.setData(orders);
                setAssignView(task, logs, orders);

                _task = task;

                if (task.getTransStatus().equals(Constants.TRANS_TYPE_DQR)) {
                    changeAssignStatus(ASSIGN_STATUS.UN_CONFIRM);
                }else if (task.getTransStatus().equals(Constants.TRANS_TYPE_YQR)) {
                    changeAssignStatus(ASSIGN_STATUS.CONFIRMED);
                } else if (task.getTransStatus().equals(Constants.TRANS_TYPE_YWC)) {
                    changeAssignStatus(ASSIGN_STATUS.COMPLETED);
                } else {
                    changeAssignStatus(ASSIGN_STATUS.ACTIONS);

                }
                if (AppHelper.isApkDebugable(_context))
                    UIUtils.showToastMessage(_context, "获取详情成功！");

                _swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                if (e.toString().contains("3002")) {
//                    AppHelper.restartApplication(_context);
//                }
                _swipeRefreshLayout.setRefreshing(false);
                if (AppHelper.isApkDebugable(_context))
                    UIUtils.showToastMessage(_context, "获取详情失败！");
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_ORDER_DETAIL, ss,
                HttpData.getAssignDetailData(assignId));
    }

    private void operateOrder(String assignId, String orderCode, double lat, double lng,
                              String operateType, Integer isGoodsFine, JsonArray fileList) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {

                _uploadManager.clearUploadData();
                getOrderDetail(_task.getAssignId());
                UIUtils.showToastMessage(_context, "操作成功！");
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                _uploadManager.clearUploadData();
//                if (e.toString().contains("3002")) {
//                    AppHelper.restartApplication(_context);
//                }
                UIUtils.showToastMessage(_context, "操作失败！");
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_ORDER_OPERATE, ss,
                HttpData.getOperateOrdersData(assignId, orderCode, lat, lng, operateType, isGoodsFine, fileList));
    }

    private void confirmOrder(final Task task, String lat, String lng) {
        MySubscriber<NetMessageVO> ss = new MySubscriber<NetMessageVO>() {
            @Override
            public void onNext(NetMessageVO o) {
                UIUtils.showToastMessageShortly(_context, "确认运单成功");
                getOrderDetail(task.getAssignId());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                if (e.toString().contains("3002")) {
//                    AppHelper.restartApplication(_context);
//                }
                UIUtils.showToastMessage(_context, "确认运单失败！");
            }
        };

        CarApiManager.getInstance().sendRequest(HttpData.InterfacesURL.ASSIGN_ORDER_CONFIRM, ss,
                HttpData.getConfirmOrderData(task.getAssignId(), lat, lng));
    }

    private void uploadImagesToServer(final ArrayList<TImage> list) {
        if (list != null && list.size() > 0) {
            if (list.size() == 1) {
                _uploadManager.sendRequestForUpload(new File(list.get(0).getCompressPath()), new UploadManager.UploadCallBack() {
                    @Override
                    public void onSuccess(String fileId) {
                        _uploadManager.putSuccessUploadImage(list.get(0).getCompressPath(), fileId);
                        handlerCompleteLogic();
                    }

                    @Override
                    public void onError() {
                        UIUtils.showToastMessageShortly(_context, "上传失败！");
                    }
                });
                _uploadManager.addImage(list.get(0).getCompressPath());
            }
        }
//        startCheckUploadProgressTimerTask();
        showProgressDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constants.POST_EXCEPTION_CODE) {
            getOrderDetail(_task.getAssignId());
        }
    }

    private void handlerCompleteLogic() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissProgressDialog();
                final Location location = BLocationManager.getInstance().getLatestLocation();
                operateOrder(_task.getAssignId(), _currentOrder.getOrderCode(), location.getLatitude(), location.getLongitude(),
                        _currentOperateBtn.getBtnType(), 1, getPhotoNameFromData());

                _photosData.clear();
            }
        });

//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                UIUtils.showPromptDialog(_context, "提示", "是否继续上传签收单？", "是", "否",
//                        new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                UIUtils.showPromptDialog(_context, "提示", "货物是否完好无损？", "是", "否",
//                                        new View.OnClickListener() {
//                                            @Override
//                                            public void onClick(View view) {
//
//                                                Intent intent = new Intent(TaskDetailActivity.this, PostExceptionActivity.class);
//                                                intent.putExtra(Constants.EXCEPTION_ID, _task.getAssignId());
//                                                intent.putExtra(Constants.EXCEPTION_NO, _currentOrder.getOrderCode());
//                                                intent.putExtra(Constants.EXCEPTION_DETAIL, "CARGO_BROKEN");
//                                                intent.putExtra(Constants.EXCEPTION_TYPE, 2);
//                                                startActivity(intent);
//                                                _photosData.clear();
//
//                                            }
//                                        },
//                                        new View.OnClickListener() {
//                                            @Override
//                                            public void onClick(View view) {
//
////                                                Log.d(TAG, "handlerCompleteLogic getBtnType --> " + _currentOperateBtn.getBtnType());
////                                                Log.d(TAG, "handlerCompleteLogic getPhotoNameFromData --> " + getPhotoNameFromData());
//                                                final Location location = BLocationManager.getInstance().getLatestLocation();
//                                                operateOrder(_task.getAssignId(), _currentOrder.getOrderCode(), location.getLatitude(), location.getLongitude(),
//                                                        _currentOperateBtn.getBtnType(), 1, getPhotoNameFromData());
//
//                                                _photosData.clear();
//
//                                            }
//                                        }, false);
//                            }
//                        },
//                        new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
//                                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
//                                Uri imageUri = Uri.fromFile(file);
//                                CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
//                                getTakePhoto().onEnableCompress(compressConfig, true);
//                                getTakePhoto().onPickFromCapture(imageUri);
//
//
//                            }
//                        }, false);
//            }
//        });
    }

    private JsonArray getPhotoNameFromData() {
        ArrayList<String> data = new ArrayList<>();

        for (int i = 0; i < _photosData.size(); i ++) {
            data.add(_photosData.get(i).getCompressPath());
        }

        ArrayList<UploadFile> uploadFiles = _uploadManager.getFinalUploadedImages(data);
        JsonArray photos = new JsonArray();
        for (int i = 0; i < uploadFiles.size(); i++) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("fileId", uploadFiles.get(i).getFileId().toString());
            photos.add(jsonObject);
        }

        return photos;
    }

    private void startCheckUploadProgressTimerTask() {
        if (mCheckUploadProgressTimerTask == null) {
            mCheckUploadProgressTimerTask = new TimerTask() {
                @Override
                public void run() {
                    Log.d(TAG, "startCheckUploadProgressTimerTask");
                    if (_uploadManager.isUpLoadEnd()) {

                        final Location location = BLocationManager.getInstance().getLatestLocation();
                        switch (_currentOperateBtn.getBtnType()) {
                            case Constants.FINISH_PICKUP_GOODS:
                                operateOrder(_task.getAssignId(), _currentOrder.getOrderCode(), location.getLatitude(),
                                        location.getLongitude(), _currentOperateBtn.getBtnType(), 0, getPhotoNameFromData());
                                break;

                            case Constants.HAS_COMPLETED:
                                UIUtils.showPromptDialog(_context, "货物破损？", "上传破损图片", "无破损", "上传",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                Intent intent = new Intent(TaskDetailActivity.this, PostExceptionActivity.class);
                                                intent.putExtra(Constants.EXCEPTION_ID, _task.getAssignId());
                                                intent.putExtra(Constants.EXCEPTION_NO, _currentOrder.getOrderCode());
                                                intent.putExtra(Constants.EXCEPTION_DETAIL, "CARGO_BROKEN");
                                                intent.putExtra(Constants.EXCEPTION_TYPE, 2);
                                                startActivityForResult(intent, Constants.POST_EXCEPTION_CODE);
                                            }
                                        },
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {

                                                operateOrder(_task.getAssignId(), _currentOrder.getOrderCode(), location.getLatitude(), location.getLongitude(),
                                                        _currentOperateBtn.getBtnType(), 1, getPhotoNameFromData());


                                            }
                                        }, true);
                                break;
                        }

                        dismissProgressDialog();
                        cancelCheckUploadProgressTimeTask();
                    }
                }
            };
            mCheckUploadProgressTimer = new Timer();
            mCheckUploadProgressTimer.schedule(mCheckUploadProgressTimerTask, 0, 1000);
        }
    }

    public void cancelCheckUploadProgressTimeTask() {
        Log.d(TAG, "cancelCheckUploadProgressTimeTask");
        if (mCheckUploadProgressTimerTask != null) {
            mCheckUploadProgressTimerTask.cancel();
        }
        if (mCheckUploadProgressTimer != null) {
            mCheckUploadProgressTimer.cancel();
            mCheckUploadProgressTimer.purge();
        }

        mCheckUploadProgressTimerTask = null;
        mCheckUploadProgressTimer = null;
    }

    private void showProgressDialog() {
        _progressDialog = ProgressDialog.show(_context, "提示", "正在上传照片", false, false);
    }

    private void dismissProgressDialog() {
        _progressDialog.dismiss();
    }
}
