package com.tofly.ghrq_route.common.ui.activity;

import android.annotation.SuppressLint;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.esri.arcgisruntime.mapping.view.MapView;
import com.lcp.arecyclerview.widget.ARecycleView;
import com.lcp.arecyclerview.widget.DividerItemDecoration;
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.BaseMapActivity;
import com.tofly.ghrq_route.base.URLResponseCode;
import com.tofly.ghrq_route.common.ui.adapter.SignDataAdapter;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.deviceInfo.domain.DeviceInfoBean;
import com.tofly.ghrq_route.module.gps.GpsTool;
import com.tofly.ghrq_route.module.sign.SignTool;
import com.tofly.ghrq_route.module.sign.controller.SignCallBack;
import com.tofly.ghrq_route.module.sign.domain.SignHistoryDataBean;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.latte_core.base.IPresenter;

import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zombiexq on 2016/7/4.
 */
public class UiSign extends BaseMapActivity {
    @BindView(R.id.main_toolbar)
    Toolbar toolbar;
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.my_location)
    ImageView imvMyLocation;
    @BindView(R.id.textView_addr)
    TextView textViewAddr;
    @BindView(R.id.btn_sign_on)
    Button btnSignOn;
    @BindView(R.id.btn_sign_off)
    Button btnSignOff;
    @BindView(R.id.recycler_view)
    ARecycleView recycleView;

    private SignTool signTool;

    private SignDataAdapter signDataAdapter;

    private int mLastSignStatus = SIGN_UNCHECKED_TYPE;

    private List<SignHistoryDataBean> signDataList;

    public final static int SIGN_ON_TYPE = 1;
    public final static int SIGN_OFF_TYPE = 2;

    public final static int SIGN_UNCHECKED_TYPE = 0;    //开机
    public final static int SIGN_CHECKED_ON_TYPE = 1;   //上班

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_clear_location_sign) {
            DialogUtil.showAlertDialog(this, "提示", "是否清除轨迹", (dialog, which) -> {
                UserInfoTool userInfoTool = UserInfoTool.getInstance();
                userInfoTool.removeLocalLocationGpsData();
            });
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe
    public void onMessageEvent(UiPlan.PlanEvent event) {
        if (event.message.equals(UiPlan.PLAN_POINT_DOWNLOAD_STARTED)) {
            String strUploading = getResources().getString(R.string.updating_plan_point_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        } else if (event.message.equals(UiPlan.PLAN_POINT_DOWNLOAD_FINISHED)) {
            boolean isSuccess = (boolean) event.arg0;
            ProgressManager.getInstance().cancelProgress();
            String msg = "下载当日所要巡检的点数据：" + (isSuccess ? "成功" : "失败");
            showToast(msg);
            DeviceInfoTool.getInstance().checkTodayPlanCount(false, null);
        }
    }

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

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recycleView.setLayoutManager(linearLayoutManager);
        recycleView.setItemAnimator(new DefaultItemAnimator());
        recycleView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recycleView.setEmptyViewText(getResources().getString(R.string.sign_on_off_no));
        signDataList = new ArrayList<>();
        signDataAdapter = new SignDataAdapter(this, signDataList);
        recycleView.setAdapter(signDataAdapter);
        recycleView.setEnabled(false);

        textViewAddr.setText("正在定位...");
    }

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

        initListener();

        signTool = SignTool.getInstance();
        getSignStatusToday();
    }

    @SuppressLint("ClickableViewAccessibility")
    protected void initListener() {

    }

    private void getSignStatusToday() {
        signTool.getSignStatusToday(this, new SignCallBack(){
            @Override
            public void onGetSignStatusToday(boolean isSuccess, int errorCode, String errMsg, int status, int section) {
                super.onGetSignStatusToday(isSuccess, errorCode, errMsg, status, section);
                if (isSuccess) {
                    mLastSignStatus = status;
                    setSignDisplayStatus(status);
                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    showToast(errMsg);
                }
            }
        });
        getSignListToday();
    }

    private void setSignDisplayStatus(int status) {
        /*已签到上班*/
        if (status == SIGN_CHECKED_ON_TYPE) {
            btnSignOn.setText(getResources().getString(R.string.sign_xb));
        } else {
            btnSignOn.setText(getResources().getString(R.string.sign_sb));
        }
    }

    private void getSignListToday() {
        signTool.getSignListToday(this, new SignCallBack(){
            @Override
            public void onGetSignListToday(boolean isSuccess, int errorCode, String errMsg, List<SignHistoryDataBean> signDataBeanList, int total) {
                super.onGetSignListToday(isSuccess, errorCode, errMsg, signDataBeanList, total);
                if (isSuccess) {
                    if (signDataBeanList != null) {
                        signDataList = signDataBeanList;
                        recycleView.setTotal(total);
                        signDataAdapter.clear();
                        signDataAdapter.addAll(signDataBeanList);
                    } else {
                        errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                        showToast(errMsg);
                    }
                }
            }
        });
    }



    @OnClick({R.id.btn_sign_on, R.id.btn_sign_off})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sign_on:
                if (checkValid()) {
                    signAlert();
                }
                break;
            case R.id.btn_sign_off:
                if (checkValid()) {
                    showSignOffAlert();
                }
                break;
        }
    }

    private boolean checkValid() {
        if (mLastLocation == null) {
            showToast("当前位置信息不可用！");
            return true;
        }

        return true;
    }

    private void signAlert() {
        if (mLastSignStatus == SIGN_CHECKED_ON_TYPE) {
            /*上班中,开始下班*/
            showSignOffAlert();
        } else {
            showSignOnAlert();
        }
    }

    private void showSignOnAlert() {
        DialogUtil.showAlertDialog(this, R.string.dialog_sign_on_title, R.string.dialog_sign_on_msg,
                (dialog, which) -> {
                    // start之后会默认发起一次定位请求，开发者无须判断isstart并主动调用request
                    GpsTool gpsTool = GpsTool.getInstance();
                    boolean isEnabled = gpsTool.isLocationEnabled();
                    if (!isEnabled){
                        showToast("GPS未打开，请开启GPS！");
                        gpsTool.gotoSystemGpsSetting();
                    }else {
                        startSign(SIGN_ON_TYPE);
                    }
                });
    }

    private void showSignOffAlert() {
        DialogUtil.showAlertDialog(this, R.string.dialog_sign_off_title, R.string.dialog_sign_off_msg,
                (dialog, which) -> {
                    // start之后会默认发起一次定位请求，开发者无须判断isstart并主动调用request
                    startSign(SIGN_OFF_TYPE);
                });
    }

    private void startSign(final int type) {
        String lon = "";
        String lat = "";
        String addr = "";
        if (mLastLocation != null) {
            lon = String.valueOf(mLastLocation.getX());
            lat = String.valueOf(mLastLocation.getY());
        }
        if (mAddress != null && !mAddress.isEmpty())
            addr = mAddress;

        SignHistoryDataBean signHistoryData = new SignHistoryDataBean(type, lon, lat, mGpsFlag, addr);
        DeviceInfoBean deviceInfoBean = DeviceInfoTool.getInstance().getDeviceInfo();
        signTool.signOnOffNoSave(this, signHistoryData, deviceInfoBean, (isSuccess, errMsg, errorCode) -> {
            if (isSuccess) {
                getSignStatusToday();
            } else {
                if (errorCode == URLResponseCode.ErrorCode.APP_MUST_UPDATE){
                    DialogUtil.showMustUpdateAppDialog(this, errorCode, errMsg);
                }else {
                    showToast(errMsg);
                }
            }
        });
    }


    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    @Override
    public int setLayout() {
        return R.layout.ui_sign_new;
    }

    @Override
    public boolean enableLoadMap() {
        return true;
    }

    @Override
    public boolean enableMoveMapListener() {
        return true;
    }

    @Override
    public boolean enableArcgisLocating() {
        return false;
    }

    @Override
    public boolean enableAmapLocationListener() {
        return true;
    }

    @Override
    public boolean enableMapMoveToLocation() {
        return true;
    }

    @Override
    public TextView getTextAddrView() {
        return textViewAddr;
    }

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

        BaseApp.cancelRequest(getClass().getName());
    }
}
