package com.sipai.jspatrol.Fault;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.Fault;
import com.sipai.jspatrol.Bean.Maintenance;
import com.sipai.jspatrol.Bean.Picture;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.Bean.User;
import com.sipai.jspatrol.BuildConfig;
import com.sipai.jspatrol.Fault.adapter.PicAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.vansz.glideimageloader.GlideImageLoader;

import net.bither.util.NativeUtil;

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

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DoingFaultDetailActivity extends AppCompatActivity implements View.OnClickListener{

    private Fault mFault;
    private Button btn_sign_in,btn_sub;
    //异常详情
    private TextView tv_area,tv_equ_detail,tv_content,tv_date,tv_man;
    private LinearLayout ll_equ;
    //实施详情
    private TextView tv_show_area,tv_show_equ,tv_show_description,tv_show_content,tv_show_remark,tv_show_date,tv_show_man;
    private RecyclerView rc_show;
    private LinearLayout ll_show;
    //编辑模块
    private EditText edt_question_description,edt_dispose_content,edt_maintenance_date;
    private TextView tv_processsection,tv_equ,tv_receiver;
    private LinearLayout ll_edit;
    private List<ProcessSection> areas = new ArrayList<>();
    private EquList sel_equ;
    private ProcessSection sel_ps;
    private String sel_equs_id = "";
    private List<User> receivers = new ArrayList<>();
    private List<User> sel_receivers = new ArrayList<>();
    private String st_sel_receiver_id = "";
    private static final int SEND_RECEIVERS = 131;
    private String mseriverip;
    private Calendar cal;
    private int year,month,day,hour,minute;
    private RecyclerView rc_fault_pic;
    private List<Picture> pics = new ArrayList<>();
    private List<Picture> pics_show = new ArrayList<>();
    private PicAdapter picAdapter;
    private LinearLayoutManager stmanager;
    private GridView gv_pic;
    private Dialog ddialog;
    private SweetAlertDialog pDialog;
    private static final int UPIMG = 10;
    private final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static final int SELEQU = 104;
    private static final int SELPS = 8;//选择工艺段
    // 获取sd卡根目录地址,并创建图片父目录文件对象和文件的对象;
    private List<Map<String, Object>> datas;
    private GridViewAddImgesAdpter gridViewAddImgesAdpter;
    String file_str = Environment.getExternalStorageDirectory().getPath();
    File mars_file = new File(file_str + "/my_camera");
    File file_go = new File(file_str + "/my_camera/"+System.currentTimeMillis()+".jpg");
    private final String IMAGE_DIR = Environment.getExternalStorageDirectory() + "/gridview/";
    private Transferee transferee;
    private Spinner etrepairway;
    private String[] repway = {"in","out"};
    private EditText edt_actualMoney;
    private EditText edt_workinghours;
    private TextView tv_planMoney;
    private String pc_id,pc_processid,pc_handledetail,pc_taskid,pc_unitid,pc_businessid,pc_taskdefinitionkey;
    private Button btn_big_sub;

    public static void actionStart(Context context, Fault fault){
        Intent intent = new Intent(context, DoingFaultDetailActivity.class);
        intent.putExtra("fault",fault);
        context.startActivity(intent);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPIMG:
                    photoPath(msg.obj.toString());
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doing_fault_detail);
        init();
        getNowData();
        initView();
        if (!mFault.getTodoTask().contains("验收")) {
            getReceiver();
//            //修改后获取故障详情
//            showDefectAdjust();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getDetail();
            }
        }, 1000);
    }

    private void getReceiver() {
        HashMap<String,String> map = new HashMap<>();
        map.put("search_pid",mBizid);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETUSERLISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                if (!DoingFaultDetailActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("人员列表获取失败，请重试！")
                                    .setConfirmText("重试")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getReceiver();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                receivers = parseReceiver(res);
            }
        });
    }

    private List<User> parseReceiver(String response) {
        List<User> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews = new JSONArray(jsonObject.getString("rows"));
            for (int i=0;i<aNews.length();i++){
                User item = new User();
                item.setId(aNews.getJSONObject(i).get("id").toString());
                item.setCaption(aNews.getJSONObject(i).get("caption").toString());
                item.setName(aNews.getJSONObject(i).get("name").toString());
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
    }

    /*
        根据缺陷id获取图片
         */
    private void getDetail() {
        HashMap<String,String> map = new HashMap<>();
        map.put("maintenanceDetailId",mFault.getId());
        map.put("tbName","tb_maintenance_problem_fille");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetFaultTodoPics_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadPicFail(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pics = getPicData(res);
                updatePic();
            }
        });
    }

    private void loadPicFail(IOException e) {
        if (!DoingFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DoingFaultDetailActivity.this, "图片获取失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void updatePic() {
        if (!DoingFaultDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (pics.size()>0) {
                        List<String> ivUrls = new ArrayList<>();
                        for (int i=0;i<pics.size();i++){
                            ivUrls.add(pics.get(i).getAbspath());
                        }
                        TransferConfig config = TransferConfig.build()
                                .setSourceUrlList(ivUrls)
                                .setDuration(350)
                                .setImageLoader(GlideImageLoader.with(getApplicationContext()))
                                .bindRecyclerView(rc_fault_pic, R.id.moudle_item_show_pic_iv);
                        rc_fault_pic.setVisibility(View.VISIBLE);
                        picAdapter = new PicAdapter(pics, DoingFaultDetailActivity.this, new PicAdapter.PicAdapterOnClickListener() {
                            @Override
                            public void onItemClick(View v, int position) {
                                config.setNowThumbnailIndex(position);
                                transferee.apply(config).show();
                            }
                        });
                        rc_fault_pic.setAdapter(picAdapter);
                        stmanager = new LinearLayoutManager(DoingFaultDetailActivity.this);
                        stmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        rc_fault_pic.setLayoutManager(stmanager);
                    }else {
                        rc_fault_pic.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    private void getSubDetailPic(String id) {
        HashMap<String,String> map = new HashMap<>();
        map.put("masterId",id);
        map.put("tbName","tb_maintenance_file");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetSubDetailPics_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadPicFail(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                pics_show = getSubPicData(res);
                if (!DoingFaultDetailActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (pics_show.size() > 0) {
                                List<String> ivUrls = new ArrayList<>();
                                for (int i=0;i<pics_show.size();i++){
                                    ivUrls.add(pics_show.get(i).getAbspath());
                                }
                                TransferConfig config = TransferConfig.build()
                                        .setSourceUrlList(ivUrls)
                                        .setDuration(350)
                                        .setImageLoader(GlideImageLoader.with(getApplicationContext()))
                                        .bindRecyclerView(rc_fault_pic, R.id.moudle_doing_fault_detail_rc_show_pic);
                                rc_show.setVisibility(View.VISIBLE);
                                picAdapter = new PicAdapter(pics_show, DoingFaultDetailActivity.this, new PicAdapter.PicAdapterOnClickListener() {
                                    @Override
                                    public void onItemClick(View v, int position) {
                                        config.setNowThumbnailIndex(position);
                                        transferee.apply(config).show();
                                        transferee.setOnTransfereeStateChangeListener(new Transferee.OnTransfereeStateChangeListener() {
                                            @Override
                                            public void onShow() {

                                            }

                                            @Override
                                            public void onDismiss() {
                                                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
                                            }
                                        });
                                    }
                                });
                                rc_show.setAdapter(picAdapter);
                                stmanager = new LinearLayoutManager(DoingFaultDetailActivity.this);
                                stmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
                                rc_show.setLayoutManager(stmanager);
                            } else {
                                rc_show.setVisibility(View.GONE);
                            }
                        }
                    });
                }
            }
        });
//        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
//        RequestParams params = new RequestParams();
//        params.put("masterId",id);
//        params.put("tbName","tb_maintenance_file");
//        AsyncHttpClient client = new AsyncHttpClient();
//        client.setCookieStore(myCookieStore);
//        client.post(mServer+"base/getInputFileList.do?", params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(String response) {
//                String a = response;
//                pics_show = getSubPicData(response);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (pics_show.size()>0) {
//                            picAdapter = new PicAdapter(pics_show, DoingFaultDetailActivity.this);
//                            rc_show.setAdapter(picAdapter);
//                            stmanager = new LinearLayoutManager(DoingFaultDetailActivity.this);
//                            stmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
//                            rc_show.setLayoutManager(stmanager);
//                        }else {
//                            rc_show.setVisibility(View.GONE);
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void onStart() {
//                super.onStart();
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//            }
//
//            @Override
//            public void onFailure(final Throwable error) {
//                super.onFailure(error);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(DoingFaultDetailActivity.this, "图片获取失败："+error.toString(), Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//        });
    }

    private List<Picture> getSubPicData(String response) {
        List<Picture> list = new ArrayList<>();
        try {
            JSONArray aNews = new JSONArray(response);
            for (int i=0;i<aNews.length();i++){
                Picture item = new Picture();
                item.setId(aNews.getJSONObject(i).get("id").toString());
                String abs = aNews.getJSONObject(i).get("abspath").toString();
                String url = "http://"+mseriverip.substring(0,mseriverip.length())+"////UploadFile////MaintenanceFile////"+abs.substring(abs.lastIndexOf("\\")+1,abs.length());
                item.setAbspath(url);
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private List<Picture> getPicData(String response) {
        List<Picture> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews = new JSONArray(jsonObject.get("content1").toString());
            for (int i=0;i<aNews.length();i++){
                Picture item = new Picture();
                item.setId(aNews.getJSONObject(i).get("id").toString());
                String abs = aNews.getJSONObject(i).get("abspath").toString();
                String url = "http://"+mseriverip.substring(0,mseriverip.length())+"////UploadFile////MaintenanceProblem////"+abs.substring(abs.lastIndexOf("\\")+1,abs.length());
                item.setAbspath(url);
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void getNowData() {
        cal=Calendar.getInstance();
        year=cal.get(Calendar.YEAR);       //获取年月日时分秒
        month=cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day=cal.get(Calendar.DAY_OF_MONTH);
        hour = cal.get(Calendar.HOUR_OF_DAY);
        minute = cal.get(Calendar.MONTH);
    }

    private void initView() {
        TextView tv_title = findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("缺陷详情");
        ImageView btn_back = findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setTitleText("数据上传中...");
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(true);
        ll_edit = findViewById(R.id.moudle_doing_fault_detail_ll_edit);
        //按钮
        btn_sign_in = findViewById(R.id.moudle_doing_fault_detail_btn_sign_in);
        btn_sign_in.setOnClickListener(this);
        btn_sub = findViewById(R.id.moudle_doing_fault_detail_btn_sub);
        btn_sub.setOnClickListener(this);
        btn_big_sub = findViewById(R.id.moudle_doing_fault_detail_btn_big_sub);
        btn_big_sub.setOnClickListener(this);
        tv_planMoney = findViewById(R.id.moudle_doing_fault_detail_tv_planMoney);
        edt_actualMoney = findViewById(R.id.moudle_doing_fault_detail_edt_actualMoney);
        edt_workinghours = findViewById(R.id.moudle_doing_fault_detail_edt_workinghours);
        //详情
        tv_area = findViewById(R.id.moudle_doing_fault_detail_tv_area);
        ll_equ = findViewById(R.id.moudle_doing_fault_detail_ll_equ);
        tv_equ_detail = findViewById(R.id.moudle_doing_fault_detail_tv_equ_detail);
        tv_content = findViewById(R.id.moudle_doing_fault_detail_tv_content);
//        tv_remark = findViewById(R.id.moudle_doing_fault_detail_tv_remark);
        tv_date = findViewById(R.id.moudle_doing_fault_detail_tv_date);
        tv_man = findViewById(R.id.moudle_doing_fault_detail_tv_man);

        //编辑
        edt_question_description = findViewById(R.id.moudle_doing_fault_detail_edt_question_description);
        edt_dispose_content = findViewById(R.id.moudle_doing_fault_detail_edt_dispose_content);
        edt_maintenance_date = findViewById(R.id.moudle_doing_fault_detail_edt_maintenance_date);
        //在TextView上显示日期
        String smonth = "";
        String sday = "";
        String shour = "";
        String smin = "00";
        //在TextView上显示日期
        if (month<9){
            smonth = "0"+String.valueOf(month+1);
        }else {
            smonth = String.valueOf(month+1);
        }
        if (day<10){
            sday = "0"+String.valueOf(day);
        }else {
            sday = String.valueOf(day);
        }
        if (hour<10){
            shour = "0"+String.valueOf(hour);
        }else {
            shour = String.valueOf(hour);
        }
        edt_maintenance_date.setText(year+"-"+smonth+"-"+sday+" "+shour+":"+"00:00");
        edt_maintenance_date.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //创建DatePickerDialog对象
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    DatePickerDialog dpd = new DatePickerDialog(DoingFaultDetailActivity.this, Datelistener, year, month, day);
                    dpd.show();//显示DatePickerDialog组件
                }
                return false;
            }
        });
        tv_processsection = findViewById(R.id.moudle_doing_fault_detail_tv_processsection);
        tv_processsection.setOnClickListener(this);
        tv_equ = findViewById(R.id.moudle_doing_fault_detail_tv_equ);
        tv_equ.setOnClickListener(this);
        tv_receiver = findViewById(R.id.moudle_doing_fault_detail_tv_receiver);
        tv_receiver.setOnClickListener(this);
        rc_fault_pic = findViewById(R.id.moudle_doing_fault_detail_rc_pic);
//        picAdapter = new PicAdapter(pics,DoingFaultDetailActivity.this);
//        rc_fault_pic.setAdapter(picAdapter);
        stmanager = new LinearLayoutManager(DoingFaultDetailActivity.this);
        stmanager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rc_fault_pic.setLayoutManager(stmanager);
        datas = new ArrayList<>();
        gv_pic = findViewById(R.id.moudle_doing_fault_detail_gv_pic);
        gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
        gv_pic.setAdapter(gridViewAddImgesAdpter);
        gv_pic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                showdialog();
            }
        });

        //实施内容显示
        ll_show = findViewById(R.id.moudle_doing_fault_detail_ll_show);
        etrepairway=(Spinner)findViewById(R.id.rp_imp_sp_repairway);//是否委外
        String[] cates=getResources().getStringArray(R.array.repairway);
        ArrayAdapter adaptergroup=new ArrayAdapter(this, R.layout.item_normal_little_spin, R.id.moudle_normal_little_spin_tv_title,cates);
        etrepairway.setAdapter(adaptergroup);
        etrepairway.setSelection(0);//默认选择第一种维修方式
        tv_show_area = findViewById(R.id.moudle_doing_fault_detail_tv_show_processsection);
        tv_show_equ = findViewById(R.id.moudle_doing_fault_detail_tv_show_equ);
        tv_show_description = findViewById(R.id.moudle_doing_fault_detail_tv_show_question_description);
        tv_show_content = findViewById(R.id.moudle_doing_fault_detail_tv_show_dispose_content);
        tv_show_remark = findViewById(R.id.moudle_doing_fault_detail_tv_show_content_added);
        tv_show_date = findViewById(R.id.moudle_doing_fault_detail_tv_show_maintenance_date);
        tv_show_man = findViewById(R.id.moudle_doing_fault_detail_tv_show_receiver);
        rc_show = findViewById(R.id.moudle_doing_fault_detail_rc_show_pic);
        transferee = Transferee.getDefault(this);
        if (mFault!=null&&mFault.getId()!=null){
            tv_area.setText(mFault.getProcessSection().getName());
            if (mFault.getEquipmentCard()!=null&&!mFault.getEquipmentCard().getEquipmentname().equals("")) {
                tv_equ_detail.setText(mFault.getEquipmentCard().getEquipmentname());
            }else {
//                tv_equ_detail.setVisibility(View.GONE);
                ll_equ.setVisibility(View.GONE);
            }
            tv_content.setText(mFault.getProblemcontent());
            tv_planMoney.setText(mFault.getPlanMoney());
//            tv_remark.setText(mFault.getProblemTypeNames());
            tv_date.setText(mFault.getInsdt().substring(5,16));
            tv_man.setText(mFault.getInsuser());
            tv_processsection.setText(sel_ps.getName());
            tv_equ.setText(sel_equ.getEquipmentname());
            if (mFault.getTodoTask()!=null){
                if (mFault.getTodoTask().equals("待签收")){
                    btn_sub.setVisibility(View.GONE);
                    btn_big_sub.setVisibility(View.GONE);
                    ll_edit.setVisibility(View.GONE);
                    ll_show.setVisibility(View.GONE);
                }else if (mFault.getTodoTask().contains("执行")){
                    btn_sign_in.setVisibility(View.GONE);
                    ll_show.setVisibility(View.GONE);
                }else if (mFault.getTodoTask().contains("验收")||mFault.getTodoTask().contains("完成")){
                    btn_sub.setVisibility(View.GONE);
                    btn_big_sub.setVisibility(View.GONE);
                    btn_sign_in.setVisibility(View.GONE);
                    ll_edit.setVisibility(View.GONE);
                    ll_show.setVisibility(View.VISIBLE);
                    getSubDetail();
                }
            }
        }

    }

    /*
    获取执行的详情
     */
    private void getSubDetail() {
        HashMap<String,String> map = new HashMap<>();
        map.put("id",mFault.getId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetSubDetail_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!DoingFaultDetailActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DoingFaultDetailActivity.this, "数据获取失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    if(res.contains("fail")) {
                        showFailDialog();
                    }else {
                        JSONObject jsonObject = new JSONObject(res);
                        JSONArray aNews = new JSONArray(jsonObject.opt("content1").toString());
                        showDetail(aNews);
                        String businessid = jsonObject.opt("businessUnitHandleId").toString();
                        getSubDetailPic(businessid);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showFailDialog() {
        if (!DoingFaultDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("工单获取失败，请重试！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void showDetail(final JSONArray arry) {
        try {
            JSONObject obj = arry.getJSONObject(0);
            final Maintenance item = new Maintenance();
            item.setId(obj.opt("id").toString());
            item.setProblem(obj.opt("problem").toString());
            item.setHandledetail(obj.opt("handledetail").toString());
            item.setDetailsupplement(obj.opt("detailsupplement").toString());
            item.setFaultLibraryName(obj.opt("faultLibraryName").toString());
            item.setInsdt(obj.opt("insdt").toString());
            item.setProcessSectionName(obj.opt("processSectionName").toString());
            item.setInsuserName(obj.opt("insuserName").toString());
            item.setEquipmentNames(obj.opt("equipmentNames").toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_show_area.setText(item.getProcessSectionName());
                    tv_show_equ.setText(mFault.getEquipmentCard().getEquipmentname());
                    tv_show_description.setText(item.getProblem());
                    tv_show_content.setText(item.getHandledetail());
                    tv_show_remark.setText(item.getDetailsupplement());
                    tv_show_date.setText(item.getInsdt().substring(5,16));
                    tv_show_man.setText(item.getInsuserName());
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 选择图片对话框
     */
    public void showdialog() {
        View localView = LayoutInflater.from(this).inflate(
                R.layout.dialog_add_picture, null);
        TextView tv_camera = (TextView) localView.findViewById(R.id.tv_camera);
        TextView tv_gallery = (TextView) localView.findViewById(R.id.tv_gallery);
        TextView tv_cancel = (TextView) localView.findViewById(R.id.tv_cancel);
        ddialog = new Dialog(this, R.style.custom_dialog);
        ddialog.setContentView(localView);
        ddialog.getWindow().setGravity(Gravity.BOTTOM);
        // 设置全屏
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = ddialog.getWindow().getAttributes();
        lp.width = display.getWidth(); // 设置宽度
        ddialog.getWindow().setAttributes(lp);
        ddialog.show();
        tv_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ddialog.dismiss();
            }
        });

        tv_camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ddialog.dismiss();
                // 拍照
                camera();
            }
        });

        tv_gallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ddialog.dismiss();
                // 从系统相册选取照片
                gallery();
            }
        });
    }

    public void photoPath(String path) {
        Map<String,Object> map=new HashMap<>();
        map.put("path",path);
        datas.add(map);
        gridViewAddImgesAdpter.notifyDataSetChanged();
    }

    /**
     * 拍照
     */
    public void camera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            try {
                File file = createOriImageFile();
                file_go = file;
                if (file != null) {
                    Uri imgUriOri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID+ ".fileProvider", file);
                    cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    startActivityForResult(cameraIntent, 0x1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                if (!mars_file.exists()) {
                    mars_file.mkdirs();
                }
                // 并设置拍照的存在方式为外部存储和存储的路径；
                cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file_go));
                //跳转到拍照界面;
                startActivityForResult(cameraIntent, 0x1);
            } else {
                Toast.makeText(DoingFaultDetailActivity.this, "请先安装好sd卡", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    private File createOriImageFile() throws IOException {
        String imgNameOri = "nk_" + new SimpleDateFormat(
                "yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() +  "/my_camera");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        String  imgPathOri = image.getAbsolutePath();
        return image;
    }

    /**
     * 判断sdcard是否被挂载
     */
    public boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }


    /**
     * 从相册获取2
     */
    public void gallery() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }


    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            year=myyear;
            month=monthOfYear;
            day=dayOfMonth;
            //更新日期
            updateDate();
        }
        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate()
        {
            //在TextView上显示日期
            TimePickerDialog dpd=new TimePickerDialog(DoingFaultDetailActivity.this,Timelistener,hour,minute,true);
            dpd.show();//显示DatePickerDialog组件
        }
    };
    private TimePickerDialog.OnTimeSetListener Timelistener=new TimePickerDialog.OnTimeSetListener()
    {
        @Override
        public void onTimeSet(TimePicker view, int hours, int minutes) {
            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            hour=hours;
            minute=minutes;
            //更新日期
            updateDate();
        }
        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate()
        {
            //在TextView上显示日期
            String smonth = "";
            String sday = "";
            String shour = "";
            String smin = "00";
            //在TextView上显示日期
            if (month<9){
                smonth = "0"+String.valueOf(month+1);
            }else {
                smonth = String.valueOf(month+1);
            }
            if (day<10){
                sday = "0"+String.valueOf(day);
            }else {
                sday = String.valueOf(day);
            }
            if (hour<10){
                shour = "0"+String.valueOf(hour);
            }else {
                shour = String.valueOf(hour);
            }
            //在TextView上显示日期
            if(edt_maintenance_date.isFocused()){
                edt_maintenance_date.setText(year+"-"+smonth+"-"+sday+" "+shour+":"+"00:00");
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.moudle_doing_fault_detail_btn_sign_in:
                SignInFault();
                break;
            case R.id.moudle_doing_fault_detail_btn_sub:
                List<EditText> edts = new ArrayList<>();
                edts.add(edt_question_description);
                edts.add(edt_dispose_content);
//                edts.add(edt_maintenance_date);
                Boolean istrue = isEditTextEmpty(edts);
                if (!istrue){
                    subDoingFault();
                }
                break;
            case R.id.moudle_doing_fault_detail_btn_big_sub:
                List<EditText> edtas = new ArrayList<>();
                edtas.add(edt_question_description);
                edtas.add(edt_dispose_content);
                Boolean isatrue = isEditTextEmpty(edtas);
                if (!isatrue){
                    subDoingFault();
                }
                break;
            case R.id.moudle_doing_fault_detail_tv_processsection:
                Intent intent_sel_ps = new Intent(DoingFaultDetailActivity.this, SingleChoiceActivity.class);
                intent_sel_ps.putExtra("mark","ps");
                startActivityForResult(intent_sel_ps,SELPS);
                break;
            case R.id.moudle_doing_fault_detail_tv_equ:
                Intent intent_sel_equ = new Intent(DoingFaultDetailActivity.this, SingleChoiceActivity.class);
                intent_sel_equ.putExtra("mark","equ");
                if (sel_ps!=null) {
                    intent_sel_equ.putExtra("psId",sel_ps.getSid());
                }
                startActivityForResult(intent_sel_equ, SELEQU);
                break;
            case R.id.moudle_doing_fault_detail_tv_receiver:
                if (receivers.size()>0) {
                    Intent intent_man = new Intent(DoingFaultDetailActivity.this, PersonSelectorActivity.class);
                    intent_man.putExtra("users", (Serializable) receivers);
                    startActivityForResult(intent_man,SEND_RECEIVERS);
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("暂未配置接收人")
                                    .show();
                        }
                    });
                }
                break;
        }
    }

    /*
    获取提交缺陷执行时所需提交的部分参数
     */
    private void getHandleDetail() {
        HashMap<String,String> map = new HashMap<>();
        map.put("taskId",mFault.getTaskId());
        map.put("processInstanceId",mFault.getProcessInstanceId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GetPar_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                if (!DoingFaultDetailActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DoingFaultDetailActivity.this, "流程数据获取失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                subDoingFaultFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    JSONArray array = new JSONArray(jsonObject.opt("content1").toString());
                    pc_id = array.getJSONObject(0).optString("id");
                    pc_processid = array.getJSONObject(0).optString("processid");
                    pc_handledetail = array.getJSONObject(0).optString("handledetail");
                    pc_taskid = array.getJSONObject(0).optString("taskid");
                    pc_unitid = array.getJSONObject(0).optString("unitid");
                    if (pc_unitid.isEmpty()){
                        pc_unitid = "handle";
                    }
                    pc_businessid = array.getJSONObject(0).optString("businessid");
                    pc_taskdefinitionkey = array.getJSONObject(0).optString("taskdefinitionkey");
                    updateProcess();
                } catch (JSONException e) {
                    e.printStackTrace();
                    subDoingFaultFail();
                }
            }
        });
    }

    /**
     * 更新流程
     */
    private void updateProcess() {
        HashMap<String,String> map = new HashMap<>();
        map.put("businessid",pc_businessid);
        map.put("handledetail",edt_dispose_content.getText().toString());
        map.put("id",pc_id);
        map.put("processid",pc_processid);
        map.put("targetusers",st_sel_receiver_id);
        map.put("taskdefinitionkey",pc_taskdefinitionkey);
        map.put("taskid",pc_taskid);
        map.put("unitid",pc_unitid);
        map.put("routeNum","0");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.UpdateProcess_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                subDoingFaultFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resa = response.body().string();
                pDialogHide();
                try {
                    JSONObject jsonObject = new JSONObject(resa);
                    String res = jsonObject.opt("res").toString();
                    if (res.equals("1")) {
                        subDoingFaultSuccess();
                    } else {
                        subDoingFaultFail();
                    }
                }catch (Exception e){

                }
            }
        });
    }

    /*
    提交实施内容
     */
    private void subDoingFault() {
        String actualMoney = "";
        if (edt_actualMoney.getText()!=null&&edt_actualMoney.getText().toString().length()>0){
            actualMoney = edt_actualMoney.getText().toString();
        }
        String workinghours = "";
        if (edt_workinghours.getText()!=null&&edt_workinghours.getText().toString().length()>0){
            workinghours = edt_workinghours.getText().toString();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("id",mFault.getId());
        map.put("targetusers",st_sel_receiver_id);
        if (edt_question_description.getText()!=null&&!edt_question_description.getText().toString().isEmpty()) {
            map.put("problemcontent", edt_question_description.getText().toString());//故障描述
        }
        map.put("actualMoney",actualMoney);//实际费用
        map.put("workinghours",workinghours);//工时
        map.put("maintenanceWay",repway[etrepairway.getSelectedItemPosition()]);//是否委外
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.SubImp_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                subDoingFaultFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resa = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(resa);
                    String res = jsonObject.opt("res").toString();
                    if (res.equals("1")){
                        if (datas.size()>0){
                            subDoingFaultPics(jsonObject.optString("id"));
                        }else {
                            pDialogHide();
                            getHandleDetail();
                        }
                    }else {
                        pDialogHide();
                        subDoingFaultFail();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void subDoingFaultPics(String id) {
        pDialogshow();
        HashMap<String,String> map = new HashMap<>();
        map.put("masterId",id);
        map.put("tbName","tb_maintenance_file");
        map.put("nameSpace","MaintenanceFile");
        String picMark = "filelist";
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpSubPics(map,mServer, MethodURL.SubPic_Method,picMark,datas)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pDialogHide();
                picSubFail(id);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("suc")){
                    getHandleDetail();
                }else {
                    picSubFail(id);
                }
            }
        });
    }

    private void picSubFail(String id) {
        if (!DoingFaultDetailActivity.this.isFinishing()){
            new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("失败")
                    .setContentText("图片上传失败")
                    .setConfirmText("重新上传")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            subDoingFaultPics(id);
                        }
                    }).setCancelText("取消")
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            finish();
                        }
                    }).show();
        }
    }

    private void subDoingFaultSuccess() {
        if (!DoingFaultDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("上传成功")
                            .setConfirmText("确认")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).show();
                }
            });
        }
    }

    private void subDoingFaultFail() {
        if (!DoingFaultDetailActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("提交失败，请重试")
                            .setConfirmText("确认")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void pDialogHide() {
        if (!DoingFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!DoingFaultDetailActivity.this.isFinishing()) {
                        pDialog.hide();
                    }
                }
            });
        }
    }

    private void pDialogshow() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!DoingFaultDetailActivity.this.isFinishing()){
                    pDialog.show();
                }
            }
        });
    }

    private Boolean isEditTextEmpty(final List<EditText> edts) {
        Boolean isEmpty = false;
        for (int i=0;i<edts.size();i++){
            if (edts.get(i).getText()!=null&&edts.get(i).getText().toString().length()>0){}else {
                final EditText edt_sel = edts.get(i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        edt_sel.setError("请填写内容");
                    }
                });
                isEmpty = true;
            }
        }
        return isEmpty;
    }

    private void SignInFault() {
        HashMap<String,String> map = new HashMap<>();
        map.put("taskId",mFault.getTaskId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.SignIn_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                signFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.equals("1")){
                    SubSuccess();
                    if (!DoingFaultDetailActivity.this.isFinishing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btn_sign_in.setVisibility(View.GONE);
                                btn_sub.setVisibility(View.VISIBLE);
                                btn_big_sub.setVisibility(View.VISIBLE);
                                ll_edit.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                }else {
                    signFail();
                }
            }
        });
    }

    private void signFail() {
        if (!DoingFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DoingFaultDetailActivity.this, "签收失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void SubSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                        .setTitleText("签收成功")
                        .setConfirmText("确认")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        }).show();
            }
        });
    }

    private void SubFail() {
        if (!DoingFaultDetailActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(DoingFaultDetailActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("签收失败，请重试")
                            .setConfirmText("确认")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELPS:
                if (resultCode == RESULT_OK) {
                    sel_ps = (ProcessSection) data.getSerializableExtra("ps");
                    if (!DoingFaultDetailActivity.this.isFinishing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showText(sel_ps.getName(), tv_processsection);
                            }
                        });
                    }
                }
                break;
            case SELEQU:
                if (resultCode == RESULT_OK) {
                    sel_equ = (EquList) data.getSerializableExtra("equ");
                    if (!DoingFaultDetailActivity.this.isFinishing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sel_equs_id = sel_equ.getId();
                                showText(sel_equ.getEquipmentname(), tv_equ);
//                                if (sel_equ.getEquipmentcardid().equals(mFault.getEquipmentCard().getEquipmentcardid())) {
//                                    sel_equs_id = sel_equ.getId();
//                                    showText(sel_equ.getEquipmentname(), tv_equ);
//                                }else {
//                                    new SweetAlertDialog(DoingFaultDetailActivity.this,SweetAlertDialog.WARNING_TYPE)
//                                            .setTitleText("提示")
//                                            .setContentText("检测到您所选设备与维修设备不符，请确认后重新选择！")
//                                            .setConfirmText("确定")
//                                            .show();
//                                }
                            }
                        });
                    }
                }
                break;
            case SEND_RECEIVERS:
                if (resultCode == RESULT_OK) {
                    sel_receivers = (List<User>) data.getSerializableExtra("sel");
                    String suser = "";
                    st_sel_receiver_id = "";
                    if (sel_receivers.size() > 0) {
                        for (int i = 0; i < sel_receivers.size(); i++) {
                            if (i == 0) {
                                suser = sel_receivers.get(i).getCaption();
                                st_sel_receiver_id = sel_receivers.get(i).getId();
                            } else if (0<i &&i < sel_receivers.size()) {
                                suser = suser + "," + sel_receivers.get(i).getCaption();
                                st_sel_receiver_id = st_sel_receiver_id + "," + sel_receivers.get(i).getId();
                            }
                        }
                    }
                    final String st = suser;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (sel_receivers.size() > 0) {
                                showText(st,tv_receiver);
                            }
                        }
                    });
                }
                break;
            case PHOTO_REQUEST_GALLERY:
                // 从相册返回的数据
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    String[] proj = {MediaStore.Images.Media.DATA};
                    //好像是android多媒体数据库的封装接口，具体的看Android文档
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    //按我个人理解 这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    //将光标移至开头 ，这个很重要，不小心很容易引起越界
                    cursor.moveToFirst();
                    //最后根据索引值获取图片路径
                    String path = cursor.getString(column_index);
                    uploadImage(path);
                }
                break;
            case PHOTO_REQUEST_CAREMA:
                if (resultCode != RESULT_CANCELED) {
                    // 从相机返回的数据
                    if (hasSdcard()) {
                        if (file_go != null) {
                            uploadImage(file_go.getPath());
                        } else {
                            Toast.makeText(this, "相机异常请稍后再试！", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    /**
     * 上传图片
     *
     * @param path
     */
    private void uploadImage(final String path) {
        new Thread() {
            @Override
            public void run() {
                if (new File(path).exists()) {
                    Log.d("images", "源文件存在" + path);
                } else {
                    Log.d("images", "源文件不存在" + path);
                }

                File dir = new File(IMAGE_DIR);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                final File file = new File(dir + "/temp_photo" + System.currentTimeMillis() + ".jpg");
                NativeUtil.compressBitmap(path, file.getAbsolutePath(), 50);
                if (file.exists()) {
                    Log.d("images", "压缩后的文件存在" + file.getAbsolutePath());
                } else {
                    Log.d("images", "压缩后的不存在" + file.getAbsolutePath());
                }
                Message message = new Message();
                message.what = UPIMG;
                message.obj = file.getAbsolutePath();
                handler.sendMessage(message);

            }
        }.start();

    }

    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mGroup;
    public void init(){
        SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);
        mServer=sharedPre.getString("server", "");
        mUsername=sharedPre.getString("username", "");
        mPassword=sharedPre.getString("password", "");
        mUserid=sharedPre.getString("userid", "");
        mCaption=sharedPre.getString("caption", "");
        mBizid=sharedPre.getString("bizid", "");
        mseriverip=sharedPre.getString("serverip", "");
        mGroup=sharedPre.getString("group", "");
        if (getIntent().getSerializableExtra("fault")!=null){
            mFault    = (Fault) getIntent().getSerializableExtra("fault");
            sel_ps = mFault.getProcessSection();
            sel_equ = mFault.getEquipmentCard();
            sel_equs_id = mFault.getEquipmentCard().getId();
        }
    }

    private void showText(final String st, final TextView tv) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText(st);
            }
        });
    }

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