package com.tofly.ghrq_route.module.trouble.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.google.gson.Gson;
import com.mgq.base.utils.progressdialog.ProgressManager;
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.module.gps.service.AmapLocationHelper;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.domain.DeviceAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.MyTroubleEvent;
import com.tofly.ghrq_route.module.trouble.domain.PipeAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.troubleType.TroubleTypeTool;
import com.tofly.ghrq_route.module.troubleType.controller.TroubleTypeCallBack;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleRiskLevelBean;
import com.tofly.ghrq_route.module.troubleType.domain.TroubleTypeBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
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.FileViewUtil;
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.util.ArrayList;
import java.util.Date;
import java.util.List;

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

public class UiTroubleUndertakerHandle extends BaseUi {
    @BindView(R.id.spinner_trouble_event_type)
    AppCompatSpinner spinnerTroubleEventType;
    @BindView(R.id.spinner_trouble_type)
    AppCompatSpinner spinnerTroubleType;
    @BindView(R.id.spinner_risk_level)
    AppCompatSpinner spinnerRiskLevel;
    @BindView(R.id.layout_type_risk_module)
    LinearLayout layoutTypeRiskModule;
    @BindView(R.id.edit_report_note)
    EditText editReportNote;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.btn_audio_record)
    MyAudioRecordButton btnAddAudio;
    @BindArray(R.array.trouble_handle_event_types)
    String[] eventTypes;

    private int mEventType = 0; // 0:非隐患 1: 一般隐患 2: 重大隐患

    private List<TroubleTypeBean> mTroubleTypeList;

    private List<TroubleRiskLevelBean> mTroubleLevelList;

    private int indexTroubleType = -1;

    private int indexTroubleLevel = -1;

    private List<PipeAttributesBean> mPipeFeatures;

    private List<DeviceAttributesBean> mDeviceFeatures;

    protected PhotoHelper photoHelper;

    protected PermissionHelper permissionHelper;

    private FileViewUtil fileViewUtil;

    private TroubleBean mTroubleBean;

    private List<TroublePictureBean> mPicturesUpload = new ArrayList<>();

    private List<Record> mAudiosRecords = new ArrayList<>();

    private List<TroubleAudioBean> mDocumentsUpload = new ArrayList<>();

    private AudioRecordHelper audioRecordHelper;

    private TroubleTool troubleTool;

    private AmapLocationHelper amapLocationHelper;

    private LocationUtil_xu.CoordinateClass mCoordinate = null;

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

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

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

    private void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mTroubleBean = (TroubleBean) bundle.getSerializable(TroubleBean.TROUBLE_BEAN_KEY);
            if (mTroubleBean != null) {

            }
        }
    }

    private void initData() {
        permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);
        fileViewUtil = new FileViewUtil(this);
        amapLocationHelper = new AmapLocationHelper(this);

        audioRecordHelper = new AudioRecordHelper(this, permissionHelper, btnAddAudio);
        audioRecordHelper.initRecordButton();

        troubleTool = TroubleTool.getInstance();

        amapLocationHelper.startLocating();

        setWorkStateAdapter();
    }

    private void initListener() {
        amapLocationHelper.setMapLocationListener((location, addr, projLoc) ->
                mCoordinate = new LocationUtil_xu.CoordinateClass(location.getX(), location.getY(), addr));

        AudioRecordButton.AudioFinishRecorderListener mRecorderListener = (seconds, filePath) -> {
            String time = DateUtils.getDate(new Date().getTime());
            int audioLength = (int) seconds <= 0 ? 1 : (int) seconds;

            final Record recordModel = new Record();
            recordModel.setSecond(audioLength);
            recordModel.setPath(filePath);
            recordModel.setPlayed(false);
            recordModel.setCreateTime(time);
            mAudiosRecords.add(recordModel);

            View view = getRecordViewFromAudio(recordModel);
            photoGallery.addView(view);
        };
        btnAddAudio.setAudioFinishRecorderListener(mRecorderListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_commit) {
            hideSoftKeyboard();
            if (isValid()) {
                uploadTroubleAlert();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void setWorkStateAdapter() {
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, eventTypes) {
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerTroubleEventType.setAdapter(adapterDevType);
        spinnerTroubleEventType.setSelection(mEventType);
    }

    @OnItemSelected({R.id.spinner_trouble_event_type, R.id.spinner_trouble_type, R.id.spinner_risk_level})
    public void onItemSelected(AdapterView<?> parent, int position) {
        switch (parent.getId()) {
            case R.id.spinner_trouble_event_type:
                mEventType = position;
                onSetWorkState();
                break;
            case R.id.spinner_trouble_type:
                indexTroubleType = position;
                break;
            case R.id.spinner_risk_level:
                indexTroubleLevel = position;
                break;
        }
    }

    private void onSetWorkState() {
        switch (mEventType) {
            case 0:  //非隐患
                layoutTypeRiskModule.setVisibility(View.GONE);
                indexTroubleType = -1;
                indexTroubleLevel = -1;
                break;
            case 1:   //是隐患
                layoutTypeRiskModule.setVisibility(View.VISIBLE);
                getTroubleTypeRisk();
                break;
        }
    }

    private void getTroubleTypeRisk() {
        if (mTroubleTypeList == null || mTroubleTypeList.isEmpty()) {
            getTroubleTypes();
        }

        if (mTroubleLevelList == null || mTroubleLevelList.isEmpty()) {
            getTroubleLevels();
        }
    }

    private void getTroubleTypes() {
        TroubleTypeTool troubleTypeTool = TroubleTypeTool.getInstance();
        troubleTypeTool.getTroubleTypeList(this, new TroubleTypeCallBack() {
            @Override
            public void onGetTroubleTypeList(boolean isSuccess, int errorCode, String errMsg, List<TroubleTypeBean> troubleTypeList) {
                super.onGetTroubleTypeList(isSuccess, errorCode, errMsg, troubleTypeList);
                if (isSuccess) {
                    mTroubleTypeList = troubleTypeList;
                    setTroubleTypeAdapter();
                }
            }
        });
    }

    private void setTroubleTypeAdapter() {
        List<String> typeNameList = new ArrayList<>();
        for (TroubleTypeBean troubleTypeBean : mTroubleTypeList) {
            typeNameList.add(troubleTypeBean.getName());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, typeNameList) {
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerTroubleType.setAdapter(adapterDevType);
    }

    private void getTroubleLevels() {
        TroubleTypeTool troubleTypeTool = TroubleTypeTool.getInstance();
        troubleTypeTool.getTroubleLevelList(this, new TroubleTypeCallBack() {
            @Override
            public void onGetTroubleRiskLevelList(boolean isSuccess, int errorCode, String errMsg, List<TroubleRiskLevelBean> riskLevelList) {
                super.onGetTroubleRiskLevelList(isSuccess, errorCode, errMsg, riskLevelList);
                if (isSuccess) {
                    mTroubleLevelList = riskLevelList;
                    setTroubleLevelAdapter();
                }
            }
        });
    }

    private void setTroubleLevelAdapter() {
        List<String> levelNameList = new ArrayList<>();
        for (TroubleRiskLevelBean levelBean : mTroubleLevelList) {
            levelNameList.add(levelBean.getName());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, levelNameList) {
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerRiskLevel.setAdapter(adapterDevType);
    }

    @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);
        }
    }

    @OnClick({R.id.btn_add_photo})
    void onClicked(View view) {
        if (view.getId() == R.id.btn_add_photo) {
            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();
                            } else if (i == 2) {
                                startAudioRecord();
                            } else if (i == 3) {
                                requestFileView();
                            }
                        });
        dialog.setCancelable(true);
        dialog.show();
    }

    private WaterMarkParams getWaterMarkParams() {
        WaterMarkParams params = null;
        if (mCoordinate != null) {
            params = new WaterMarkParams();
            params.mbNeedGps = 1;
            String strLng = LocationUtil.formatLocation(mCoordinate.Longtitude);
            String strLat = LocationUtil.formatLocation(mCoordinate.Latitude);
            if (!strLng.isEmpty() && !strLat.isEmpty()) {
                params.mLongitude = strLng;
                params.mLatitude = strLat;
            }
            params.mAddress = mCoordinate.addr;
            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, this::getWaterMarkParams, (success, errStr, pictureBean) -> {
            if (success) {
                if (pictureBean != null) {
                    mPicturesUpload.add(pictureBean);//本地缓存
                    View view = getPhotoViewFromPath(pictureBean);
                    photoGallery.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);
                    photoGallery.addView(view);
                }
            } else {
                toast(errStr);
            }
        });
    }

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

    private void startAudioRecord() {
        if (audioRecordHelper != null) {
            boolean hasPermission = audioRecordHelper.checkRecordPermission();
            if (!hasPermission) {
                audioRecordHelper.requestRecordPermission();
            }else {
                btnAddAudio.setCanRecord(true);
                btnAddAudio.setRecordMode();
            }
        }
        btnAddAudio.performClick();
    }

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

    private void requestFileView() {
        photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    photoGallery.removeView(view1);
                    mDocumentsUpload.remove(document1);
                });
                if (rootView != null) {
                    mDocumentsUpload.add(document);
                    photoGallery.addView(rootView);
                }
            }
        });
    }

    private boolean isValid() {
/*        if (mTappedCoordinate == null ||
                mTappedCoordinate.Longtitude == null || mTappedCoordinate.Latitude == null) {
            toast("当前位置不可用");
            return false;
        }

        if ((mPipeFeatures == null || mPipeFeatures.isEmpty()) &&
                (mDeviceFeatures == null || mDeviceFeatures.isEmpty())) {
            toast(R.string.trouble_report_empty_device);
            return false;
        }*/

        if (editReportNote.getText().toString().isEmpty()) {
            editReportNote.requestFocus();
            toast(R.string.trouble_onduty_route_note_hint);
            return false;
        }

        if (mEventType == 1) {    //是隐患
            if (mTroubleTypeList == null || mTroubleTypeList.isEmpty() || indexTroubleType == -1) {
                toast(R.string.trouble_report_empty_trotype);
                return false;
            }

            if (mTroubleLevelList == null || mTroubleLevelList.isEmpty() || indexTroubleLevel == -1) {
                toast(R.string.trouble_report_empty_trolevel);
                return false;
            }
        }

        return true;
    }

    private void collectData() {
        /*隐患详情*/
        String notes = editReportNote.getText().toString();
        mTroubleBean.setUndertakerHandleNotes(notes);
        /*隐患地址*/
        if (mCoordinate != null) {
            String lng = LocationUtil.formatLocation(mCoordinate.Longtitude);
            mTroubleBean.setLocationX(lng);
            String lat = LocationUtil.formatLocation(mCoordinate.Latitude);
            mTroubleBean.setLocationY(lat);
            String addr = mCoordinate.addr;
            mTroubleBean.setAddress(addr);
        }
        if (mEventType == 1) {    //是隐患
            TroubleTypeBean typeBean = mTroubleTypeList.get(indexTroubleType);
            mTroubleBean.setTroubleTypeId(typeBean.getId());
            mTroubleBean.setTroubleName(typeBean.getName());
            TroubleRiskLevelBean levelBean = mTroubleLevelList.get(indexTroubleLevel);
            mTroubleBean.setLevelId(levelBean.getId());
            mTroubleBean.setLevelName(levelBean.getName());
        }
        mTroubleBean.setEventType(mEventType);
        mTroubleBean.setEventTypeName(eventTypes[mEventType]);
        if (mPipeFeatures != null && mPipeFeatures.size() > 0) {
            Gson gson = new Gson();
            String strJson = gson.toJson(mPipeFeatures);
            mTroubleBean.setPipeInfo(strJson);
        }
        if (mDeviceFeatures != null && mDeviceFeatures.size() > 0) {
            Gson gson = new Gson();
            String strJson = gson.toJson(mDeviceFeatures);
            mTroubleBean.setDeviceInfo(strJson);
        }
    }

    private void uploadTroubleAlert() {
        String title = "上传数据";
        String content = "是否上传数据?";
        showAlertWithConfirmCancelButton(title, content, true, (dialogInterface, i) -> uploadTroubleData());
    }

    private void uploadTroubleData() {
        collectData();
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        troubleTool.undertakerHandleTroubleNoSave(this, mTroubleBean, mPicturesUpload, mAudiosRecords, mDocumentsUpload, new TroubleCallBack() {
            @Override
            public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                super.onSetData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    EventBus.getDefault().post(new MyTroubleEvent(MyTroubleEvent.TROUBLE_UPLOADED));
                    showUploadFinishedDialog();
                }
            }
        });
    }

    private void showUploadFinishedDialog() {
        int title = R.string.trouble_undertaker_handle_title;
        int msg = R.string.upload_ok;
        showAlertWithConfirmButton(title, msg, false, (dialogInterface, i) -> this.finish());
    }
}
