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

import android.annotation.SuppressLint;
import android.app.Activity;
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.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.AudioRecordButton;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.string.StringUtil;
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.base.C;
import com.tofly.ghrq_route.module.emergencyHandle.EmergencyTool;
import com.tofly.ghrq_route.module.emergencyHandle.controller.EmergencyCallBack;
import com.tofly.ghrq_route.module.emergencyHandle.domain.EmergencyHandleData;
import com.tofly.ghrq_route.module.emergencyHandle.domain.MyEmergencyEvent;
import com.tofly.ghrq_route.module.gps.service.AmapLocationHelper;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.DepartmentBean;
import com.tofly.ghrq_route.module.user.domain.DepartmentUserBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.ui.activity.UiCheckAddr;
import com.tofly.ghrq_route.common.ui.dialog.MultiUserSelectDailog;
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.SnackBarUtil;
import com.tofly.ghrq_route.common.util.SpinnerUtils;
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.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

@SuppressLint("NonConstantResourceId")
public class UiEmergencyReport extends BaseUi {
    @BindView(R.id.coordinator_layout)
    CoordinatorLayout mainRoot;
    @BindView(R.id.edit_report_addr)
    EditText editReportAddr;
    @BindView(R.id.edit_alert_name)
    EditText editAlertName;
    @BindView(R.id.edit_contact_phone)
    EditText editContactPhone;
    @BindView(R.id.spinner_level_one_type)
    AppCompatSpinner spinnerLevelOne;
    @BindView(R.id.spinner_level_two_type)
    AppCompatSpinner spinnerLevelTwo;
    @BindView(R.id.spinner_handle_depart)
    AppCompatSpinner spinnerHandleDepart;
    @BindView(R.id.spinner_handle_user)
    AppCompatSpinner spinnerHandleUser;
    @BindView(R.id.spinner_assist_depart)
    AppCompatSpinner spinnerAssistDepart;
    @BindView(R.id.text_user_coprocessor)
    TextView textAssistUser;
    @BindView(R.id.edit_report_note)
    EditText editReportNote;
    @BindView(R.id.btn_audio_record)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindArray(R.array.emergency_level_one)
    String[] emergeLevelOnes;
    @BindArray(R.array.emergency_leak)
    String[] emergeLeaks;
    @BindArray(R.array.emergency_no_leak)
    String[] emergeNoLeaks;


    private int indexLevelOne = -1;

    private int indexLevelTwo = -1;

    private int indexHandleDepart = -1;

    private int indexHandleUser = -1;

    private int indexAssistDepart = -1;

    private int indexAssistUser = -1;

    private String mAssistDepartId = null;

    protected PhotoHelper photoHelper;

    protected PermissionHelper permissionHelper;

    private final EmergencyHandleData mEmergencyBean = new EmergencyHandleData();

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

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

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

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

    private AudioRecordHelper audioRecordHelper;

    private EmergencyTool emergencyTool;

    private FileViewUtil fileViewUtil;

    private AmapLocationHelper amapLocationHelper;

    private LocationUtil_xu.CoordinateClass mTappedCoordinate = null;

    private MultiUserSelectDailog userSelectDailog;

    private List<DepartmentUserBean> mCoprocessorList;

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

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

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

    private void initView() {
        setDarkStatusBar();
    }

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

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

        emergencyTool = EmergencyTool.getInstance();

        amapLocationHelper = new AmapLocationHelper(this);
        amapLocationHelper.startLocating();

        setLevelOneAdapter();

        getDepartments();
    }

    private void initListener() {
        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);

        amapLocationHelper.setMapLocationListener((location, addr, projLoc) -> {
            mTappedCoordinate = new LocationUtil_xu.CoordinateClass(projLoc.getX(), projLoc.getY(), addr);
            editReportAddr.setText(addr);

            amapLocationHelper.reserveLocation(location.getX(), location.getY());
        });

        amapLocationHelper.setReserveLocListener((isSuccess, addr) -> {
            if (isSuccess) {
                mTappedCoordinate.addr = addr;
                editReportAddr.setText(addr);
            }
        });
    }

    @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()) {
                uploadEmergencyAlert();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @OnItemSelected({R.id.spinner_level_one_type, R.id.spinner_level_two_type, R.id.spinner_handle_depart,
            R.id.spinner_handle_user, R.id.spinner_assist_depart})
    public void onItemSelected(AdapterView<?> parent, int position){
        switch (parent.getId()) {
            case R.id.spinner_level_one_type:
                indexLevelOne = position;
                setLevelTwoAdapter();
                break;
            case R.id.spinner_level_two_type:
                indexLevelTwo = position;
                break;
            case R.id.spinner_handle_depart:
                indexHandleDepart = position;
                DepartmentBean departmentBean = mDepartmentList.get(position);
                if (departmentBean != null) {
                    getDepartmentUsers(departmentBean.getId(), false);
                }
                break;
            case R.id.spinner_handle_user:
                indexHandleUser = position;
                break;
            case R.id.spinner_assist_depart:
                indexAssistDepart = position;
                departmentBean = mDepartmentList.get(position);
                if (departmentBean != null) {
                    mAssistDepartId = departmentBean.getId();
                }
                textAssistUser.setText("请选择协助人员");
                if (userSelectDailog != null)
                    userSelectDailog.setDepartment(mAssistDepartId);
                //SpinnerUtils.setTextForSpinner(this, spinnerAssistUser, "请选择协助人员");
                break;
/*            case R.id.spinner_assist_user:
                indexAssistUser = position;
                break;*/
        }
    }

    private void getDepartments() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(this, false, new UserCallBack(){
            @Override
            public void onGetDepartmentList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentBean> departmentList) {
                super.onGetDepartmentList(isSuccess, errorCode, errMsg, departmentList);
                if (isSuccess) {
                    mDepartmentList = departmentList;
                    setDepartmentAdapter();
                }else {
                    SnackBarUtil.showSnackAlways(mainRoot, "获取部门失败", "重试", view -> getDepartments());
                }
            }
        });
    }

    private void setDepartmentAdapter(){
        if (mDepartmentList != null) {
            List<String> typeNameList = new ArrayList<>();
            for (DepartmentBean departmentBean : mDepartmentList) {
                typeNameList.add(departmentBean.getName());
            }
            SpinnerUtils.setAdapter(this, spinnerHandleDepart, typeNameList);
            SpinnerUtils.setAdapter(this, spinnerAssistDepart, typeNameList);
        }
    }

    private void getDepartmentUsers(String departId, boolean assist) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(this, departId, new UserCallBack(){
            @Override
            public void onGetDepartmentUserList(boolean isSuccess, int errorCode, String errMsg,
                                                List<DepartmentUserBean> userList) {
                super.onGetDepartmentUserList(isSuccess, errorCode, errMsg, userList);
                if (isSuccess) {
                    mUserList = userList;
                    setUserAdapter(assist);
                }else {
                    SnackBarUtil.showSnackAlways(mainRoot, "获取部门用户失败", "重试",
                            view -> getDepartmentUsers(departId, assist));
                }
            }
        });
    }

    private void setUserAdapter(boolean assist) {
        List<String> levelNameList = new ArrayList<>();
        for (DepartmentUserBean userBean : mUserList) {
            levelNameList.add(userBean.getRealName());
        }
        if (assist) {
            //SpinnerUtils.setAdapter(this, spinnerAssistUser, levelNameList);
        }else {
            SpinnerUtils.setAdapter(this, spinnerHandleUser, levelNameList);
        }
    }

    private void setLevelOneAdapter(){
        SpinnerUtils.setAdapter(this, spinnerLevelOne, emergeLevelOnes);
    }

    private void showMultiUserSelectDialog() {
        if (userSelectDailog == null) {
            userSelectDailog = new MultiUserSelectDailog(this);
            userSelectDailog.setClicklistener(userBeans -> {
                mCoprocessorList = userBeans;
                List<String> coprocessorNames = new ArrayList<>();
                for (DepartmentUserBean departmentUserBean : mCoprocessorList) {
                    coprocessorNames.add(departmentUserBean.getRealName());
                }
                String names = StringUtil.listToString(coprocessorNames, ',');
                textAssistUser.setText(names);
            });
        }
        userSelectDailog.show();
    }

    private void setLevelTwoAdapter(){
        List<String> nameList = new ArrayList<>();
        switch (indexLevelOne) {
            case 0:
                nameList = Arrays.asList(emergeLeaks);
                break;
            case 1:
                nameList = Arrays.asList(emergeNoLeaks);
                break;
            case 2:
                indexLevelTwo = -1;
                break;
            default:
                break;
        }
        SpinnerUtils.setAdapter(this, spinnerLevelTwo, nameList);
    }

    @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 (requestCode == C.REQUEST_CODE.SELECT_ADDR_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    mTappedCoordinate =
                            (LocationUtil_xu.CoordinateClass) bundle.getSerializable(LocationUtil.CURRENT_LOCATION_KEY);
                    if (mTappedCoordinate != null && mTappedCoordinate.addr != null) {
                        editReportAddr.setText(mTappedCoordinate.addr);
                    }
                }
            }
        }else {
            if (photoHelper != null) {
                photoHelper.handleActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @OnClick({R.id.btn_add_photo, R.id.layout_select_addr, R.id.layout_user_coprocessor})
    void onClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_add_photo:
                showAddPictureDialog();
                break;
            case R.id.layout_select_addr:
                gotoUiCheckAddr();
                break;
            case R.id.layout_user_coprocessor:
                showMultiUserSelectDialog();
                break;
        }
    }

    private void gotoUiCheckAddr() {
        UiCheckAddr.startActivityForResult(this,
                UiCheckAddr.SELECT_MODE.TROUBLE_SELECT_ADDR_UPDATE, mTappedCoordinate);
    }

    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 = new WaterMarkParams();
        params.mbNeedGps = 1;
        if (mTappedCoordinate != null) {
            String strLng = LocationUtil.formatLocation(mTappedCoordinate.Longtitude);
            String strLat = LocationUtil.formatLocation(mTappedCoordinate.Latitude);
            if (!strLng.isEmpty() && !strLat.isEmpty()) {
                double lng = Double.parseDouble(strLng);
                double lat = Double.parseDouble(strLat);
                strLng = LocationUtil.formatLocation(lng);
                strLat = LocationUtil.formatLocation(lat);
                params.mLongitude = strLng;
                params.mLatitude = strLat;
            }
            params.mAddress = mTappedCoordinate.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 (editAlertName.getText().toString().isEmpty()) {
            editAlertName.requestFocus();
            toast(R.string.emergency_report_empty_alerter);
            return false;
        }

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

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

        if (indexLevelOne == -1) {
            toast(R.string.emergency_report_empty_level_one);
            return false;
        }

        if (mUserList == null || mUserList.isEmpty() || indexHandleUser == -1) {
            toast(R.string.emergency_report_empty_handle_user);
            return false;
        }

        if (mPicturesUpload.isEmpty() && mAudiosRecords.isEmpty() && mDocumentsUpload.isEmpty()) {
            toast(R.string.report_empty_file);
            return false;
        }

        return true;
    }

    private void collectData() {
        String emergencyId = UUID.randomUUID().toString();
        mEmergencyBean.setId(emergencyId);
        /*报警人姓名*/
        String name = editAlertName.getText().toString();
        mEmergencyBean.setAlarmPeopleName(name);
        /*联系电话*/
        String phone = editContactPhone.getText().toString();
        mEmergencyBean.setContactPhone(phone);
        /*应急上报详情*/
        String notes = editReportNote.getText().toString();
        mEmergencyBean.setDescription(notes);
        /*隐患地址*/
        double lng = mTappedCoordinate.Longtitude;
        mEmergencyBean.setX(lng);
        double lat = mTappedCoordinate.Latitude;
        mEmergencyBean.setY(lat);
        String addr = editReportAddr.getText().toString();
        mEmergencyBean.setAddress(addr);
        /*一级抢修分类*/
        String levelOne = emergeLevelOnes[indexLevelOne];
        mEmergencyBean.setTypeMain(indexLevelOne + 1);
        mEmergencyBean.setTypeMainName(levelOne);
        /*二级抢修分类*/
        int levelTwo = -1;
        String levelTwoName = null;
        switch (indexLevelOne) {
            case 0:
                levelTwo = indexLevelTwo;
                levelTwoName = emergeLeaks[indexLevelTwo];
                break;
            case 1:
                levelTwo = emergeLeaks.length + indexLevelTwo;
                levelTwoName = emergeNoLeaks[indexLevelTwo];
                break;
        }
        mEmergencyBean.setType(levelTwo + 1);
        mEmergencyBean.setTypeName(levelTwoName);
        /*处理人员*/
        DepartmentBean departBean = mDepartmentList.get(indexHandleDepart);
        mEmergencyBean.setDepartmentId(departBean.getId());
        mEmergencyBean.setDepartmentName(departBean.getName());
        DepartmentUserBean userBean = mUserList.get(indexHandleUser);
        mEmergencyBean.setDispatchUserId(userBean.getId());
        mEmergencyBean.setDispatchUserName(userBean.getRealName());
        /*协同处理人员*/
        departBean = mDepartmentList.get(indexAssistDepart);
        mEmergencyBean.setAssistantDepartment(departBean.getId());
        mEmergencyBean.setAssistantDepartmentName(departBean.getName());
        if (mCoprocessorList != null && mCoprocessorList.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < mCoprocessorList.size(); i++) {
                DepartmentUserBean departmentUserBean = mCoprocessorList.get(i);
                String userid = departmentUserBean.getId();
                stringBuilder.append(userid);
                if (i < mCoprocessorList.size() - 1) {
                    stringBuilder.append(",");
                }
            }
            mEmergencyBean.setAssistantUserId(stringBuilder.toString());
        }
    }

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

    private void uploadNewEmergency() {
        collectData();
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(mAudiosRecords);
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        emergencyTool.uploadNewEmergency(this, mEmergencyBean, mPicturesUpload, audioBeans, mDocumentsUpload, new EmergencyCallBack(){
            @Override
            public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                super.onSetData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    EventBus.getDefault().post(new MyEmergencyEvent(MyEmergencyEvent.EMERGENCY_UPLOADED));
                    showUploadFinishedDialog();
                }
            }
        });
    }

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