package com.xxfc.discovery.other;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.Inc;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.BodyAddImQuestion;
import com.xxfc.discovery.event.DiscoveryAddEvent;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * 问答  发布问题
 */
@Route(path = Constance.ACTIVITY_URL_PUBLISHINGPROBLEM)
public class PublishingProblemActivity extends BaseStatusActivity<DiscoveryPresenter> {


    @BindView(R2.id.et_ask_title)
    EditText etAskTitle;
    @BindView(R2.id.et_ask_content)
    EditText etAskContent;
    @BindView(R2.id.tv_word_count)
    TextView tvWordCount;
    @BindView(R2.id.tv_ask_ok)
    TextView tvAskOk;

    private double latLatitude = 0;
    private double lonLongitude;
    private LatLng mLatLng;//当前城市经纬度
    private LocationManager locationManager;

    @Override
    protected int setLayout() {
        return R.layout.activity_publishing_problem;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("发布问题");

        etAskContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Editable editable = etAskContent.getText();
                int len = editable.toString().length();
                tvWordCount.setText(len + "/500");

                if (len > 500) {
                    showToast("超出字数限制");
                    int selEndIndex = Selection.getSelectionEnd(editable);
                    String str = editable.toString();
                    //截取新字符串
                    String newStr = str.substring(0, 500);
                    etAskContent.setText(newStr);
                    editable = etAskContent.getText();

                    //新字符串的长度
                    int newLen = editable.length();
                    //旧光标位置超过字符串长度
                    if (selEndIndex > newLen) {
                        selEndIndex = editable.length();
                    }
                    //设置新光标所在的位置
                    Selection.setSelection(editable, selEndIndex);
                }
            }
        });
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        DiscoveryAddEvent event = new DiscoveryAddEvent();
        event.setType(3);
        RxBus.post(event);
        finish();
    }

    @OnClick(R2.id.tv_ask_ok)
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_ask_ok) {
            String title = etAskTitle.getText().toString().trim();
            if (TextUtils.isEmpty(title)) {
                showToast("问题标题不能为空！");
                return;
            }

            String content = etAskContent.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                showToast("问题内容不能为空！");
                return;
            }

            upQuestion(title, content);
        }
    }

    private void upQuestion(String title, String content) {
        mPresenter.postBodyData(RvFrameConfig.HOST, 0, DiscoveryApi.DISCOVERY_IMQUESTION_ADD, BaseBean.class, new BodyAddImQuestion(title, latLatitude, lonLongitude, Inc.getDeviceName(), DateUtils.getCurTimeMillis(), content), getHeadMap(), true);
    }

    private Map<String, Object> getHeadMap() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        return headMap;
    }

    /**
     * 定位权限处理
     */
    private void permissionProcess() {

        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            new RxPermission(this).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        initGps();
                    } else {
                        finish();
                    }
                }
            });
        } else {
            initGps();
        }
    }

    /**
     * 初始化定位
     */
    public void initGps() {
        locationManager = new LocationManager(this);
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                //以下只列举部分获取经纬度相关（常用）的结果信息
                //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

                //获取定位精度，默认值为0.0f
                float radius = location.getRadius();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                String coorType = location.getCoorType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
                int errorCode = location.getLocType();
//                setGpsContent("count=:",String.valueOf(count));
//                setGpsContent("latitude:",String.valueOf(location.getLatitude()));
//                setGpsContent("longitude:",String.valueOf(location.getLongitude()));
//                setGpsContent("城市:",location.getCity());
//                setGpsContent("街道:",location.getAddrStr());
//                setGpsContent("当前位置:",location.getLocationDescribe());
                latLatitude = location.getLatitude();
                lonLongitude = location.getLongitude();
                mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                locationManager.stopLocation();
            }
        });
    }
}
