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

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseFileActivity;
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.EmergencyOverData;
import com.tofly.ghrq_route.module.emergencyHandle.domain.MyEmergencyEvent;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyAssignHandleHistoryModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyAssignHandleReportModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyReportInfoModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencySignOverModuleLayout;
import com.tofly.ghrq_route.module.gps.GpsTool;
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.common.ui.dialog.SignatureBottomDialog;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.EventBusUtil;
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.date.DateUtils;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zombiexq on 2016/7/4.
 */
public class UiEmergencyAssignHandle extends BaseFileActivity {
    @BindView(R.id.coordinator_layout)
    CoordinatorLayout mainRoot;
    @BindView(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.main_toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout_module_emergency_handle_report)
    EmergencyAssignHandleReportModuleLayout handleReportModule;
    @BindView(R.id.layout_module_emergency_assign_handle_history)
    EmergencyAssignHandleHistoryModuleLayout handleHistoryModule;
    @BindView(R.id.layout_module_emergency_sign_over)
    EmergencySignOverModuleLayout signOverModule;
    @BindView(R.id.layout_module_emergency_info)
    EmergencyReportInfoModuleLayout emergencyInfoModule;

    private int mEmergencyId;

    private EmergencyHandleData mEmergencyData;

    private SignatureBottomDialog signatureBottomDialog;

    private EmergencyTool emergencyTool;

    private AmapLocationHelper amapLocationHelper;

    private LocationUtil_xu.CoordinateClass mTappedCoordinate = new LocationUtil_xu.CoordinateClass();

    protected List<TroublePictureBean> mSignaturePhoto = new ArrayList<>();

    private boolean mIsRejected = false;

    private MenuItem menuCommit;

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

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

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

        EventBusUtil.register(this);
    }

    @Override
    public void initView() {
        super.initView();
        initToolBar();
        setDarkStatusBar();
    }

    private void initToolBar() {
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        toolbar.setNavigationOnClickListener(v -> {
            this.finish();
        });
    }

    @Override
    public void initData() {
        super.initData();

        emergencyTool = EmergencyTool.getInstance();

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            EmergencyHandleData handleData =
                    (EmergencyHandleData) extras.getSerializable(EmergencyHandleData.EMERGENCY_DATA_KEY);
            if (handleData != null) {
                mEmergencyData = handleData;
                initEmergencyInfo(handleData);
            }
        }

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

    private void initEmergencyInfo(EmergencyHandleData handleData) {
        emergencyInfoModule.initEmergencyInfo(handleData);
        signOverModule.initEmergencyInfo(handleData);
        boolean isOver = emergencyTool.isEmergencyOver(handleData);
        if (isOver) {
            signOverModule.setVisibility(View.GONE);
            handleReportModule.setVisibility(View.VISIBLE);
            handleReportModule.initEmergencyInfo(handleData);
        }else {
            handleReportModule.setVisibility(View.GONE);
        }
        if (menuCommit != null) {
            menuCommit.setVisible(isOver);
        }

        handleHistoryModule.setVisibility(View.GONE);
        mIsRejected = mEmergencyData.getRejectedFlag() == 1;
        if (mIsRejected) {
            handleHistoryModule.setVisibility(View.VISIBLE);
            handleHistoryModule.initEmergencyInfo(handleData);
        }
    }

    @Override
    public void initListener() {
        super.initListener();

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

        TextView btnOverSign = signOverModule.findViewById(R.id.text_over_sign);
        btnOverSign.setOnClickListener(view -> emergencySignOver(mEmergencyData));

        Button btnSign = handleReportModule.findViewById(R.id.btn_add_signature);
        btnSign.setOnClickListener(view -> gotoUiSignature());
    }

    private void emergencySignOver(EmergencyHandleData handleData) {
        Location lastLocation = GpsTool.getInstance().getLocationInfo();
        if (lastLocation == null ||
                Double.isNaN(lastLocation.getLongitude()) || Double.isNaN(lastLocation.getLatitude())) {
            toast("当前位置不可用");
            return;
        }

        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);

        String emergencyId = handleData.getId();
        double lng = lastLocation.getLongitude();
        double lat = lastLocation.getLatitude();
        emergencyTool.emergencySignOver(this, emergencyId, lng, lat, 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_LIST_NEED_REFRESH));

                    handleData.setSignX(lng);
                    handleData.setSignY(lat);
                    handleData.setSignTime(DateUtils.getDate());
                    initEmergencyInfo(handleData);
                }else {
                    SnackBarUtil.showSnackAlways(mainRoot, "到位签到失败", "重试", view -> emergencySignOver(handleData));
                }
            }
        });
    }

    private void showSignatureDialog() {
        if (signatureBottomDialog == null)
            signatureBottomDialog = new SignatureBottomDialog(this);
        signatureBottomDialog.setGetSignature(signature -> {
            addSignatureView(signature);
        });
        signatureBottomDialog.setCancelable(false);
        signatureBottomDialog.setCanceledOnTouchOutside(false);
        signatureBottomDialog.show();
    }

    private void gotoUiSignature() {
        UiEmergencySignature.startActivityForResult(this);
    }

    private void addSignatureView(TroublePictureBean signature) {
        if (signature != null) {
            LinearLayout sign_gallery = handleReportModule.findViewById(R.id.sign_gallery);
            Button btnSign = handleReportModule.findViewById(R.id.btn_add_signature);
            View signView = photoHelper.getPhotoViewFromPath(signature,
                    (view, picture) -> {
                        if (sign_gallery != null)
                            sign_gallery.removeView(view);
                        FileUtil.deleteFile(picture.getFilepath());
                        mSignaturePhoto.remove(picture);
                        btnSign.setVisibility(View.VISIBLE);
                    });
            if (signView != null) {
                if (sign_gallery != null)
                    sign_gallery.addView(signView);
                mSignaturePhoto.add(signature);
                btnSign.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == C.REQUEST_CODE.SIGNATURE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    TroublePictureBean signature =
                            (TroublePictureBean) bundle.getSerializable(UiEmergencySignature.SIGNATURE_PICTURE_BEAN_KEY);
                    addSignatureView(signature);
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        menuCommit = menu.findItem(R.id.action_commit);
        boolean isOver = false;
        if (mEmergencyData != null) {
            isOver = emergencyTool.isEmergencyOver(mEmergencyData);
        }
        menuCommit.setVisible(isOver);
        return super.onCreateOptionsMenu(menu);
    }

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

    private boolean isValid() {
        RadioGroup radioGroupNeedRepair = handleReportModule.findViewById(R.id.radio_group_repair);
        boolean isNeedRepair = radioGroupNeedRepair.getCheckedRadioButtonId() == R.id.radio_btn_yes;
        if (!isNeedRepair) {
            if (mSignaturePhoto.isEmpty()) {
                toast(R.string.emergency_assign_handle_empty_sign);
                return false;
            }
        }

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

        return handleReportModule.isValid();
    }

    private void uploadAlert() {
        String title = "上传数据";
        String content = "是否上传数据?";
        DialogUtil.showAlertWithConfirmCancelButton(this, title, content, true, (dialogInterface, i) -> {
            emergencyHandle();
        });
    }

    private EmergencyHandleData collectData() {
        EmergencyHandleData handleData = new EmergencyHandleData();
        handleData.setId(mEmergencyData.getId());

        EmergencyOverData overData = emergencyTool.getLocalEmergencyOverData(mEmergencyData.getId());
        if (overData != null && overData.getIsOver() == 1) {
            String overTime = overData.getOverTime();
            handleData.setOverTime(overTime);
        }

        handleData.setCompleteTime(DateUtils.getDate());

        handleReportModule.collectData(handleData);
        return handleData;
    }

    private void emergencyHandle() {
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);

        EmergencyHandleData handleData = collectData();
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(mAudiosRecords);
        RadioGroup radioGroupNeedRepair = handleReportModule.findViewById(R.id.radio_group_repair);
        boolean isNeedRepair = radioGroupNeedRepair.getCheckedRadioButtonId() == R.id.radio_btn_yes;
        List<TroublePictureBean> signPhotos = isNeedRepair ? null : mSignaturePhoto;
        emergencyTool.emergencyAssignHandle(this, handleData, signPhotos, 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) {
                    onEmergencyHandled();
                }
            }
        });
    }

    public void onEmergencyHandled() {
        EventBus.getDefault().post(new MyEmergencyEvent(MyEmergencyEvent.EMERGENCY_ASSIGN_HANDLE_UPLOADED, mEmergencyData));
        showUploadFinishedDialog();
    }

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

    @Override
    public Button getAddPhotoBtn() {
        return handleReportModule.findViewById(R.id.btn_add_photo);
    }

    @Override
    public LinearLayout getPhotoGallery() {
        return handleReportModule.findViewById(R.id.photo_gallery);
    }

    @Override
    public MyAudioRecordButton getAudioRecordBtn() {
        return handleReportModule.findViewById(R.id.btn_audio_record);
    }

    @Override
    public LocationUtil_xu.CoordinateClass getLocation() {
        return mTappedCoordinate;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
