package com.navinfo.outdoor.util;

import android.app.Activity;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.github.lazylibrary.util.ZipUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.bean.ChargingPileSaveBean;
import com.navinfo.outdoor.bean.OtherUploadPicBean;
import com.navinfo.outdoor.bean.PoiSaveBean;
import com.navinfo.outdoor.bean.PoiUploadBean;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.room.ChargingPileEntity;
import com.navinfo.outdoor.room.InsertAndUpdateUtils;
import com.navinfo.outdoor.room.PoiDatabase;
import com.navinfo.outdoor.room.PoiEntity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Response;

/**
 * Poi数据保存公共类
 */
public class PoiSaveUtils {
    private Activity mContext;
    private Gson gson;
    private static PoiSaveUtils instance;
    private int anInt=0;
    private int bInt=0;

    public static PoiSaveUtils getInstance(Activity mContext) {
        if (instance == null) {
            instance = new PoiSaveUtils(mContext);
        }
        return instance;
    }

    private PoiSaveUtils(Activity mContext) {
        this.mContext = mContext;
        this.gson = new Gson();
    }

    /**
     * 批量上传数据到服务端
     */
    public void uploadPoiEntityBatch(List<PoiEntity> poiEntityList) {
        if (poiEntityList == null || poiEntityList.isEmpty()) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (PoiEntity poiEntity : poiEntityList) {
                    if (poiEntity.getType() == 2) { // 如果是充电站数据，首先检查子充电桩的状态
                        if (saveChargingPileByChargingStation(poiEntity)) {
                            if (savePoiNet(poiEntity) == 200) { // 网络保存成功
                                // 开始上传流程
                                if (saveChargingPileUploadChargingStation(poiEntity)) {
                                    uploadPoiNet(poiEntity);
                                }
                            }
                        }
                    } else if (poiEntity.getType() == 6) {//面状任务


                    } else {//其他类型
                        if (savePoiNet(poiEntity) == 200) { // 网络保存成功
                            //走上传流程：
                            uploadPoiNet(poiEntity);
                        }
                    }
                }
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Message obtain = Message.obtain();
                        obtain.what = Constant.EVENT_STAY_REFRESH;
                        obtain.obj = "提交成功"+anInt+",提交失败"+bInt;
                        EventBus.getDefault().post(obtain);
                    }
                });

            }
        }).start();
    }

//    /**
//     * 保存数据到本地，保存后taskStatus为2
//     * */
//    public void savePoiLocal(PoiEntity poiEntity) {
//        if (poiEntity!=null) {
//            XXPermissions.with(mContext)
//                    //读写权限
//                    .permission(Permission.MANAGE_EXTERNAL_STORAGE)
//                    .request(new OnPermissionCallback() {
//                        @Override
//                        public void onGranted(List<String> permissions, boolean all) {
//                            poiEntity.setTaskStatus(2);
//                            InsertAndUpdateUtils.getInstance().insertOrUpdate(mContext, poiEntity);
//                        }
//
//                        @Override
//                        public void onDenied(List<String> permissions, boolean never) {
//
//                        }
//                    });
//        }
//    }

    /**
     * 保存数据到服务
     */
    public int savePoiNet(PoiEntity poiEntity) {
        if (poiEntity.getTaskStatus() >= 3) {
            return 200;
        }
        String url = null;
        HttpParams httpParams = new HttpParams();
        //1 "POI"2 "充电站"3 "POI录像"4 "道路录像"5 "其他"6 "面状任务"
        if (poiEntity.getType() == 1) {
            httpParams.put("taskId", poiEntity.getTaskId());
            httpParams.put("name", poiEntity.getName());
            httpParams.put("address", poiEntity.getAddress());
            httpParams.put("existence", poiEntity.getExistence());
            httpParams.put("geo", poiEntity.getGeoWkt());
            httpParams.put("memo", poiEntity.getMemo());
            httpParams.put("telephone", poiEntity.getTelPhone());
            url = HttpInterface.SUBMIT_POI_TASK;
        } else if (poiEntity.getType() == 2) {
            httpParams.put("taskId", poiEntity.getTaskId());
            httpParams.put("sptype", poiEntity.getStation_type());
            httpParams.put("name", poiEntity.getName());
            httpParams.put("address", poiEntity.getAddress());
            httpParams.put("telephone", poiEntity.getTelPhone());
            httpParams.put("memo", poiEntity.getMemo());
            httpParams.put("geo", poiEntity.getGeoWkt());
            url = HttpInterface.SUBMIT_CTASK;
        } else if (poiEntity.getType() == 3) {
            httpParams.put("taskId", poiEntity.getTaskId());
            httpParams.put("name", poiEntity.getName());
            httpParams.put("address", poiEntity.getAddress());
            httpParams.put("workType", poiEntity.getWork_type());
            httpParams.put("memo", poiEntity.getMemo());
            url = HttpInterface.INSIDE_API_LIST;
        } else if (poiEntity.getType() == 4) {
            httpParams.put("taskId", poiEntity.getTaskId());
            httpParams.put("name", poiEntity.getName());
            httpParams.put("address", poiEntity.getAddress());
            httpParams.put("workType", poiEntity.getWork_type());
            httpParams.put("memo", poiEntity.getMemo());
            url = HttpInterface.ROAD_TASK_SUBMIT;
        } else if (poiEntity.getType() == 5) {
            httpParams.put("type", poiEntity.getStation_type());
            httpParams.put("taskId", poiEntity.getTaskId());
            httpParams.put("name", poiEntity.getName());
            httpParams.put("existence", poiEntity.getExistence());
            httpParams.put("geo", poiEntity.getGeoWkt());
            httpParams.put("memo", poiEntity.getMemo());
            url = HttpInterface.SUBMIT_OTHER_TASK;
        } else {
            return -1;
        }
        try {
            Response execute = OkGoBuilder.getInstance().url(url)
                    .Builder(mContext)
                    .token(Constant.ACCESS_TOKEN).params(httpParams).getSynchronization();
            if (execute.code() != 200) {
                return execute.code();
            }
            String bodyStr = execute.body().string();
            if (bodyStr == null) {
                return -1;
            }
            PoiSaveBean poiSaveBean = gson.fromJson(bodyStr, PoiSaveBean.class);
            if (poiSaveBean.getCode() == 200) {
                poiEntity.setTaskStatus(3);
                poiEntity.setBodyId(poiSaveBean.getBody());
            } else {
                return poiSaveBean.getCode();
            }
            InsertAndUpdateUtils.getInstance().insertOrUpdate(mContext, poiEntity);
            Log.d("TAGss", "savePoiNet: 保存成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 200;
//        OkGoBuilder.getInstance()
//                .Builder(mContext)
//                .url(HttpInterface.SUBMIT_POI_TASK)
//                .method(OkGoBuilder.GET)
//                .cls(PoiSaveBean.class)
//                .params(httpParams)
//                .callback(new Callback<PoiSaveBean>() {
//                    @Override
//                    public void onSuccess(PoiSaveBean poiSaveBean, int id) {
//                        Integer body = poiSaveBean.getBody();
//                        poiEntity.setBodyId(body);
//                        poiEntity.setTaskStatus(3);
//                        InsertAndUpdateUtils.getInstance().insertOrUpdate(mContext, poiEntity);
//                        Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onError(Throwable e, int id) {
//                        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
//                        Log.d("TAG", "onError: " + e.getMessage());
//                    }
//                }).build();
    }

    /**
     * 最终上传POI数据到服务
     */
    public void uploadPoiNet(PoiEntity poiEntity) {
        if (poiEntity == null) {
            Toast.makeText(mContext, "无法获取POI数据", Toast.LENGTH_SHORT).show();
            return;
        }
        int bodyId = poiEntity.getBodyId();
        if (bodyId == 0) {
            Toast.makeText(mContext, "该数据未保存到服务，无法上传", Toast.LENGTH_SHORT).show();
            return;
        }
        ArrayList<File> photoFile = new ArrayList<>();
        photoFile.clear();
        if (poiEntity.getPhotoInfo() != null) {
            if (poiEntity.getPhotoInfo().size() > 0) {
                for (int i = 0; i < poiEntity.getPhotoInfo().size(); i++) {
                    String photo = poiEntity.getPhotoInfo().get(i).getPhoto();
                    photoFile.add(new File(photo));
                }
            }
        }

        List<File> videoFileList = AWMp4ParserHelper.getInstance().getVideoFileListByUUID(poiEntity.getId());
        if (videoFileList!=null&&!videoFileList.isEmpty()) {
            List<File> txtFileList = new ArrayList<>();
            for (File videoFile: videoFileList) {
                File file = new File(videoFile.getAbsolutePath() + ".txt");
                txtFileList.add(file);
            }
            videoFileList.addAll(txtFileList);
        }
        File fileZip = new File(Constant.PICTURE_FOLDER, "files" + ".zip");
        ZipUtil.zipFiles(videoFileList, fileZip, null);
        photoFile.add(fileZip);

        String url = null;
        //1 "POI"2 "充电站"3 "POI录像"4 "道路录像"5 "其他"6 "面状任务"
        if (poiEntity.getType() == 1) {
            url = HttpInterface.POI_TASK_UPLOAD_PIC;
        } else if (poiEntity.getType() == 2) {
            url = HttpInterface.C_TASK_UP_LOAD_PIC;
        } else if (poiEntity.getType() == 3) {
            url = HttpInterface.POI_VIDEO_UPLOAD_PIC;
        } else if (poiEntity.getType() == 4) {
            url = HttpInterface.ROAD_TASK_UPLOAD_PIC;
        } else if (poiEntity.getType() == 5) {
            url = HttpInterface.OTHER_TASK_UPLOAD_PIC;
        }
        try {
            HttpParams httpParams=new HttpParams();
            httpParams.put("auditId",bodyId);
            Response execute = OkGoBuilder.getInstance()
                    .Builder(mContext)
                    .url(url)
                    .params(httpParams)
                    .token(Constant.ACCESS_TOKEN)
                    .fileList(photoFile).postFileSynchronization();
            if (execute.code() != 200) {
                return;
            }
            String bodyStr = execute.body().string();
            if (bodyStr == null) {
                return;
            }
            Gson gson = new Gson();
            OtherUploadPicBean otherUploadPicBean = gson.fromJson(bodyStr, OtherUploadPicBean.class);
            if (otherUploadPicBean.getCode() == 200) {
                PoiDatabase.getInstance(mContext).getPoiDao().deletePoiEntity(poiEntity);
                Log.d("TAGss", "uploadPoiNet: 成功");
               anInt++;
            } else {
                Log.d("TAGss", "uploadPoiNet: 失败");
               bInt++;
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
       /* OkGo
                // 请求方式和请求url
                .<OtherUploadPicBean>post(HttpInterface.POI_TASK_UPLOAD_PIC)
                // 请求的 tag, 主要用于取消对应的请求
                .params("auditId", bodyId)
                .addFileParams("file", poiPicList)
                .tag(this)
                .execute(new DialogCallback<OtherUploadPicBean>(OtherUploadPicBean.class) {
                    @Override
                    public void onSuccess(Response<OtherUploadPicBean> otherUploadPicBeanResponse) {
                        Toast.makeText(mContext, "上传成功", Toast.LENGTH_SHORT).show();
                      PoiDatabase.getInstance(mContext).getPoiDao().deletePoiEntity(poiEntity);
                    }

                    @Override
                    public void onError(Response<OtherUploadPicBean> response) {
                        super.onError(response);
                        Toast.makeText(mContext, response.message() + "", Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + response.message() + "");
                    }
                });*/
    }

    /**
     * 根据充电站数据检查充电桩数据，如果没有网络保存，则批量网络保存
     */
    private boolean saveChargingPileByChargingStation(PoiEntity chargingStationPoiEntity) {
        boolean result = true;
        if (chargingStationPoiEntity != null) {
            List<ChargingPileEntity> chargingPileEntityList = PoiDatabase.getInstance(mContext).getChargingPileDao().getChargingPileByStationId(chargingStationPoiEntity.getId());
            if (chargingPileEntityList != null && !chargingPileEntityList.isEmpty()) {
                // 依次上传充电桩数据，如果有一条数据未上传成功，则返回false
                for (ChargingPileEntity pileEntity : chargingPileEntityList) {
                    if (pileEntity.getBodyId() == 0) {
                        int saveResult = saveChargingPile2NetWork(pileEntity);
                        if (saveResult == 200) {
                            result = result & true;
                        } else {
                            result = result & false;
                        }
                    }
                }
            }
        }
        Log.d("TAGss", "saveChargingPileByChargingStation" + result);
        return result;
    }

    /**
     * 保存充电桩数据到服务端
     */
    private int saveChargingPile2NetWork(ChargingPileEntity chargingPileEntity) {
        HttpParams httpParams = new HttpParams();
        httpParams.put("taskId", chargingPileEntity.getTaskId());
        httpParams.put("name", chargingPileEntity.getName());
        httpParams.put("existence", chargingPileEntity.getExist());
        httpParams.put("geo", chargingPileEntity.getP());
        httpParams.put("memo", chargingPileEntity.getMemo());
        httpParams.put("ffid", chargingPileEntity.getFid());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("cp_openType", chargingPileEntity.getCp_openType());
        hashMap.put("cp_floor", chargingPileEntity.getCp_floor());
        hashMap.put("cp_availableState", chargingPileEntity.getCp_availableState());
        hashMap.put("sign_exist", chargingPileEntity.getSign_exist());
        httpParams.put("detail", String.valueOf(hashMap));
        try {
            Response execute = OkGoBuilder.getInstance()
                    .Builder(mContext)
                    .url(HttpInterface.SUBMIT_CSTASK)
                    .token(Constant.ACCESS_TOKEN)
                    .params(httpParams).getSynchronization();
            if (execute.code() != 200) {
                return execute.code();
            }
            String responseBodyStr = execute.body().string();
            if (responseBodyStr == null) {
                return -1;
            }
            if (responseBodyStr != null) {
                Gson gson = new Gson();
                ChargingPileSaveBean chargingPileSaveBean = gson.fromJson(responseBodyStr, ChargingPileSaveBean.class);
                if (chargingPileSaveBean.getCode() != 200) {
                    return chargingPileSaveBean.getCode();
                }
                Log.d("TAGss", "saveChargingPile2NetWork" + 200);
                chargingPileEntity.setBodyId(chargingPileSaveBean.getBody());
                InsertAndUpdateUtils.getInstance().insertOrUpdateChargingPile(mContext, chargingPileEntity); // 更新当前充电桩的bodyId
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 200;
    }

    /**
     * 根据充电站数据检查充电桩数据，如果没有网络上传，则批量网络上传
     */
    private boolean saveChargingPileUploadChargingStation(PoiEntity chargingStationPoiEntity) {
        boolean result = true;
        if (chargingStationPoiEntity != null) {
            // 首先批量上传充电桩数据
            List<ChargingPileEntity> chargingPileEntityList = PoiDatabase.getInstance(mContext).getChargingPileDao().getChargingPileByStationId(chargingStationPoiEntity.getId());
            if (chargingPileEntityList != null && !chargingPileEntityList.isEmpty()) {
                for (ChargingPileEntity chargingPileEntity : chargingPileEntityList) {
                    if (chargingPileEntity.getBodyId() != 0) {
                        int pileResult = chargingPileUploadNetWork(chargingPileEntity);
                        if (pileResult == 200) {
                            result = result & true;
                        } else {
                            result = result & false;
                        }
                    }
                }
            }
        }
        Log.d("TAGss", "saveChargingPileUploadChargingStation" + result);
        return result;
    }

    /**
     * 上传充电桩数据到服务器
     */
    private int chargingPileUploadNetWork(ChargingPileEntity chargingPileEntity) {
        if (chargingPileEntity == null || chargingPileEntity.getBodyId() == 0) {
            Toast.makeText(mContext, "没有保存本地", Toast.LENGTH_SHORT).show();
            return -1;
        }

        List<File> chargingPileFileList = new ArrayList<>();
        if (chargingPileEntity.getPhotos() != null && !chargingPileEntity.getPhotos().isEmpty()) {
            for (String photoPath : chargingPileEntity.getPhotos()) {
                chargingPileFileList.add(new File(photoPath));
            }
        }

        try {
            HttpParams httpParams=new HttpParams();
            httpParams.put("auditId",chargingPileEntity.getBodyId());
            Response execute = OkGoBuilder.getInstance()
                    .Builder(mContext)
                    .url(HttpInterface.CS_TASK_UP_LOAD_PIC)
                    .token(Constant.ACCESS_TOKEN)
                    .params(httpParams)
                    .fileList(chargingPileFileList).postFileSynchronization();
            if (execute.code() != 200) {
                return execute.code();
            }
            String pileUpLoadResultStr = execute.body().string();
            if (pileUpLoadResultStr == null) {
                return -1;
            }
            if (pileUpLoadResultStr != null) {
                Gson gson = new Gson();
                PoiUploadBean uploadBeanResult = gson.fromJson(pileUpLoadResultStr, PoiUploadBean.class);
                if (uploadBeanResult.getCode() == 200) {
                    Log.d("TAGss", "chargingPileUploadNetWork" + 200);
                    PoiDatabase.getInstance(mContext).getChargingPileDao().deleteChargingPileEntity(chargingPileEntity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 200;

//        OkGo
//                // 请求方式和请求url
//                .<PoiUploadBean>post(HttpInterface.CS_TASK_UP_LOAD_PIC)
//                // 请求的 tag, 主要用于取消对应的请求
//                .params("auditId", chargingPileEntity.getBodyId())
//                .addFileParams("file", chargingPileFileList)
//                .tag(this)
//                .execute(new DialogCallback<PoiUploadBean>(PoiUploadBean.class) {
//                    @Override
//                    public void onSuccess(Response<PoiUploadBean> poiUploadBeanResponse) {
//                        dismissLoadingDialog();
//                        Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
//                        isChargingPoleUploaded = true;
//                        if (isChargeStationUploaded && isChargingPoleUploaded) {
//                            getActivity().runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    getActivity().onBackPressed();//回退
//                                }
//                            });
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<PoiUploadBean> poiUploadBeanResponse) {
//                        super.onError(poiUploadBeanResponse);
//                        dismissLoadingDialog();
//                        Toast.makeText(getActivity(), poiUploadBeanResponse.code() + "", Toast.LENGTH_SHORT).show();
//                        Log.d("TAG", "onError: " + poiUploadBeanResponse.code() + "");
//                    }
//                });
    }

}
