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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.esri.arcgisruntime.geometry.Point;
import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePlanRecordBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.recorder.AudioRecordHelper;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.hzw.graffiti.WaterMarkParams;

/**
 * Created by Amu on 2017/3/23.
 */

public class UiReportedClear extends BaseUi {
    @BindView(R.id.edit_report_note)
    EditText editReportNote;
    @BindView(R.id.reported_clear_addpic)
    Button reportedClearAddpic;
    @BindView(R.id.reported_clear_gallery)
    LinearLayout reportedClearGallery;
    @BindView(R.id.report_clear_addaudio)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.layout_addaudio_area)
    LinearLayout layoutAddAudioArea;
    @BindView(R.id.audio_record_gallery)
    LinearLayout layoutAudioGallery;

    private MenuItem menuCommit;
    private MenuItem menuSave;

    private TroubleTool troubleTool;
    private TroubleBean mTrouble;
    private OfflinePathBean mPlanPoint;
    private Point mLocation;
    private boolean mbIsClear;
    private boolean mbNeedRemoveCache = true;

    private List<TroublePictureBean> mPicturesUpload = new ArrayList<>();
    private PhotoHelper photoHelper;
    private PermissionHelper permissionHelper;

    private List<Record> mAudiosUpload = new ArrayList<>();
    private AudioRecordHelper audioRecordHelper;

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

        setContentView(R.layout.ui_reported_clear);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_danger_report_next, menu);
        menuCommit = menu.findItem(R.id.action_upload);
        menuSave = menu.findItem(R.id.action_save);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_upload:
                if (isValid()){
                    showUploadAlertDialog();
                }
                break;
            case R.id.action_save:
                if (isValid()){
                    showSaveAlertDialog();
                }
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {

    }

    private void initData() {
        troubleTool = TroubleTool.getInstance();
        permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null){
            mTrouble = (TroubleBean) bundle.getSerializable(TroubleBean.TROUBLE_BEAN_KEY);
            mPlanPoint = (OfflinePathBean) bundle.getSerializable(OfflinePathBean.PLAN_POINT_BEAN_KEY);
            mbIsClear = bundle.getBoolean(TroublePlanRecordBean.TROUBLE_RECORD_CLOSE_KEY, true);
            LocationUtil_xu.CoordinateClass coordinate = (LocationUtil_xu.CoordinateClass) bundle.getSerializable(LocationUtil.CURRENT_LOCATION_KEY);
            if (coordinate != null)
                mLocation = new Point(coordinate.Longtitude, coordinate.Latitude);
        }
    }

    private void initListener() {
        audioRecordHelper = new AudioRecordHelper(this, permissionHelper, btnAddAudio);
        audioRecordHelper.initRecordButton();
        AudioRecordButton.AudioFinishRecorderListener recorderListener = new AudioRecordButton.AudioFinishRecorderListener() {
            @Override
            public void onFinished(float seconds, String filePath) {
                final Record recordModel = new Record();
                String time = DateUtils.getDate(new Date().getTime());
                recordModel.setSecond((int) seconds <= 0 ? 1 : (int) seconds);
                recordModel.setPath(filePath);
                recordModel.setPlayed(false);
                recordModel.setCreateTime(time);
                mAudiosUpload.add(recordModel);
                View view = getRecordViewFromAudio(recordModel);
                layoutAudioGallery.addView(view);
            }
        };
        btnAddAudio.setAudioFinishRecorderListener(recorderListener);

        setOnNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeCacheFile();
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        removeCacheFile();
        finish();
    }

    private boolean isValid() {
        boolean isPictureValid = false;
        boolean isEditValid = false;

        String notes = editReportNote.getText().toString();
        if (!notes.isEmpty()){
            isEditValid = true;
        }

        if (mPicturesUpload != null && mPicturesUpload.size() > 0) {
            isPictureValid = true;
        }

        if (!isEditValid){
            toast("请输入详情");
            editReportNote.requestFocus();
            return false;
        }

        if (!isPictureValid) {
            toast("请选择图片");
            return false;
        }
        return true;
    }

    private void showSaveAlertDialog() {
        String title = "保存数据";
        String content = "是否保存数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mbIsClear)
                    saveTroubleClearInfo();
                else {
                    saveRouteRecordInfo();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void saveTroubleClearInfo(){

    }

    private void saveRouteRecordInfo(){

    }

    private void showUploadAlertDialog() {
        String title = "上传数据";
        String content = "是否上传数据?";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mbIsClear)
                    uploadClearRecord();
                else {
                    uploadRouteRecord();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void uploadClearRecord(){

    }

    private void uploadRouteRecord(){

    }

    private void onSaveFinished(){
        menuCommit.setEnabled(false);
        menuSave.setEnabled(false);
        mbNeedRemoveCache = false;
        String msg = mbIsClear ? REPORT_CLEAR_SAVED : REPORT_ROUTE_SAVED;
        EventBus.getDefault().post(new ReportClearMessageEvent(msg));
        showSaveFinishedDialog();
    }

    private void showSaveFinishedDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dangerreport_next_save_ok);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UiReportedClear.this.finish();
            }
        });
        builder.show();
    }

    private void onUploadFinished(boolean isSuccess){
        menuCommit.setEnabled(false);
        menuSave.setEnabled(false);
        String msg = mbIsClear ? REPORT_CLEAR_UPLOADED : REPORT_ROUTE_UPLOADED;
        EventBus.getDefault().post(new ReportClearMessageEvent(msg));
        showUploadFinishedDialog(isSuccess);
    }

    private void showUploadFinishedDialog(final boolean isSuccess){
        mbNeedRemoveCache = isSuccess;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(mbIsClear ? R.string.reported_clear_title : R.string.reported_route_title);
        builder.setMessage(isSuccess ?
                R.string.upload_ok : R.string.upload_fail_saved);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                removeCacheFile();
                UiReportedClear.this.finish();
            }
        });
        builder.show();
    }

    private void removeCacheFile(){
        if (!mbNeedRemoveCache)
            return;
        //删除临时文件
        if (mPicturesUpload != null && mPicturesUpload.size() > 0){
            for (TroublePictureBean pictureBean : mPicturesUpload){
                String file = pictureBean.getFilepath();
                FileUtil.deleteFile(file);
            }
        }
        if (mAudiosUpload != null && mAudiosUpload.size() > 0){
            for (Record record: mAudiosUpload){
                String file = record.getPath();
                FileUtil.deleteFile(file);
            }
        }
    }

    @OnClick({R.id.reported_clear_addpic})
    public void onClick(View view){
        if (view.getId() == R.id.reported_clear_addpic) {
            showAddPictureDialog();
        }
    }

    private void showAddPictureDialog(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this).
                setItems(new String[]{"拍照", "从手机相册选择"},
                        (arg0, i) -> {
                            if (i == 0) {
                                getPicFromSysCamera();
                            } else if (i == 1) {
                                getPicFromSysAlbums();
                            }
                        });
        dialog.setCancelable(true);
        dialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (photoHelper != null){
            photoHelper.handleActivityResult(requestCode, resultCode, data);
        }
    }

    private WaterMarkParams getWaterMarkParams(){
        WaterMarkParams params = null;
        if (mTrouble != null){
            params = new WaterMarkParams();
            params.mbNeedGps = 1;
            if (mLocation != null){
                double lon = mLocation.getX();
                double lat = mLocation.getY();
                BigDecimal decimal = new BigDecimal(lon);
                lon = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                decimal = new BigDecimal(lat);
                lat = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                params.mLongitude = Double.toString(lon);
                params.mLatitude = Double.toString(lat);
            }else {
                String strLng = mTrouble.getLocationX();
                String strLat = mTrouble.getLocationY();
                if (strLng != null && !strLng.isEmpty() && strLat != null && !strLat.isEmpty()){
                    double lon = Double.parseDouble(strLng);
                    double lat = Double.parseDouble(strLat);
                    BigDecimal decimal = new BigDecimal(lon);
                    lon = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                    decimal = new BigDecimal(lat);
                    lat = decimal.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                    params.mLongitude = Double.toString(lon);
                    params.mLatitude = Double.toString(lat);
                }
            }
            params.mGpsFlag = 0;
            params.mAddress = mTrouble.getAddress();
            UserBean userBean = BaseApp.getInstance().getLoginUser();
            if (userBean != null){
                params.mUser = userBean.getRealName();
                params.mCompany = userBean.getCompany_name();
            }
            params.mReportTime = DateUtils.getDate(new Date().getTime());
        }
        return params;
    }

    private void getPicFromSysCamera(){
        photoHelper.requestCameraPhoto(true, () -> getWaterMarkParams(), (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    reportedClearGallery.addView(view);
                }
            } else {
                toast(errStr);
            }
        });
    }

    private void getPicFromSysAlbums() {
        photoHelper.requestImagePhoto(true, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    reportedClearGallery.addView(view);
                }
            } else {
                toast(errStr);
            }
        });
    }

    private View getPhotoViewFromPath(TroublePictureBean pictureBean){
        return photoHelper.getPhotoViewFromPath(pictureBean,
                (view, picture) -> {
                    reportedClearGallery.removeView(view);
                    mPicturesUpload.remove(picture);
                });
    }

    private View getRecordViewFromAudio(Record record){
        return audioRecordHelper.getRecordViewFromAudio(record,
                mAudiosUpload, (view, record1) -> {
                    mAudiosUpload.remove(record1);
                    layoutAudioGallery.removeView(view);
                });

    }

    public final static String REPORT_CLEAR_SAVED = "reportClearSaved";
    public final static String REPORT_CLEAR_UPLOADED = "reportClearUploaded";
    public final static String REPORT_ROUTE_SAVED = "reportRouteSaved";
    public final static String REPORT_ROUTE_UPLOADED = "reportRouteUploaded";
    public static class ReportClearMessageEvent {
        public String message;
        public ReportClearMessageEvent(String message) {
            this.message = message;
        }
    }

    @Override
    protected void onStop() {
        BaseApp.cancelMultiRequest(getClass().getName());
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApp.cancelAllRequest(getClass().getName());
        //重置数据状态
        if (mAudiosUpload != null){
            for (Record record : mAudiosUpload) {
                record.setPlaying(false);
            }
        }
        MediaManager.release();//重置
    }
}
