package com.casic.dcms.view;

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

import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityBridgeBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.BridgeConfigBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.callback.IAddressListener;
import com.casic.dcms.utils.callback.ILocationListener;
import com.casic.dcms.vm.BridgeViewModel;
import com.casic.dcms.widgets.SignInDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.hub.ContextHub;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.hub.LongHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.utils.SaveKeyValues;
import com.pengxh.androidx.lite.vm.LoadState;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder;

import java.util.List;

public class BridgeMaintainActivity extends AndroidxBaseActivity<ActivityBridgeBinding> {

    private final Context context = BridgeMaintainActivity.this;
    private BridgeViewModel bridgeViewModel;
    private String bridgeId = "";

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

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

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initData() {
        bridgeViewModel = new ViewModelProvider(this).get(BridgeViewModel.class);
    }

    @Override
    protected void initEvent() {
        viewBinding.bridgeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<BridgeConfigBean.BridgesBean> bridges = StringHelper.getBridgeBeanList();
                if (bridges.size() == 0) {
                    StringHub.show(context, "获取桥梁数据异常");
                    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.mainTextColor));
                    }
                }).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.mainTextColor));
                            }
                        }).build().show();
            }
        });

        String systemDate = LongHub.timestampToDate(System.currentTimeMillis());
        viewBinding.maintainDateView.setText(systemDate);
        viewBinding.liablePersonView.setText(StringHelper.getUserBean().getAccount());

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LocationHelper.obtainCurrentLocation(context, new ILocationListener() {

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (TextUtils.isEmpty(bridgeId)) {
                            StringHub.show(context, "请先选择养护的桥梁");
                            return;
                        }
                        String maintainContent = viewBinding.maintainView.getText().toString();
                        if (TextUtils.isEmpty(maintainContent)) {
                            StringHub.show(context, "请选择养护的内容");
                            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);
                            }
                        });
                        //提交养护记录
                        bridgeViewModel.submitMaintain(
                                bridgeId,
                                maintainContent,
                                viewBinding.maintainDateView.getText().toString(),
                                StringHelper.getUserBean().getId(),
                                String.valueOf(gcjToWgs[0]),
                                String.valueOf(gcjToWgs[1]),
                                StringHub.filterSpaceOrEnter(viewBinding.remarksView.getText().toString())
                        );
                    }
                }, true);
            }
        });
        bridgeViewModel.submitResultModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                String maintainAddress = (String) SaveKeyValues.getValue("maintainAddress", "");
                if (resultBean.getCode() == 200) {
                    new SignInDialog.Builder()
                            .setContext(context)
                            .setTitle("桥梁养护记录提交成功")
                            .setAddress(maintainAddress.equals("") ? "详细位置解析失败" : maintainAddress)
                            .setOnDialogClickListener(new SignInDialog.OnDialogClickListener() {
                                @Override
                                public void onViewClick() {
                                    ContextHub.navigatePageTo(context, MaintainRecordActivity.class);
                                }
                            }).build().show();
                }
            }
        });
        bridgeViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "养护记录签到中，请稍后");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }
}