package com.casic.dcms.ui;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.bean.BridgeConfigBean;
import com.casic.dcms.databinding.ActivityBridgeBinding;
import com.casic.dcms.mvp.presenter.impl.SubmitMaintainPresenterImpl;
import com.casic.dcms.mvp.view.IMaintainSubmitView;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.SaveKeyValues;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.TimeOrDateUtil;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.utils.callback.IAddressListener;
import com.casic.dcms.utils.callback.ILocationListener;
import com.casic.dcms.widgets.SignInDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class BridgeMaintainActivity extends AndroidxBaseActivity<ActivityBridgeBinding> implements IMaintainSubmitView {

    private final Context context = BridgeMaintainActivity.this;
    private Timer timer;
    private SubmitMaintainPresenterImpl submitMaintainPresenter;
    private String bridgeId = "";

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("路桥养护");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
        viewBinding.titleBarLayout.rightImageView.setOnClickListener(v -> startActivity(new Intent(this, MaintainRecordActivity.class)));
    }

    @Override
    protected void initData() {
        timer = new Timer();
        submitMaintainPresenter = new SubmitMaintainPresenterImpl(this);
    }

    @Override
    protected void initEvent() {
        viewBinding.liablePersonView.setText(StringHelper.getUserAccount());
        viewBinding.liablePersonView.setTextColor(ContextCompat.getColor(this, R.color.textColor));
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String systemDate = TimeOrDateUtil.timestampToDate(System.currentTimeMillis());
                viewBinding.maintainDateView.post(new Runnable() {
                    @Override
                    public void run() {
                        viewBinding.maintainDateView.setText(systemDate);
                        viewBinding.maintainDateView.setTextColor(ContextCompat.getColor(context, R.color.textColor));
                    }
                });
            }
        }, 0, 1000);

        viewBinding.bridgeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<BridgeConfigBean.BridgesBean> bridges = StringHelper.getBridgeBeanList();
                if (bridges.size() == 0) {
                    ToastHelper.showToast("获取桥梁数据异常", ToastHelper.ERROR);
                    return;
                }
                BottomListSheetBuilder sheetBuilder = new BottomListSheetBuilder(context);
                sheetBuilder.setTitle("选择桥梁");
                for (BridgeConfigBean.BridgesBean bean : bridges) {
                    sheetBuilder.addItem(bean.getName());
                }
                sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.dismiss();
                        bridgeId = String.valueOf(bridges.get(position).getId());
                        viewBinding.bridgeNameView.setText(tag);
                        viewBinding.bridgeNameView.setTextColor(
                                ContextCompat.getColor(context, R.color.textColor)
                        );
                    }
                }).build().show();
            }
        });

        viewBinding.maintainContentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new BottomListSheetBuilder(context)
                        .setTitle("养护内容")
                        .addItem("日常养护，无异常")
                        .addItem("清除表面污垢")
                        .addItem("修补混凝土空洞、破损、剥落和表面风化及裂缝")
                        .addItem("清除暴露钢筋的锈渍、恢复保护层")
                        .addItem("处理各种横、纵向构件的开裂、开焊和锈蚀")
                        .setGravityCenter(true)
                        .setOnSheetItemClickListener(new BottomListSheetBuilder.OnSheetItemClickListener() {
                            @Override
                            public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                                dialog.dismiss();
                                viewBinding.maintainView.setText(tag);
                                viewBinding.maintainView.setTextColor(ContextCompat.getColor(context, R.color.textColor));
                            }
                        }).build().show();
            }
        });

        viewBinding.submitButton.setChangeAlphaWhenPress(true);
        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LocationHelper.obtainCurrentLocationByGD(context, new ILocationListener() {
                    @Override
                    public void onLocationGet(Location location) {

                    }

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (TextUtils.isEmpty(bridgeId)) {
                            ToastHelper.showToast("请先选择养护的桥梁", ToastHelper.WARING);
                            return;
                        }
                        String maintainContent = viewBinding.maintainView.getText().toString();
                        if (TextUtils.isEmpty(maintainContent)) {
                            ToastHelper.showToast("请选择养护的内容", ToastHelper.WARING);
                            return;
                        }
                        double[] gcjToWgs = LocationHelper.gcjToWgs(
                                aMapLocation.getLongitude(),
                                aMapLocation.getLatitude()
                        );
                        LatLonPoint latLonPoint = new LatLonPoint(gcjToWgs[1], gcjToWgs[0]);
                        LocationHelper.antiCodingLocation(context, latLonPoint, new IAddressListener() {
                            @Override
                            public void onGetAddress(String address) {
                                SaveKeyValues.putValue("maintainAddress", address);
                            }
                        });
                        //提交养护记录
                        submitMaintainPresenter.onReadyRetrofitRequest(
                                bridgeId,
                                maintainContent,
                                viewBinding.maintainDateView.getText().toString(),
                                StringHelper.getUserBean().getId(),
                                String.valueOf(gcjToWgs[0]),
                                String.valueOf(gcjToWgs[1]),
                                StringHelper.filterString(viewBinding.remarksView.getText().toString())
                        );
                    }
                }, true);
            }
        });
    }

    @Override
    public void showProgress() {
        OtherUtils.showLoadingDialog(this, "养护记录签到中，请稍后");
    }

    @Override
    public void hideProgress() {
        OtherUtils.dismissLoadingDialog();
    }

    @Override
    public void obtainSubmitResult(ActionResultBean resultBean) {
        String maintainAddress = (String) SaveKeyValues.getValue("maintainAddress", "");
        if (resultBean.getCode() == 200) {
            new SignInDialog.Builder()
                    .setContext(this)
                    .setTitle("桥梁养护记录提交成功")
                    .setAddress(maintainAddress.equals("") ? "详细位置解析失败" : maintainAddress)
                    .setOnDialogClickListener(new SignInDialog.OnDialogClickListener() {
                        @Override
                        public void onViewClick() {
                            startActivity(new Intent(context, MaintainRecordActivity.class));
                            finish();
                        }
                    }).build().show();
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        submitMaintainPresenter.disposeRetrofitRequest();
        super.onDestroy();
    }
}