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

import android.annotation.SuppressLint;
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.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;

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.module.gps.service.AmapLocationHelper;
import com.tofly.ghrq_route.module.survey.SurveyTool;
import com.tofly.ghrq_route.module.survey.controller.SurveyCallBack;
import com.tofly.ghrq_route.module.survey.domain.MySurveyEvent;
import com.tofly.ghrq_route.module.survey.domain.SurveyBean;
import com.tofly.ghrq_route.module.trouble.domain.AuditFileBean;
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.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.SpinnerUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.UUID;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnItemSelected;

@SuppressLint("NonConstantResourceId")
public class UiSurveyReport extends BaseFileActivity {
    @BindView(R.id.edit_report_addr)
    EditText editReportAddr;
    @BindView(R.id.edit_project_name)
    EditText editProjectName;
    @BindView(R.id.spinner_project_kind)
    AppCompatSpinner spinnerProjectKind;
    @BindView(R.id.spinner_device_type)
    AppCompatSpinner spinnerDeviceType;
    @BindView(R.id.edit_contact_people)
    EditText editContactPeople;
    @BindView(R.id.edit_contact_phone)
    EditText editContactPhone;
    @BindView(R.id.edit_house_holds)
    EditText editHouseHolds;
    @BindView(R.id.edit_adjust_code)
    EditText editAdjustCode;
    @BindView(R.id.edit_device_num)
    EditText editDeviceNum;
    @BindView(R.id.radio_group_bury_pipe)
    RadioGroup radioGroupBuryPipe;
    @BindView(R.id.radio_btn_yes)
    RadioButton radioBtnYes;
    @BindView(R.id.radio_btn_no)
    RadioButton radioBtnNo;
    @BindView(R.id.layout_addition)
    LinearLayout layoutAddition;
    @BindView(R.id.btn_audio_record)
    MyAudioRecordButton btnAddAudio;
    @BindView(R.id.layout_btn_add)
    LinearLayout layoutBtnAddPhoto;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindArray(R.array.project_kinds)
    String[] projectKinds;
    @BindArray(R.array.survey_device_types)
    String[] deviceTypes;

    private SurveyTool surveyTool;

    private int indexProjectKind = -1;

    private int indexDeviceType = -1;

    private AmapLocationHelper amapLocationHelper;

    private LocationUtil_xu.CoordinateClass mTappedCoordinate = null;

    private boolean isUpdate = false;

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

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

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

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

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

        surveyTool = SurveyTool.getInstance();

        setAdapter();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            //mbRejected = bundle.getBoolean(TroubleBean.TROUBLE_IS_REJECTED, false);
            SurveyBean surveyHistory = (SurveyBean) bundle.getSerializable(SurveyBean.SURVEY_DATA_KEY);
            if (surveyHistory != null) {
                isUpdate = true;
                setReportHistory(surveyHistory);
            }
        }

        amapLocationHelper = new AmapLocationHelper(this);
        if (!isUpdate) {
            amapLocationHelper.startLocating();
        }
    }

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

        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);
        MenuItem menuCommit = menu.findItem(R.id.action_commit);
        menuCommit.setVisible(!isUpdate);
        return super.onCreateOptionsMenu(menu);
    }

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

    @OnItemSelected({R.id.spinner_project_kind, R.id.spinner_device_type})
    public void onItemSelected(AdapterView<?> parent, int position) {
        switch (parent.getId()) {
            case R.id.spinner_project_kind:
                indexProjectKind = position;
                break;
            case R.id.spinner_device_type:
                indexDeviceType = position;
                break;
        }
    }

    private void setReportHistory(SurveyBean surveyHistory) {
        String surveyId = surveyHistory.getId();
        String fileNote = "附件";

        /*工程名称*/
        String name = surveyHistory.getName();
        editProjectName.setText(name);
        editProjectName.setEnabled(false);
        /*联系人*/
        String contactPeople = surveyHistory.getContacts();
        editContactPeople.setText(contactPeople);
        editContactPeople.setEnabled(false);
        /*联系电话*/
        String phone = surveyHistory.getContactsNumber();
        editContactPhone.setText(phone);
        editContactPhone.setEnabled(false);
        /*地址*/
        String addr = surveyHistory.getBuriedAddress();
        editReportAddr.setText(addr);
        editReportAddr.setEnabled(false);
        /*户数*/
        String houseHolds = surveyHistory.getHouseHolds() + "";
        editHouseHolds.setText(houseHolds);
        editHouseHolds.setEnabled(false);
        /*调压器编号*/
        String adjustCode = surveyHistory.getCode();
        editAdjustCode.setText(adjustCode);
        editAdjustCode.setEnabled(false);
        /*新增设备数量*/
        String deviceNum = surveyHistory.getAddDeviceNum() + "";
        editDeviceNum.setText(deviceNum);
        editDeviceNum.setEnabled(false);
        /*有无埋地管*/
        boolean isBuried = surveyHistory.getIsBuried() == 1;
        radioGroupBuryPipe.check(isBuried ? R.id.radio_btn_yes : R.id.radio_btn_no);
        radioBtnYes.setEnabled(false);
        radioBtnNo.setEnabled(false);
        /*工程性质*/
        indexProjectKind = surveyHistory.getType() - 1;
        spinnerProjectKind.setSelection(indexProjectKind);
        spinnerProjectKind.setEnabled(false);
        /*设备类型*/
        indexDeviceType = surveyHistory.getAddDevice() - 1;
        spinnerDeviceType.setSelection(indexDeviceType);
        spinnerDeviceType.setEnabled(false);

        layoutBtnAddPhoto.setVisibility(View.GONE);

        //附件
        List<AuditFileBean> reportFiles = surveyHistory.getReportFile();
        if (reportFiles != null) {
            for (AuditFileBean auditFileBean : reportFiles) {
                getSchemeFiles(surveyId, auditFileBean, fileNote, photoGallery);
            }
        }
    }

    private void setAdapter() {
        setProjectKindAdapter();
        setDeviceTypeAdapter();
    }

    private void setProjectKindAdapter() {
        SpinnerUtils.setAdapter(this, spinnerProjectKind, projectKinds);
    }

    private void setDeviceTypeAdapter() {
        SpinnerUtils.setAdapter(this, spinnerDeviceType, deviceTypes);
    }

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

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

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

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

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

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

        if (indexProjectKind == -1) {
            toast(R.string.survey_report_empty_proj_kind);
            return false;
        }

        if (indexDeviceType == -1) {
            toast(R.string.survey_report_empty_dev_type);
            return false;
        }

        return true;
    }

    private SurveyBean collectData() {
        SurveyBean surveyBean = new SurveyBean();
        String troubleId = UUID.randomUUID().toString();
        surveyBean.setId(troubleId);
        /*工程名称*/
        String name = editProjectName.getText().toString();
        surveyBean.setName(name);
        /*联系人*/
        String contactPeople = editContactPeople.getText().toString();
        surveyBean.setContacts(contactPeople);
        /*联系电话*/
        String phone = editContactPhone.getText().toString();
        surveyBean.setContactsNumber(phone);
        /*地址*/
        String addr = editReportAddr.getText().toString();
        surveyBean.setBuriedAddress(addr);
        /*户数*/
        String houseHolds = editHouseHolds.getText().toString();
        surveyBean.setHouseHolds(Integer.parseInt(houseHolds));
        /*调压器编号*/
        String adjustCode = editAdjustCode.getText().toString();
        surveyBean.setCode(adjustCode);
        /*新增设备数量*/
        String deviceNum = editDeviceNum.getText().toString();
        surveyBean.setAddDevice(Integer.parseInt(deviceNum));
        /*工程性质*/
        surveyBean.setType(indexProjectKind + 1);
        surveyBean.setTypeName(projectKinds[indexProjectKind]);
        /*设备类型*/
        surveyBean.setAddDevice(indexDeviceType + 1);
        surveyBean.setAddDeviceName(deviceTypes[indexDeviceType]);
        /*有无埋地管*/
        int checkId = radioGroupBuryPipe.getCheckedRadioButtonId();
        surveyBean.setIsBuried(checkId == R.id.radio_btn_yes ? 1 : 0);

        return surveyBean;
    }

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

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

        SurveyBean surveyBean = collectData();
        List<TroubleAudioBean> audioBeans = TroubleAudioBean.getAudioBeans(mAudiosRecords);
        surveyTool.uploadSurveyBefore(this, surveyBean, mPicturesUpload, audioBeans, mDocumentsUpload, new SurveyCallBack() {
            @Override
            public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                super.onSetData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    EventBus.getDefault().post(new MySurveyEvent(MySurveyEvent.SURVEY_BEFORE_UPLOADED));
                    showUploadFinishedDialog();
                }
            }
        });
    }

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

    @Override
    public Button getAddPhotoBtn() {
        return btnAddPhoto;
    }

    @Override
    public LinearLayout getPhotoGallery() {
        return photoGallery;
    }

    @Override
    public MyAudioRecordButton getAudioRecordBtn() {
        return btnAddAudio;
    }

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