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

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.LinearLayout;

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

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.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseFileActivity;
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.MaintainExecuteBean;
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.EmergencyAssignHandleInfoModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyDispatchInfoModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyRepairHandleHistoryModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyRepairHandleInfoModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyRepairHandleReportModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyReportInfoModuleLayout;
import com.tofly.ghrq_route.module.emergencyHandle.ui.view.EmergencyScheduleAssignInfoModuleLayout;
import com.tofly.ghrq_route.module.gps.service.AmapLocationHelper;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
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.dialog.DialogUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by zombiexq on 2016/7/4.
 */
public class UiEmergencyRepairHandle extends BaseFileActivity {
    @BindView(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.main_toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout_module_emergency_handle_report)
    EmergencyRepairHandleReportModuleLayout handleReportModule;
    @BindView(R.id.layout_module_repair_handle_info)
    EmergencyRepairHandleInfoModuleLayout repairHandleInfoModule;
    @BindView(R.id.layout_module_repair_history)
    EmergencyRepairHandleHistoryModuleLayout repairHistoryModule;
    @BindView(R.id.layout_module_dispatch_info)
    EmergencyDispatchInfoModuleLayout dispatchInfoModule;
    @BindView(R.id.layout_module_schedule_assign_info)
    EmergencyScheduleAssignInfoModuleLayout scheduleAssignInfoModule;
    @BindView(R.id.layout_module_assign_handle_info)
    EmergencyAssignHandleInfoModuleLayout assignHandleInfoModule;
    @BindView(R.id.layout_module_assign_handle_history)
    EmergencyAssignHandleHistoryModuleLayout assignHandleHistoryModule;
    @BindView(R.id.layout_module_emergency_info)
    EmergencyReportInfoModuleLayout emergencyInfoModule;

    private int mEmergencyId;

    private EmergencyHandleData mEmergencyData;

    private EmergencyTool emergencyTool;

    private MenuItem menuCommit;

    private AmapLocationHelper amapLocationHelper;

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

    boolean mIsResponseUser = false;

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

        setContentView(R.layout.ui_emergency_repair_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();

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            EmergencyHandleData handleData =
                    (EmergencyHandleData) extras.getSerializable(EmergencyHandleData.EMERGENCY_DATA_KEY);
            if (handleData != null) {
                mEmergencyData = handleData;
                initReportModule();
/*                boolean bRejected = mEmergencyData.getRejectedFlag() == 1;
                if (bRejected) {
                    repairHandleInfoModule.setVisibility(View.VISIBLE);
                    repairHandleInfoModule.initEmergencyInfo(handleData);
                }*/
                List<MaintainExecuteBean> maintenanceHisList = mEmergencyData.getSchedulerMaintenanceHisList();
                if (maintenanceHisList != null && maintenanceHisList.size() > 0) {
                    repairHistoryModule.setVisibility(View.VISIBLE);
                    repairHistoryModule.initEmergencyInfo(handleData);
                }
                dispatchInfoModule.initEmergencyInfo(handleData);
                scheduleAssignInfoModule.initEmergencyInfo(handleData);
                assignHandleInfoModule.initEmergencyInfo(mEmergencyData);
                assignHandleHistoryModule.initEmergencyInfo(handleData);
                emergencyInfoModule.initEmergencyInfo(handleData);
            }
        }

        emergencyTool = EmergencyTool.getInstance();

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

    private void initReportModule() {
        if (mEmergencyData != null) {
            String responseUserId = mEmergencyData.getResponsibleUserId();
            String userId = BaseApp.getInstance().getUserId();
            mIsResponseUser = responseUserId.equals(userId);
            handleReportModule.setVisibility(mIsResponseUser ? View.VISIBLE : View.GONE);
        }
    }

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

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        menuCommit = menu.findItem(R.id.action_commit);
        menuCommit.setVisible(mIsResponseUser);
        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() {
/*        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());

        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);
        emergencyTool.emergencyRepairHandle(this, handleData, 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_REPAIR_HANDLE_UPLOADED, mEmergencyData));
        showUploadFinishedDialog();
    }

    private void showUploadFinishedDialog() {
        int title = R.string.emergency_repair_handle_report_title;
        int msg = R.string.emergency_repair_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();
    }
}
