package com.zhilin.patrol.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.zhilin.patrol.R;
import com.zhilin.patrol.adapter.UpImageAdapter;
import com.zhilin.patrol.adapter.helper.GridItemDecoration;
import com.zhilin.patrol.adapter.helper.MyItemTouchCallback;
import com.zhilin.patrol.adapter.helper.OnRecyclerItemClickListener;
import com.zhilin.patrol.bean.AddressAreaEntity;
import com.zhilin.patrol.bean.LoginEntity;
import com.zhilin.patrol.bean.MapLocationInfo;
import com.zhilin.patrol.bean.PatrolFormEntity;
import com.zhilin.patrol.bean.QuestionKindEntity;
import com.zhilin.patrol.http.HttpUrl;
import com.zhilin.patrol.tool.CheckPermissionUtils;
import com.zhilin.patrol.tool.Compresser;
import com.zhilin.patrol.tool.DensityUtil;
import com.zhilin.patrol.tool.DialogUtil;
import com.zhilin.patrol.tool.IpUtils;
import com.zhilin.patrol.tool.JsonUtils;
import com.zhilin.patrol.tool.LocationUtils;
import com.zhilin.patrol.tool.SPUtil;
import com.zhilin.patrol.tool.Utils;
import com.zhilin.patrol.views.AlertDialog;
import com.zhilin.patrol.views.CustomProgressDialog;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 巡查上报页面
 */
public class PatrolUploadActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.img_recycler)
    RecyclerView mRecyclerView;
    /** 选中问题分类 */
//    @BindView(R.id.question_recycler)
//    RecyclerView mQuestionRecyclerView;
    @BindView(R.id.tv_question)
    TextView mQuestionTypeTv;//问题分类
    @BindView(R.id.ll_question)
    LinearLayout mQuestionTypeLl;//问题分类布局
    @BindView(R.id.line_question)
    View mQuestionTypeLineView;//问题分类横线
    @BindView(R.id.rg_question)
    RadioGroup mQuestionRg;//是否有问题选择
    @BindView(R.id.et_content)
    EditText mRemarkEt;//备注
    @BindView(R.id.tv_content_num)
    TextView mContentNumTv;//备注长度
    @BindView(R.id.tv_img_num)
    TextView mImgNumTv;//图片数量
    @BindView(R.id.tv_location)
    TextView mLocationTv;//定位
    @BindView(R.id.tv_location_goal)
    TextView mLocationGoalTv;//任务位置
    @BindView(R.id.ll_last_location)
    LinearLayout mLastLocationLl;//上次定位的布局
//    @BindView(R.id.tv_last_location)
//    TextView mLastLocationTv;//上次定位
    @BindView(R.id.tv_default_address)//默认地址
    TextView mDefaultaddressTv;

    private String TAG="PatrolUploadActivity";//打印日志

    //用户信息
    private LoginEntity.InfoListBean.UserInfoBean mUserInfo;
    //选择图片适配器
    private UpImageAdapter mAdapter;
    //上传图片
    public ArrayList<String> mDataList = new ArrayList<>();

    private ItemTouchHelper mItemTouchHelper;

    private CustomProgressDialog mProgressDialog;

    private LocationUtils mLocationUtils;
    /** 定位信息 */
    private MapLocationInfo mMapLocationInfo;
    /** 是否有问题 */
    private Integer mHasProblem;
    /** 选中的问题类型 */
//    private QuestionKindEntity.Bean mQuestionKind;
    /** 是否是指派任务 */
    private int mIsAssign;
    /** 问题分类 */
    private ArrayList mQuestionList;
    /** 附近小区集合 */
    private ArrayList mAddressAreaList;
    private boolean isQuestionJump = true;

    /** 客户文件目录 */
    private String mImageDir = Environment.getExternalStorageDirectory() + "/patrol/";

    String[] mPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE};
    /** 表单返回码 */
    private String mTkCode;

    /** 选中的问题类型 */
//    private List<QuestionKindEntity.Bean> mSelectList = new ArrayList<>();
    private QuestionKindEntity.Bean mSelectBean;
//    private CommonAdapter<QuestionKindEntity.Bean> mSelectAdapter;
    /** 选中的小区 */
    private AddressAreaEntity.InfoListBean mListBean;
    private MapLocationInfo mLastMapLocationInfo;
    private AddressAreaEntity.InfoListBean mLastListBean;
    private QuestionKindEntity.Bean mLastSelectBean;
    private int mLastHasProblem;
    private String mpCode;
    private String mpbCode;
    private String maddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patrol_upload);
        ButterKnife.bind(this);
        mUserInfo = (LoginEntity.InfoListBean.UserInfoBean) getIntent().getSerializableExtra("userInfo");
        mIsAssign = getIntent().getIntExtra("isAssign", 0);
        mpCode=getIntent().getStringExtra("pCode");
        mpbCode=getIntent().getStringExtra("pbCode");
        Log.i("mpCode==",mpCode);
        Log.i("mpbCode==",mpbCode);
        maddress=getIntent().getStringExtra("address");
        mProgressDialog = new CustomProgressDialog(this);
        setTitle("巡查上报");
        setRightTv("提交");
        setRightClick(this);

        mLocationUtils = LocationUtils.getInstance();
        Log.i(TAG,"去定位");
        mLocationGoalTv.setText(maddress);
        mLocationUtils.onCreate(new LocationUtils.LocationListener() {
            @Override
            public void locationSuccess(MapLocationInfo mapLocationInfo, String message) {
                if (TextUtils.isEmpty(mapLocationInfo.getAddress())) {
//                    mMapLocationInfo = null;
                    mLocationTv.setText(Html.fromHtml("<font color='red'>定位失败！请使用照片证明你在该小区</font>"));
                } else {
                    mMapLocationInfo = mapLocationInfo;
                    mLocationTv.setText(mapLocationInfo.getAddress());
                }
                mProgressDialog.dismiss();
                Log.i(TAG,"定位ok");
                Log.i(TAG,mMapLocationInfo.toString());
                defalutAddress();//确定默认小区
            }
            @Override
            public void locationFail(String message) {
                mProgressDialog.dismiss();
//                mMapLocationInfo = null;
                mLocationTv.setText("定位： " + message);
            }
        });
        mQuestionRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (checkedRadioButtonId == R.id.rb_question_yes) {//有问题
//                    mQuestionRecyclerView.setVisibility(View.VISIBLE);
                    mQuestionTypeLl.setVisibility(View.VISIBLE);
                    mQuestionTypeLineView.setVisibility(View.VISIBLE);
                    if (isQuestionJump) {
                        isQuestionJump = true;
                        toQuestionType();
                    }
                    mHasProblem = 1;
                } else if (checkedRadioButtonId == R.id.rb_question_no) {//没问题
                    mHasProblem = 0;
//                    mQuestionRecyclerView.setVisibility(View.GONE);
                    mQuestionTypeLl.setVisibility(View.GONE);
                    mQuestionTypeLineView.setVisibility(View.GONE);
                }
            }
        });
        mRemarkEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mContentNumTv.setText(mRemarkEt.getText().length() + "/200");
            }
        });
        setRecycler();
        setImageNum();
//        setLastData();//上次定位
        checkPermissions();

        //---------lp返回选择的小区名字，距离

//----------
    }

    private void defalutAddress(){
            Log.i(TAG,"准备获取小区");
            Log.i(TAG,mMapLocationInfo.toString());
            requestAddress2();
            Log.i(TAG,"获取到小区");
//
    }
//    private void setLastData() {//上次定位
//        String lastLocationJsonStr = SPUtil.getShareStr(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "last_location");
//        String addressArea = SPUtil.getShareStr(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "addressArea");
//        mLastHasProblem = SPUtil.getShareInt(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "hasProblem");
//        String lastSelectBeanStr = SPUtil.getShareStr(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "selectBean");
//        mLastMapLocationInfo = (MapLocationInfo) JsonUtils.parseJson2Obj(lastLocationJsonStr, MapLocationInfo.class);
//        mLastListBean = (AddressAreaEntity.InfoListBean) JsonUtils.parseJson2Obj(addressArea, AddressAreaEntity.InfoListBean.class);
//        mLastSelectBean = (QuestionKindEntity.Bean) JsonUtils.parseJson2Obj(lastSelectBeanStr, QuestionKindEntity.Bean.class);
//        if (mLastMapLocationInfo != null) {
//            mLastLocationLl.setVisibility(View.VISIBLE);
////            mLastLocationTv.setText(mLastListBean != null ? mLastListBean.getAddress() : mLastMapLocationInfo.getAddress());
//        }
//
//    }

    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermissions() {
        mPermissions = CheckPermissionUtils.getNeededPermission(this, mPermissions);
        if (mPermissions.length > 0) {
            requestPermissions(mPermissions, 999);
        }
        if (mPermissions.length == 0) {
            //申请过一次这里的permissions.length就为0 了
            //申请权限后创建图片文件夹
            Utils.createDir(mImageDir);
            locationAddress();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
                new AlertDialog(PatrolUploadActivity.this).builder()
                        .setTitle(PatrolUploadActivity.this.getString(R.string.tv_tishi))
                        .setMsg("获取权限失败，是否重新尝试？")
                        .setPositiveButton("重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                checkPermissions();
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }).show();
                return;
            }
        }
        locationAddress();
        //申请权限后创建图片文件夹
        Utils.createDir(mImageDir);
    }

    /**
     * 定位
     */
    private void locationAddress() {
        mProgressDialog.showDialog("正在定位...");
        mLocationUtils.startLocationInfo();
    }

    /**
     * 设置图片数量
     */
    public void setImageNum() {
        mImgNumTv.setText(Html.fromHtml("上传图片 <Small>" + mDataList.size() + "/9</Small>"));
    }

    @OnClick({R.id.tv_question, R.id.ll_location})//R.id.tv_last_location_use
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.tv_last_location_use://使用上次定位
//                if (mLastHasProblem != -1) {
//                    mHasProblem = mLastHasProblem;
//                    isQuestionJump = false;
//                    if (mHasProblem == 1) {//有问题
//                        mQuestionRg.check(R.id.rb_question_yes);
//                    } else {//没问题
//                        mQuestionRg.check(R.id.rb_question_no);
//                    }
//                }
//                mSelectBean = mLastSelectBean;
//                mMapLocationInfo = mLastMapLocationInfo;
//                mListBean = mLastListBean;
////                mLocationTv.setText(mMapLocationInfo.getAddress());
//                if (mSelectBean != null) {
//                    mQuestionTypeTv.setText(mSelectBean.getqName());
//                }
//                mLocationTv.setText(mLastListBean != null ? mLastListBean.getAddress() : mLastMapLocationInfo.getAddress());
//                break;
            case R.id.tv_question://问题分类
                toQuestionType();
                break;
            case R.id.ll_location://定位
                if (mMapLocationInfo == null) {
                    locationAddress();
                } else {//选择小区
                    toAddressSelect();
                }
                break;
            case R.id.tv_right://提交
                if (!TextUtils.isEmpty(mTkCode)) {
                    mProgressDialog.showDialog("正在提交...");
                    postPatrolImage(mTkCode);
                    return;
                }
                if (mHasProblem == null) {
                    Utils.showToast(this, "请选择该巡查点是否有问题");
                    return;
                }
//                if (mHasProblem == 1 && mSelectList == null && mSelectList.isEmpty()) {
                if (mHasProblem == 1 && mSelectBean == null) {
                    Utils.showToast(this, "请选择问题类型");
                    return;
                }
                if (mDataList.size() < 1) {
                    Utils.showToast(this, "请拍摄图片");
                    return;
                }
                String remark = mRemarkEt.getText().toString().trim();
                if (mMapLocationInfo == null) {
                    if (TextUtils.isEmpty(remark)) {
                        Utils.showToast(this, "请输入备注信息");
                        return;
                    }
                }
                String questionKind = "";
                if (mHasProblem == 1) {
//                    StringBuilder sb = new StringBuilder();
//                    for (QuestionKindEntity.Bean bean : mSelectList) {
//                        sb.append(bean.getqCode()).append(",");
//                    }
//                    questionKind = sb.substring(0, sb.length() - 1);
                    questionKind = mSelectBean.getqCode();
                }
                postPatrol(mMapLocationInfo, mHasProblem, questionKind, remark);
                break;
            default:
                break;
        }
    }

    private void toAddressSelect() {
        if (mAddressAreaList == null) {
            requestAddress();
        } else {
            Log.i(TAG,mAddressAreaList.toString()+"附近小区list");
            toAddressSelectActivity();
        }
    }

    /**
     * 请求地址
     */
    public void requestAddress() {
        Log.i(TAG,"requestAddress");
        mProgressDialog.showDialog("正在获取附近小区...");
        String ipAddress = IpUtils.getIpAddress(this);
        Log.i(TAG,mUserInfo.getUserCode());
        Log.i(TAG,mUserInfo.getUserRole() + "");
        Log.i(TAG,ipAddress);
        Log.i(TAG,mMapLocationInfo.getDistrict());
        Log.i(TAG,mMapLocationInfo.getLongitude() + "");
        Log.i(TAG,mMapLocationInfo.getLatitude() + "");

        OkHttpUtils.post()
                .url(HttpUrl.GET_NEAR_ADDRESS_URL)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("userIP", ipAddress)
                .addParams("disName", mMapLocationInfo.getDistrict())
                .addParams("longitude", mMapLocationInfo.getLongitude() + "")
                .addParams("latitude", mMapLocationInfo.getLatitude() + "")
//                .addParams("userCode", "123")http://39.106.14.189:8081/index.php/ApiMobi/getNearAddress？userRole=1&userCode=123&disName=汉江区&longitude=114.339037&latitude=30.546917
//                .addParams("userRole", "1")
//                .addParams("userIP", ipAddress)
//                .addParams("disName", "%E6%B1%9F%E6%B1%89%E5%8C%BA")
//                .addParams("longitude", "114.339037")
//                .addParams("latitude",  "30.546917")
                .build().execute(new Callback<AddressAreaEntity>() {
            @Override
            public AddressAreaEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (AddressAreaEntity) JsonUtils.parseJson2Obj(jsonStr, AddressAreaEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mProgressDialog.dismiss();
                DialogUtil.showNetFailDialog(PatrolUploadActivity.this);
            }

            @Override
            public void onResponse(AddressAreaEntity entity, int id) {
                mProgressDialog.dismiss();
                if (entity == null) {
                    DialogUtil.showErrDialog(PatrolUploadActivity.this, "返回信息为空");
                    return;
                }
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(PatrolUploadActivity.this, entity.getReturnMsg());
                    return;
                }
                List<AddressAreaEntity.InfoListBean> infoList = entity.getInfoList();

                if (infoList == null) {
                    DialogUtil.showErrDialog(PatrolUploadActivity.this, "返回数组为空");
                    return;
                }
                if (infoList != null) {
                    mAddressAreaList = new ArrayList();
                    for (AddressAreaEntity.InfoListBean bean : infoList) {
                        mAddressAreaList.add(bean);
                    }
                }
                Log.i(TAG,mAddressAreaList.toString()+"得到附近小区list");
                toAddressSelectActivity();
            }
        });
    }
    public void requestAddress2() {
        Log.i(TAG,"requestAddress2");
        mProgressDialog.showDialog("正在获取附近小区...");
        Log.i(TAG,"getIpAddress");
        String ipAddress = IpUtils.getIpAddress(this);
        Log.i(TAG,"post");
        OkHttpUtils.post()
                .url(HttpUrl.GET_NEAR_ADDRESS_URL)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("userIP", ipAddress)
                .addParams("disName", mMapLocationInfo.getDistrict())
                .addParams("longitude", mMapLocationInfo.getLongitude() + "")
                .addParams("latitude", mMapLocationInfo.getLatitude() + "")
//                .addParams("userCode", "123")
//                .addParams("userRole", "1")
//                .addParams("userIP", ipAddress)
//                .addParams("disName", "%E6%B1%9F%E6%B1%89%E5%8C%BA")
//                .addParams("longitude", "114.339037")
//                .addParams("latitude",  "30.546917")
                .build().execute(new Callback<AddressAreaEntity>() {
            @Override
            public AddressAreaEntity parseNetworkResponse(Response response, int id) throws Exception {
                Log.i(TAG,"jsonStr");
                String jsonStr = response.body().string();
                Log.i(TAG,jsonStr);
                return (AddressAreaEntity) JsonUtils.parseJson2Obj(jsonStr, AddressAreaEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mProgressDialog.dismiss();
                DialogUtil.showNetFailDialog(PatrolUploadActivity.this);
            }

            @Override
            public void onResponse(AddressAreaEntity entity, int id) {
                mProgressDialog.dismiss();
                List<AddressAreaEntity.InfoListBean> infoList = entity.getInfoList();
                int mindDistancenumber=0;
                String addressdefault="附近没有小区";
                Log.i(TAG,"循环遍历");
                Log.i(TAG, infoList.toString());
                Log.i(TAG, infoList.size()+" ");
                if(infoList.size()!=0) {
//                    List<Integer> list=new ArrayList<Integer>();
                    int[] arr=new int[infoList.size()];
                    for (int i = 0; i <= infoList.size()-1; i++) {
//                        list.add(i,Integer.parseInt(infoList.get(i).getDistance()));
                        arr[i]=Integer.parseInt(infoList.get(i).getDistance());
                        Log.i(TAG, infoList.get(i).getDistance()+"distance");
                    }
                    Log.i(TAG, arr+"arr1");
                    for(int i=0;i<=infoList.size()-1;i++){
                        for (int j = 0; j <= infoList.size() - i-2; j++) {
//                        Integer itemp=new Integer(infoList.get(j).getDistance());
//                        Integer itemp2=new Integer(infoList.get(j+1).getDistance());
//                        int mindDistance=itemp.intValue();
//                        int mindDistance2=itemp2.intValue();
//                            int a = Integer.parseInt(infoList.get(j).getDistance());
//                            Log.i(TAG, infoList.get(j).getDistance()+"mindDistance");
//                            int b = Integer.parseInt(infoList.get(j + 1).getDistance());
//                            Log.i(TAG, infoList.get(j+1).getDistance()+"mindDistance2");
                            if (arr[j]>arr[j+1]) {
                                int itemp3=arr[j];
                                arr[j]= arr[j+1];
                                arr[j+1]=itemp3;
                            }
                        }
                    }
                    Log.i(TAG, arr+"arr");
                    int minddistance=0;
                    Log.i(TAG, "得到最小距离");
                    for (int n = 0; n <= infoList.size()-1; n++) {
//                    Integer itemp4=new Integer(infoList.get(n).getDistance());
//                    int Distancenumber=itemp4.intValue();
                        int Distancenumber = arr[0];
                        if (Integer.parseInt(infoList.get(n).getDistance())==Distancenumber) {
                            mindDistancenumber=Distancenumber;
                            addressdefault = infoList.get(n).getAddress();
                            infoList.get(n).setSelected(true);
                           mListBean=infoList.get(n);
                            Log.i(TAG, infoList.get(n).isSelected() +"==isSelected");
                            Log.i(TAG, addressdefault+"addressdefault");
                        }
                    }
                }

                if(mindDistancenumber==0) {
                    Log.i(TAG,"附近没有小区");
                    mDefaultaddressTv.setText(addressdefault);
                }else{
                    Log.i(TAG,"默认小区地址");
                    mDefaultaddressTv.setText(addressdefault+"   "+mindDistancenumber+"m");
                    Log.i(TAG,addressdefault+"  "+mindDistancenumber);
                    mLocationTv.setText(addressdefault);
                }
            }
        });
        Log.i(TAG, "退出requestAddress2");
        mProgressDialog.dismiss();
    }


    /**
     * 提交巡查信息
     *
     * @param mapLocationInfo
     * @param hasProblem
     * @param questionKind
     * @param remark
     */
    private void postPatrol(final MapLocationInfo mapLocationInfo, Integer hasProblem, String questionKind, String remark) {

        String ipAddress = IpUtils.getIpAddress(this);
        boolean isNull = (mapLocationInfo == null);

        if (mListBean != null) {
            Log.i("上传",mListBean.getAddress());
            Log.i("上传",mListBean.isSelected()+"");
        }
        Log.i("地位地址==",isNull ? "定位失败" : mapLocationInfo.getAddress()+"-"+mListBean == null ? "" : mListBean.getAddress());
        String address=mListBean == null ? "" : mListBean.getAddress();
        Log.i("mpbCode==",mpCode);
        Log.i("mpbCode==",mpbCode);
        Log.i("userCode==",mUserInfo.getUserCode());
        Log.i("userRole==",mUserInfo.getUserRole() + "");
        Log.i("isAssign==",mIsAssign + "");
        Log.i("isProblem==",hasProblem + "");
        Log.i("qCode==",questionKind);
        Log.i("infoExt==",remark);
        Log.i("userIP==",ipAddress);
        Log.i("latitude==",mapLocationInfo.getLatitude() + "");
        Log.i("longitude==",mapLocationInfo.getLongitude()+"");
        Log.i("address==",mapLocationInfo.getAddress()+"-"+address);
        Log.i("disName==",mapLocationInfo.getDistrict());
        Log.i("street==",mapLocationInfo.getStreet());
        Log.i("aoi==",mapLocationInfo.getAoi());
        Log.i("addrCode==",mapLocationInfo.getPoi());
        if(maddress.equals(address)){
            if(mpbCode.equals("null")){
                mProgressDialog.showDialog("正在提交...");
                OkHttpUtils.post()
                        .url(HttpUrl.PUBLISH_URL)
                        .addParams("userCode", mUserInfo.getUserCode())
                        .addParams("userRole", mUserInfo.getUserRole() + "")
                        .addParams("isAssign", mIsAssign + "")
                        .addParams("isProblem", hasProblem + "")
                        .addParams("qCode", questionKind)
                        .addParams("infoExt", remark)
                        .addParams("userIP", ipAddress)
                        .addParams("address", isNull ? "定位失败" : mapLocationInfo.getAddress() + "-" + address)
                        .addParams("longitude", isNull ? "0" : mapLocationInfo.getLongitude() + "")
                        .addParams("latitude", isNull ? "0" : mapLocationInfo.getLatitude() + "")
                        .addParams("disName", isNull ? "" : mapLocationInfo.getDistrict())
                        .addParams("street", isNull ? "定位失败" : mapLocationInfo.getStreet())
                        .addParams("aoi", isNull ? "定位失败" : mapLocationInfo.getAoi())
                        .addParams("poi", isNull ? "定位失败" : mapLocationInfo.getPoi())
                        .addParams("pCode", mpCode)
                        .addParams("addrCode", mListBean == null ? "" : mListBean.getAddrCode())
                        .build().execute(new Callback<PatrolFormEntity>() {
                    @Override
                    public PatrolFormEntity parseNetworkResponse(Response response, int id) throws Exception {
                        String jsonStr = response.body().string();
                        return (PatrolFormEntity) JsonUtils.parseJson2Obj(jsonStr, PatrolFormEntity.class);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mProgressDialog.dismiss();
                        DialogUtil.showNetFailDialog(PatrolUploadActivity.this);
                    }

                    @Override
                    public void onResponse(PatrolFormEntity entity, int id) {
                        if (entity == null) {
                            DialogUtil.showErrDialog(PatrolUploadActivity.this, "返回信息为空");
                            return;
                        }
                        if (!"1000".endsWith(entity.getReturnCode())) {
                            DialogUtil.showErrDialog(PatrolUploadActivity.this, entity.getReturnMsg());
                            return;
                        }
                        saveLastData(mapLocationInfo);
                        PatrolFormEntity.InfoListBean bean = entity.getInfoList();
                        mTkCode = bean.getTkCode();
                        postPatrolImage(mTkCode);
                    }
                });
            }else{
                mProgressDialog.showDialog("正在提交...");
                Log.i("mpbCode==",mpCode);
                Log.i("mpbCode==",mpbCode);
                Log.i("userCode==",mUserInfo.getUserCode());
                Log.i("userRole==",mUserInfo.getUserRole() + "");
                Log.i("isAssign==",mIsAssign + "");
                Log.i("isProblem==",hasProblem + "");
                Log.i("qCode==",questionKind);
                Log.i("infoExt==",remark);
                Log.i("userIP==",ipAddress);
                Log.i("latitude==",mapLocationInfo.getLatitude() + "");
                Log.i("longitude==",mapLocationInfo.getLongitude()+"");
                Log.i("address==",mapLocationInfo.getAddress()+"-"+address);
                Log.i("disName==",mapLocationInfo.getDistrict());
                Log.i("street==",mapLocationInfo.getStreet());
                Log.i("aoi==",mapLocationInfo.getAoi());
                Log.i("addrCode==",mapLocationInfo.getPoi());
                OkHttpUtils.post()
                        .url(HttpUrl.PUBLISH_URL)
                        .addParams("userCode", mUserInfo.getUserCode())
                        .addParams("userRole", mUserInfo.getUserRole() + "")
                        .addParams("isAssign", mIsAssign + "")
                        .addParams("isProblem", hasProblem + "")
                        .addParams("qCode", questionKind)
                        .addParams("infoExt", remark)
                        .addParams("userIP", ipAddress)
                        .addParams("address", isNull ? "定位失败" : mapLocationInfo.getAddress()+"-"+address)
                        .addParams("longitude", isNull ? "0" : mapLocationInfo.getLongitude() + "")
                        .addParams("latitude", isNull ? "0" : mapLocationInfo.getLatitude() + "")
                        .addParams("disName", isNull ? "" : mapLocationInfo.getDistrict())
                        .addParams("street", isNull ? "定位失败" : mapLocationInfo.getStreet())
                        .addParams("aoi", isNull ? "定位失败" : mapLocationInfo.getAoi())
                        .addParams("poi", isNull ? "定位失败" : mapLocationInfo.getPoi())
                        .addParams("pCode",mpCode)
                        .addParams("pbCode",mpbCode)
//                .addParams("cCode",mcCode)
                        .addParams("addrCode", mListBean == null ? "" : mListBean.getAddrCode())
                        .build().execute(new Callback<PatrolFormEntity>() {
                    @Override
                    public PatrolFormEntity parseNetworkResponse(Response response, int id) throws Exception {
                        String jsonStr = response.body().string();
                        return (PatrolFormEntity) JsonUtils.parseJson2Obj(jsonStr, PatrolFormEntity.class);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mProgressDialog.dismiss();
                        DialogUtil.showNetFailDialog(PatrolUploadActivity.this);
                    }

                    @Override
                    public void onResponse(PatrolFormEntity entity, int id) {
                        if (entity == null) {
                            DialogUtil.showErrDialog(PatrolUploadActivity.this, "返回信息为空");
                            return;
                        }
                        if (!"1000".endsWith(entity.getReturnCode())) {
                            DialogUtil.showErrDialog(PatrolUploadActivity.this, entity.getReturnMsg());
                            return;
                        }
                        saveLastData(mapLocationInfo);
                        PatrolFormEntity.InfoListBean bean = entity.getInfoList();
                        mTkCode = bean.getTkCode();
                        postPatrolImage(mTkCode);
                    }
                });
            }
        }else{
            Utils.showToast(this, "选择小区与任务点小区不符");
        }

    }

    private void saveLastData(MapLocationInfo mapLocationInfo) {
        SPUtil.savaToShared(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "last_location", JsonUtils.parseObj2Json(mapLocationInfo));
        SPUtil.savaToShared(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "addressArea", JsonUtils.parseObj2Json(mListBean));
        SPUtil.savaToShared(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "hasProblem", mHasProblem);
        SPUtil.savaToShared(PatrolUploadActivity.this, SPUtil.SP_COMMON_CONFIG, "selectBean", JsonUtils.parseObj2Json(mSelectBean));
    }

    /**
     * 上传图片
     */
    private void postPatrolImage(final String tkCode) {
        final String ipAddress = IpUtils.getIpAddress(PatrolUploadActivity.this);
        new Thread() {
            @Override
            public void run() {
                ArrayList<String> list = new ArrayList(mDataList);
                for (String imgPath : list) {
                    try {
                        postPatrolImageSync(ipAddress, imgPath, tkCode);
                    } catch (IOException e) {
                        Log.e("post_image", "图片上传失败");
                    }
                }
                list.clear();
                list = null;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressDialog.dismiss();
                        if (mDataList.size() == 0) {
                            Utils.showToast(PatrolUploadActivity.this, "提交成功，请等待审核");
                            finish();
                        } else {
                            Utils.showToast(PatrolUploadActivity.this, "图片上传失败，请点击提交重新上传");
                        }
                    }
                });
            }
        }.start();
    }

    /**
     * 提交巡查图片
     *
     * @param tkCode
     */
    private void postPatrolImageSync(String ipAddress, final String imagePath, String tkCode) throws IOException {
        Log.i(TAG,"提交巡查图片");
        File file = new File(imagePath);
        String fileName = file.getName();
        Response response = OkHttpUtils.post()
                .url(HttpUrl.PUBLISH_IMG_URL)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("tkCode", tkCode)
                .addParams("userIP", ipAddress)
                .addFile("imgFile", fileName, file)
                .build().execute();
        if (response.isSuccessful()) {
            String jsonStr = response.body().string();
            Log.i(TAG,jsonStr+"=jsonStr");
            PatrolFormEntity entity = (PatrolFormEntity) JsonUtils.parseJson2Obj(jsonStr, PatrolFormEntity.class);
            Log.i(TAG,entity.getReturnCode()+"=getReturnCode");
            if (!"1000".endsWith(entity.getReturnCode())) {
                DialogUtil.showErrDialog(PatrolUploadActivity.this, entity.getReturnMsg());
                throw new IOException(entity.getReturnMsg());
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDataList.remove(imagePath);
                        Utils.delSingleFile(imagePath);
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        } else {
            throw new IOException(response.message());
        }
    }

    /**
     * 跳转到问题类型页面
     */
    private void toQuestionType() {
        if (mQuestionList == null) {
            requestQuestionType();
        } else {
            toQuestionTypeActivity();
        }
    }

    /**
     * 跳转到问题类型页面
     */
    private void toQuestionTypeActivity() {
        Intent intent = new Intent(this, QuestionTypeActivity.class);
        intent.putExtra("userInfo", mUserInfo);
        intent.putExtra("QuestionInfoList", mQuestionList);
        startActivityForResult(intent, 1);
    }

    /**
     * 跳转到选择小区页面
     */
    private void toAddressSelectActivity() {
        Intent intent = new Intent(PatrolUploadActivity.this, AddressSelectActivity.class);
        intent.putExtra("userInfo", mUserInfo);
        intent.putExtra("AddressAreaList", mAddressAreaList);
        startActivityForResult(intent, 2);
    }

    /**
     * 请求问题类型
     */
    public void requestQuestionType() {
        mProgressDialog.showDialog("正在获取问题类型...");
        String ipAddress = IpUtils.getIpAddress(this);
        OkHttpUtils.post()
                .url(HttpUrl.QUESTION_KIND_URL)
                .addParams("userCode", mUserInfo.getUserCode())
                .addParams("userRole", mUserInfo.getUserRole() + "")
                .addParams("userIP", ipAddress)
                .build().execute(new Callback<QuestionKindEntity>() {
            @Override
            public QuestionKindEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (QuestionKindEntity) JsonUtils.parseJson2Obj(jsonStr, QuestionKindEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mProgressDialog.dismiss();
                DialogUtil.showNetFailDialog(PatrolUploadActivity.this);
            }

            @Override
            public void onResponse(QuestionKindEntity entity, int id) {
                mProgressDialog.dismiss();
                if (entity == null) {
                    DialogUtil.showErrDialog(PatrolUploadActivity.this, "返回信息为空");
                    return;
                }
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(PatrolUploadActivity.this, entity.getReturnMsg());
                    return;
                }
                List<QuestionKindEntity.InfoListBean> infoList = entity.getInfoList();
                if (infoList == null) {
                    DialogUtil.showErrDialog(PatrolUploadActivity.this, "返回数组为空");
                    return;
                }
                if (infoList != null) {
                    mQuestionList = new ArrayList();
                    for (QuestionKindEntity.InfoListBean bean : infoList) {
                        mQuestionList.add(bean);
                        mQuestionList.addAll(bean.getKindSon());
                    }
                }
                toQuestionTypeActivity();
            }
        });
    }


    private void setRecycler() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mAdapter = new UpImageAdapter(this, mDataList, layoutManager.getSpanCount());
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new GridItemDecoration(DensityUtil.dip2px(this, 8)));
        MyItemTouchCallback callback = new MyItemTouchCallback(mAdapter);
        mItemTouchHelper = new ItemTouchHelper(callback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) {
            @Override
            public void onLongClick(RecyclerView.ViewHolder vh) {
                if (vh.getLayoutPosition() != mDataList.size()) {
                    mItemTouchHelper.startDrag(vh);
                }
            }
        });

//        mQuestionRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//        mQuestionRecyclerView.setHasFixedSize(true);
//        mQuestionRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
//                .color(getResources().getColor(R.color.line_gray))
//                .size(DensityUtil.dip2px(this, 1))
//                .build());
//        mSelectAdapter = new CommonAdapter<QuestionKindEntity.Bean>(this, R.layout.item_question_type_del, mSelectList) {
//            @Override
//            protected void convert(ViewHolder holder, final QuestionKindEntity.Bean bean, final int position) {
//                holder.setText(R.id.tv_question, bean.getqName());
//                holder.setOnClickListener(R.id.iv_del, new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        mSelectList.remove(bean);
//                        for (Object o : mQuestionList) {
//                            if (o instanceof QuestionKindEntity.ListBean) {
//                                QuestionKindEntity.ListBean listBean = (QuestionKindEntity.ListBean) o;
//                                List<QuestionKindEntity.Bean> sonCell = listBean.getSonCell();
//                                for (QuestionKindEntity.Bean b : sonCell) {
//                                    if (b.getqCode().equals(bean.getqCode())) {
//                                        b.setSelected(false);
//                                    }
//                                }
//                            }
//                        }
//                        notifyDataSetChanged();
//                    }
//                });
//            }
//        };
//        mQuestionRecyclerView.setAdapter(mSelectAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {//返回问题类型
            mQuestionList = (ArrayList) data.getSerializableExtra("QuestionInfoList");
//            mSelectList.clear();
            for (Object o : mQuestionList) {
                if (o instanceof QuestionKindEntity.ListBean) {
                    QuestionKindEntity.ListBean bean = (QuestionKindEntity.ListBean) o;
                    List<QuestionKindEntity.Bean> sonCell = bean.getSonCell();
                    for (QuestionKindEntity.Bean b : sonCell) {
                        if (b.isSelected()) {
//                            mSelectList.add(b);
                            mSelectBean = b;
                            mQuestionTypeTv.setText(mSelectBean.getqName());
                        }
                    }
                }
            }
//            mSelectAdapter.notifyDataSetChanged();
        } else if (requestCode == 2 && resultCode == 1) {//返回小区选择
            mListBean = (AddressAreaEntity.InfoListBean) data.getSerializableExtra("ListBean");
            mAddressAreaList = (ArrayList) data.getSerializableExtra("AddressAreaList");
            mLocationTv.setText(mListBean.getAddress());
            mDefaultaddressTv.setText(mListBean.getAddress()+"    "+mListBean.getDistance()+"m");
        } else if (requestCode == TAKE_PICTURE) {
            //返回拍照的图片
            if (resultCode == -1 && !TextUtils.isEmpty(path) && Utils.fileIsExists(path)) {
                //压缩图片
                mProgressDialog.showDialog("正在压缩图片");
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            File compressFile = Compresser.getInstance()
                                    .compressImage(Compresser.THIRD_GEAR, new File(path),
                                            mImageDir);
                            if (compressFile != null && compressFile.exists()) {
                                mDataList.add(compressFile.getAbsolutePath());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mProgressDialog.dismiss();
                                        mAdapter.notifyDataSetChanged();
                                        setImageNum();
                                    }
                                });
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }

        }
    }

    /** 拍照的文件地址 */
    private String path = "";
    /** 拍照请求码 */
    private static final int TAKE_PICTURE = 0x000003;

    /**
     * 拍照
     */
    public void toCamera() {
        if (UpImageAdapter.MAX_IMAGE_SIZE <= 0) {
            Utils.showToast(this, "已达到上传图片上限!");
            return;
        }
        File vFile = new File(Environment.getExternalStorageDirectory()
                + "/myimage/", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + ".jpg");

        if (!vFile.exists()) {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        } else {
            if (vFile.exists()) {
                vFile.delete();
            }
        }
        path = vFile.getPath();
        /*获取当前系统的android版本号*/
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(vFile));
            startActivityForResult(intent, TAKE_PICTURE);
        } else {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, vFile.getAbsolutePath());
            Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, TAKE_PICTURE);
        }
    }

    @Override
    protected void onDestroy() {
        if (mLocationUtils != null) {
            mLocationUtils.stopLocationClient();
        }
        super.onDestroy();
    }
}
