package com.rv.home.rv.module.ui.main.home;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.frame.rv.RvFrameConfig;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseFragment;
import com.ruiwenliu.wrapper.inter.OnViewHolder;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.TimeManager;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.adapter.HotCarTypeAdapter;
import com.rv.home.rv.module.ui.main.home.bean.CityPickerBean;
import com.rv.home.rv.module.ui.main.home.bean.ListsBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.bean.ShopListBean;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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

/**
 * Created :Auser
 * Date: 2019/5/15.
 * Desc:首页
 */

public class HomePageFragment extends BaseFragment<CommonPresenter> {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.iv_top)
    ImageView ivTop;
    private HotCarTypeAdapter mAdapter;
    private Map<String, Integer> mapGetTime;
    private Map<String, Integer> mapOutTime;
    private TextView headTvGetCity;//获取出发城市
    private TextView headTvOutCity;//获取还车城市
    private TextView headTvGetShop;//获取出发门店地址
    private TextView headTvOutShop;//获取还车门店地址
    private final int TYPE_REQUEST_CITY = 1;//城市列表
    private final int TYPE_REQUEST_SHOP = 2;//门店列表
    private final int TYPE_REQUEST_ADDRESS = 3;//地址选择
    private LocationManager locationManager;
    private String nowCity = "";
    private int getSwitchType;//取车开关类型
    private int outSwitchType;//还车开关类型
    private double latLatitude = 0;
    private double lonLongitude;
    private LatLng mLatLng;//当前城市经纬度

    private double outLatitude = 0;
    private double outLongitude;
    private int getCityId;//取车城市ID
    private int outCityId;//还车城市ID
    private OrderDataBean dataBean;
    private int copyDay=2;//租车天数


    public static Intent getIntent(Context context) {
        return new Intent(context, CarRentalActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    };

    public static HomePageFragment getInstance(int type) {
        Bundle bundl = new Bundle();
        bundl.putInt("type", type);
        HomePageFragment fragment = new HomePageFragment();
        fragment.setArguments(bundl);
        return fragment;
    }
    @Override
    public int getViewLayout() {
        return R.layout.rv_act_car_rental;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        permissionProcess();
        mAdapter = new HotCarTypeAdapter();
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.setAdapter(mAdapter);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        ivTop.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_UP:
                        ivTop.setVisibility(View.VISIBLE);
                        break;
                }
                return false;
            }
        });
        getData();

    }

    @Override
    protected void loadData(Bundle savedInstanceState) {

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        processData((ShopListBean) result);
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", 1);
            String requestData = data.getStringExtra("location");
            switch (requestCode) {
                case TYPE_REQUEST_CITY://城市列表
                    if (type == 1) {
                        headTvGetShop.setText("");
                        getCityId = data.getIntExtra("id", 0);
                    } else {
                        headTvOutShop.setText("");
                        outCityId = data.getIntExtra("id", 0);
                    }
                    setRequestData(type, requestData, headTvGetCity, headTvOutCity, 0, 0);

                    break;
                case TYPE_REQUEST_SHOP://门店
                    setRequestData(type, requestData, headTvGetShop, headTvOutShop, 0, 0);
                    break;
                case TYPE_REQUEST_ADDRESS://地址
                    double lat = data.getDoubleExtra("latitude", 0);
                    double lon = data.getDoubleExtra("longitude", 0);
                    setRequestData(type, requestData, headTvGetShop, headTvOutShop, lat, lon);
                    break;
            }
        }

    }

    @OnClick(R2.id.iv_top)
    public void onViewClicked() {
        if (recyclerView != null && mAdapter != null) {
            recyclerView.scrollToPosition(0);
        }
    }

    /**
     * 设置返回结果参数
     * @param type
     * @param data
     * @param tvGet
     * @param tvOut
     * @param lat
     * @param lon
     */
    private void setRequestData(int type, String data, TextView tvGet, TextView tvOut, double lat, double lon) {
        if (tvGet == null) {
            return;
        }
        switch (type) {
            case 1:
                latLatitude = lat;
                lonLongitude = lon;
                tvGet.setText(data);
                break;
            case 2:
                outLatitude = lat;
                outLongitude = lon;
                tvOut.setText(data);
                break;
        }
    }


    /**
     * 获取门店列表
     */
    private void getShopList(double lat, double lon) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", 1);
        map.put("limit", 1);
        map.put("lat", lat);
        map.put("lon", lon);
        mPresenter.getData(RvFrameConfig.VEHICLE_POST, 0, ApiConfig.HTTP_URL_SHOP_LIST, ShopListBean.class, map, true);
    }

    /**
     * 处理最近门店请求结果
     * @param bean
     */
    private void processData(ShopListBean bean) {
        if (bean.getData().getTotalCount() > 0) {
            if (headTvGetShop != null && TextUtils.isEmpty(headTvGetShop.getText().toString().trim())) {
                headTvGetShop.setText(bean.getData().getData().get(0).getName());
                latLatitude = bean.getData().getData().get(0).getLatitude();
                lonLongitude = bean.getData().getData().get(0).getLongitude();
            }

            if (headTvOutShop != null && TextUtils.isEmpty(headTvOutShop.getText().toString().trim())) {
                headTvOutShop.setText(bean.getData().getData().get(0).getName());
                outLatitude = bean.getData().getData().get(0).getLatitude();
                outLongitude = bean.getData().getData().get(0).getLongitude();
            }
        }

    }

    private void getData() {
        mAdapter.addHeaderView(getHeadView());
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add("东莞松山湖欣新房车总店" + i);
        }
        mAdapter.setNewData(list);

    }

    /**
     * 获取头部View
     *
     * @return
     */
    private View getHeadView() {
        return getHelperView(recyclerView, R.layout.rv_head_car_rental, new OnViewHolder() {
            @Override
            public void helper(ViewHolder helper) {
                headTvGetCity = helper.getView(R.id.tv_get_city);
                headTvOutCity = helper.getView(R.id.tv_out_city);
                headTvGetShop = helper.getView(R.id.tv_get_address);
                headTvOutShop = helper.getView(R.id.tv_out_address);
                final TextView tvGetTime = helper.getView(R.id.tv_get_time);
                final TextView tvGetWeek = helper.getView(R.id.tv_get_week);
                final TextView tvOutTime = helper.getView(R.id.tv_out_time);
                final TextView tvOutWeek = helper.getView(R.id.tv_out_week);
                final TextView tvGetDay = helper.getView(R.id.tv_day);
                final CheckBox checkBox = helper.getView(R.id.check_driver);

                Switch shGet = helper.getView(R.id.switch_get);
                initTime(tvGetTime, tvOutTime);
                tvGetDay.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
                shGet.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            getSwitchType = 1;
                        } else {
                            getSwitchType = 0;
                        }
                        headTvGetShop.setText("");
                    }
                });
                Switch shOut = helper.getView(R.id.switch_out);
                shOut.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            outSwitchType = 1;
                        } else {
                            outSwitchType = 0;
                        }
                        headTvOutShop.setText("");
                    }
                });

                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.iv_back) {
                            getActivity().finish();

                        } else if (i == R.id.tv_get_city) {
                            startActivityForResult(CityListActivity.getIntent(getContext(), 1, headTvGetCity.getText().toString().trim(), getCityId), TYPE_REQUEST_CITY);

                        } else if (i == R.id.tv_out_city) {
                            startActivityForResult(CityListActivity.getIntent(getContext(), 2, headTvOutCity.getText().toString().trim(), outCityId), TYPE_REQUEST_CITY);

                        } else if (i == R.id.tv_get_address) {
                            String getCity = headTvGetCity.getText().toString().trim();
//                                if (getSwitchType == 0) {
//                                    startActivityForResult(SelectShopActivity.getIntent(mActivity, 1,"",getCity.equals(nowCity) && mLatLng!=null?mLatLng.latitude:0,getCity.equals(nowCity)&& mLatLng!=null?mLatLng.longitude:0), TYPE_REQUEST_SHOP);
//                                } else {
                            startActivityForResult(SelectLocationActivity.getIntent(getContext(), 1, getCity, latLatitude, lonLongitude, nowCity), TYPE_REQUEST_ADDRESS);
//                                }


                        } else if (i == R.id.tv_out_address) {
                            String outCity = headTvOutCity.getText().toString().trim();
//                                if (outSwitchType == 0) {
//                                    startActivityForResult(SelectShopActivity.getIntent(mActivity, 2,"",outCity.equals(nowCity)&& mLatLng!=null?mLatLng.latitude:0,outCity.equals(nowCity)&& mLatLng!=null?mLatLng.longitude:0), TYPE_REQUEST_SHOP);
//                                } else {
                            startActivityForResult(SelectLocationActivity.getIntent(getContext(), 2, outCity, outLatitude, outLongitude, nowCity), TYPE_REQUEST_ADDRESS);
//                                }

                        } else if (i == R.id.tv_get_time) {
                            if (mapGetTime == null) {
                                return;
                            }
                            showDatePicker(mapGetTime.get("year"), mapGetTime.get("month"), mapGetTime.get("day"), mapGetTime.get("hour"), mapGetTime.get("minute"), tvGetTime, tvGetWeek, mapGetTime, tvGetDay);

                        } else if (i == R.id.tv_out_time) {
                            if (mapOutTime == null) {
                                return;
                            }
                            showDatePicker(mapOutTime.get("year"), mapOutTime.get("month"), mapOutTime.get("day"), mapOutTime.get("hour"), mapOutTime.get("minute"), tvOutTime, tvOutWeek, mapOutTime, tvGetDay);

                        } else if (i == R.id.tv_select) {
                            if (mapGetTime.size() > 0 && mapOutTime.size() > 0) {
                                String getTime = String.format("%1$s-%2$s-%3$s", mapGetTime.get("year"), mapGetTime.get("month") < 10 ? "0" + mapGetTime.get("month") : mapGetTime.get("month"), mapGetTime.get("day") < 10 ? "0" + mapGetTime.get("day") : mapGetTime.get("day"));
                                String outTime = String.format("%1$s-%2$s-%3$s", mapOutTime.get("year"), mapOutTime.get("month") < 10 ? "0" + mapOutTime.get("month") : mapOutTime.get("month"), mapOutTime.get("day") < 10 ? "0" + mapOutTime.get("day") : mapOutTime.get("day"));
                                if (copyDay < 0) {
                                    showToast(getContext().getString(R.string.rv_day_toast));
                                    return;
                                }
                                sendData(headTvGetCity.getText().toString().trim(),
                                        headTvGetShop.getText().toString().trim(),
                                        headTvOutCity.getText().toString().trim(),
                                        headTvOutShop.getText().toString().trim(),
                                        getTime, outTime, copyDay, checkBox.isChecked(),
                                        tvGetTime.getText().toString().trim(),
                                        tvOutTime.getText().toString().trim()
                                );

                            }

                        }

                    }
                }, R.id.iv_back, R.id.tv_get_city, R.id.tv_out_city, R.id.tv_get_address, R.id.tv_out_address, R.id.tv_get_time, R.id.tv_out_time, R.id.tv_select);
            }
        });
    }


    /**
     * 初始化定位
     */
    public void initGps() {
        locationManager = new LocationManager(getContext());
        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());
                getShopList(mLatLng.latitude, mLatLng.longitude);
                headTvGetCity.setText(location.getCity());
                headTvOutCity.setText(location.getCity());
                nowCity = location.getCity();
                locationManager.stopLocation();
            }
        });
    }

    /**
     * 初始化时间进程
     */
    private void initTime(TextView tvGetTime, TextView tvOutTime) {
        Calendar cal = Calendar.getInstance();
        if (mapGetTime == null) {
            mapGetTime = new LinkedHashMap<>();
        }
        mapGetTime.put("year", cal.get(Calendar.YEAR));
        mapGetTime.put("month", cal.get(Calendar.MONTH) + 1);
        mapGetTime.put("day", cal.get(Calendar.DAY_OF_MONTH));
        mapGetTime.put("hour", cal.get(Calendar.HOUR));
        mapGetTime.put("minute", cal.get(Calendar.MINUTE));
        if (mapOutTime == null) {
            mapOutTime = new LinkedHashMap<>();
        }
        String[] timeGroup = TimeManager.getAfterDay(2).split("-");
        mapOutTime.put("year", Integer.valueOf(timeGroup[0]));
        mapOutTime.put("month", Integer.valueOf(timeGroup[1]));
        mapOutTime.put("day", Integer.valueOf(timeGroup[2]));
        mapOutTime.put("hour", cal.get(Calendar.HOUR));
        mapOutTime.put("minute", cal.get(Calendar.MINUTE));
        tvGetTime.setText(String.format("%1$s-%2$s-%3$s %4$s:%5$s", mapGetTime.get("year"), mapGetTime.get("month"), mapGetTime.get("day"), mapGetTime.get("hour"), mapGetTime.get("minute")));
        tvOutTime.setText(String.format("%1$s-%2$s-%3$s %4$s:%5$s", mapOutTime.get("year"), mapOutTime.get("month"), mapOutTime.get("day"), mapOutTime.get("hour"), mapOutTime.get("minute")));
    }

    /**
     * 获取进程天数
     *
     * @param tvDay
     */
    private void getTimeDay(TextView tvDay) {
        if (mapGetTime != null && mapOutTime != null) {
            copyDay = TimeManager.getDays(String.format("%1$s-%2$s-%3$s", mapGetTime.get("year"), mapGetTime.get("month"), mapGetTime.get("day"))
                    , String.format("%1$s-%2$s-%3$s", mapOutTime.get("year"), mapOutTime.get("month"), mapOutTime.get("day")));

            tvDay.setText(String.format("%1$s%2$s", copyDay, getContext().getString(R.string.rv_days)));
        }

    }


    /**
     * 展示日历弹窗
     *
     * @param newYear
     * @param newMonth
     * @param newDay
     * @param tvTime
     */
    private void showDatePicker(int newYear, int newMonth, int newDay, final int newHour, final int newMinute, final TextView tvTime, final TextView tvWeek, final Map<String, Integer> map, final TextView tvDay) {
        if (tvTime == null) {
            return;
        }
        //实例化日期选择器悬浮窗
        //参数1：上下文对象
        //参数2：监听事件
        //参数3：初始化年份
        //参数4：初始化月份
        //参数5：初始化日期
        new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                map.clear();
                map.put("year", year);
                map.put("month", month + 1);
                map.put("day", dayOfMonth);
                tvTime.setText("");
                tvWeek.setText("");
                String tvMonth = month < 10 ? "0" + month : "" + month;
                String tvDays = month < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
                tvTime.append("" + year + "-" + tvMonth + "-" + tvDays + " ");
                showTimeDialog(newHour, newMinute, tvTime, map);
                getTimeDay(tvDay);
            }
        }, newYear, newMonth - 1,
                newDay).show();

    }

    /**
     * 展示时间弹窗
     * //实例化时间选择器
     * //参数1：上下文对象
     * //参数2：监听事件
     * //参数3：初始化小时
     * //参数4：初始化分钟
     * //参数5：是否24小时制
     */
    private void showTimeDialog(int hour, int minute, final TextView tvTime, final Map<String, Integer> map) {
        new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
            //实现监听方法
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {
                map.put("hour", i);
                map.put("minute", i1);

                //设置文本显示内容
                tvTime.append("" + i + ":" + i1);
            }
        }, hour, minute, true).show();//记得使用show才能显示！
    }

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

        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            new RxPermission(getActivity()).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 {
                        getActivity().finish();
                    }
                }
            });
        } else {
            initGps();
        }
    }

    /**
     * 传参
     * @param starCity
     * @param starAddress
     * @param endCity
     * @param endAddress
     * @param getTime
     * @param outTime
     * @param day
     * @param checkBox
     * @param startTime
     * @param endTime
     */
    private void sendData(String starCity, String starAddress, String endCity, String endAddress, String getTime, String outTime, int day, boolean checkBox, String startTime, String endTime) {
        if (dataBean == null) {
            dataBean = new OrderDataBean();
        }
        if (getCityId > 0 && outCityId > 0) {
            dataBean.setEndCity(outCityId);
            dataBean.setStartCity(getCityId);
        } else {
            String json = UtilsManager.getInstance().getJson(getContext(), "city.json");
            CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);
            for (CityPickerBean.CityBean cityBean : bean.getCity()) {
                for (ListsBean lsBean : cityBean.getLists()) {
                    if (starCity.equals(lsBean.getName())) {
                        dataBean.setStartCity(lsBean.getId());
                    }

                    if (endCity.equals(lsBean.getName())) {
                        dataBean.setEndCity(lsBean.getId());
                    }
                }
            }
        }
        dataBean.setDayNum(day);
        dataBean.setStartCityName(starCity);
        dataBean.setStartAddr(starAddress);
        try {
            dataBean.setStartTime(TimeManager.dateToStamp(getTime));
            dataBean.setEndTime(TimeManager.dateToStamp(outTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dataBean.setEndCityName(endCity);
        dataBean.setEndAddr(endAddress);
        dataBean.setDriverType(checkBox == true ? 1 : 2);
        startActivity(CarRentalListActivity.getIntent(getContext(), latLatitude, lonLongitude, checkBox, dataBean, startTime, endTime));
    }
}
