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

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.GpsManager;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.MyUtils;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
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.ShopListBean;
import com.rv.home.rv.module.ui.main.home.presenter.CarRentPresenter;

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

import butterknife.BindView;
import butterknife.OnClick;

public class CarRentActivity extends BaseStatusActivity<CarRentPresenter> implements GpsManager.GpsChangeListener {

    private static final int TYPE_REQUEST_CITY = 10000;

    @BindView(R2.id.ll_rent)
    LinearLayout llRent;
    @BindView(R2.id.tv_home_get_address)
    TextView tvHomeGetAddress;
    @BindView(R2.id.ll_return)
    LinearLayout llReturn;
    @BindView(R2.id.tv_home_out_address)
    TextView tvHomeOutAddress;
    @BindView(R2.id.tv_home_get_time)
    TextView tvHomeGetTime;
    @BindView(R2.id.tv_home_get_week)
    TextView tvHomeGetWeek;
    @BindView(R2.id.tv_home_day)
    TextView tvHomeDay;
    @BindView(R2.id.tv_home_out_time)
    TextView tvHomeOutTime;
    @BindView(R2.id.tv_home_out_week)
    TextView tvHomeOutWeek;
    @BindView(R2.id.tv_home_select_car)
    Button tvHomeSelectCar;

    private String outCityName;
    private String getCompanyName; // 取车公司
    private String outCompanyName; // 还车公司

    private double latLatitude;  // 当前的经纬度
    private double lonLongitude; // 当前的经纬度

    private String begDate = "";  // 租车起始时间
    private String endDate = ""; // 还车时间

    private String getCityName; // 取车城市
    private int getCityId; // 取车城市id
    private int outCityId; // 还车城市id

    private int getCompanyId; // 取车公司id
    private int outCompanyId; // 还车公司id

    private LocationManager locationManager;

    private long rentDay = 2;//租车天数

    public static Intent getIntent(Context context, String cityName) {
        Intent intent = new Intent(context, CarRentActivity.class);
        intent.putExtra("cityName", cityName);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(getString(R.string.rv_home_title_recent_info));
        GpsManager.getInstance(this).bindGpsListener(this);
        setDefaultTime();
        initGps();
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getCityName = outCityName = intent.getStringExtra("cityName");
        if (!TextUtils.isEmpty(getCityName)) {
            getShopList();
        }
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {

        switch (requestType) {
            case 0:
                processData((ShopListBean) result);
                break;
        }
    }

    /**
     * 获取门店列表
     */
    private void getShopList() {
        int addrCity = 0;
        String json = UtilsManager.getInstance().getJson(mActivity, "city.json");
        CityPickerBean bean = new Gson().fromJson(json, CityPickerBean.class);
        for (CityPickerBean.CityBean cityBean : bean.getCity()) {
            for (ListsBean lsBean : cityBean.getLists()) {
                if (!TextUtils.isEmpty(getCityName)) {
                    if (getCityName.equals(lsBean.getName())) {
                        addrCity = lsBean.getId();
                    }
                }
            }
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", 1);
        map.put("limit", 1);
        map.put("addrCity", String.valueOf(addrCity));
        mPresenter.getData(RvFrameConfig.VEHICLE_POST, 0, ApiConfig.HTTP_URL_SHOP_LIST, ShopListBean.class, map, false);
    }

    /**
     * 处理最近门店请求结果
     *
     * @param bean
     */
    private void processData(ShopListBean bean) {
        if (bean.getData() != null && bean.getData().getTotalCount() > 0) {

            getCompanyName = bean.getData().getData().get(0).getName();
            StringBuffer getBuffer = new StringBuffer();
            if (!TextUtils.isEmpty(getCompanyName)) {
                getBuffer.append(getCompanyName);
            }
            if (!TextUtils.isEmpty(getCityName)) {
                getBuffer.append("(").append(getCityName).append(")");
            }

            if (getBuffer != null && getBuffer.length() > 0) {
                tvHomeGetAddress.setText(getBuffer.toString());
            } else {
                tvHomeGetAddress.setText("");
            }
            tvHomeGetAddress.setTextColor(getResources().getColor(R.color.colorMain));

            getCompanyId = bean.getData().getData().get(0).getId();

            outCompanyName = bean.getData().getData().get(0).getName();
            StringBuffer outBuffer = new StringBuffer();
            if (!TextUtils.isEmpty(outCompanyName)) {
                outBuffer.append(outCompanyName);
            }
            if (!TextUtils.isEmpty(outCityName)) {
                outBuffer.append("(").append(outCityName).append(")");
            }
            if (outBuffer != null && outBuffer.length() > 0) {
                tvHomeOutAddress.setText(outBuffer.toString());
            } else {
                tvHomeOutAddress.setText("");
            }
            tvHomeOutAddress.setTextColor(getResources().getColor(R.color.colorMain));
            outCompanyId = bean.getData().getData().get(0).getId();
        } else {
            getCompanyName = "";
            tvHomeGetAddress.setText(getCompanyName);
            outCompanyName = "";
            tvHomeOutAddress.setText(outCompanyName);
        }
    }

    /**
     * 设置默认时间
     */
    private void setDefaultTime() {
        String time = DateUtils.formatDate28(DateUtils.timestampToString1(DateUtils.getCurTimeMillis()), 2);
        String hh = DateUtils.formatDate21(time);
        String mm = DateUtils.formatDate22(time);
        String begTime = "";
        if (Double.valueOf(mm) > 30) {   //判断当前分钟是否已经超过30，如果超过了取整加30分钟
            begTime = DateUtils.formatDate19(hh + ":30");
        } else {
            begTime = hh + ":30";
        }

        if (DateUtils.formatDate20(begTime) > DateUtils.formatDate20("22:30")) {   //如果当前时间大于 22：30，日期往后加一，时间改成早上8：00
            begDate = MyUtils.getFetureDate(1) + " " + "08:30";
            endDate = MyUtils.getFetureDate(3) + " " + "08:30";
        } else {
            begDate = MyUtils.getFetureDate(0) + " " + begTime;
            endDate = MyUtils.getFetureDate(2) + " " + begTime;
        }

        tvHomeGetTime.setText(DateUtils.formatDate66(begDate));
        tvHomeGetWeek.setText("周" + MyUtils.getWeek(DateUtils.formatDate16(begDate)));

        tvHomeOutTime.setText(DateUtils.formatDate66(endDate));
        tvHomeOutWeek.setText("周" + MyUtils.getWeek(DateUtils.formatDate16(endDate)));

        rentDay = getCountDay(begDate, endDate);
        tvHomeDay.setText(String.format("%1$s%2$s", rentDay, getString(R.string.rv_days)));
    }

    /**
     * 计算天数
     *
     * @param endDate2
     * @param begDate2
     * @return
     */
    private long getCountDay(String begDate2, String endDate2) {
        long second = DateUtils.compareDateSecond3(endDate2, begDate2);   //两个时间相差的秒数
        long day = second / 86400;       //天数
        long remainder = second % 86400;  //余数  秒

        if (day == 0) {               //不够24小时也算一天
            day = day + 1;
        } else if (remainder > 14400) {    //4小时内天数不增加，否则加一
            day = day + 1;
        }
        return day;
    }

    @OnClick({R2.id.ll_rent, R2.id.tv_home_get_address, R2.id.ll_return, R2.id.tv_home_out_address, R2.id.ll_home_item_select_data,
            R2.id.tv_home_select_car})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_home_get_address || id == R.id.ll_rent) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat", latLatitude)
                    .withDouble("mLon", lonLongitude)
                    .withString("cityName", getCityName)
                    .withInt("shopType", 1)
                    .navigation(mActivity, TYPE_REQUEST_CITY);
        } else if (id == R.id.ll_return || id == R.id.tv_home_out_address) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat", latLatitude)
                    .withDouble("mLon", lonLongitude)
                    .withString("cityName", outCityName)
                    .withInt("shopType", 2)
                    .navigation(mActivity, TYPE_REQUEST_CITY);
        } else if (id == R.id.ll_home_item_select_data) {
            //选择日期
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CALENDAR)
                    .withString("begDate", begDate)
                    .withString("endDate", endDate)
                    .navigation(mActivity, 108);
        } else if (id == R.id.tv_home_select_car) {
            //租房车 立即选车
            if (rentDay < 1) {
                showToast(getString(R.string.rv_day_toast));
                return;
            }
            if (TextUtil.isEmpty(tvHomeGetAddress.getText().toString().trim()) ||
                    TextUtil.isEmpty(tvHomeOutAddress.getText().toString().trim())) {
                showToast("请选择取/还车地址");
                return;
            }

            mPresenter.sendData(getCityId,outCityId,getCompanyId,outCompanyId,
                    latLatitude,lonLongitude,getCityName,
                    getCompanyName,
                    outCityName,
                    outCompanyName,
                    begDate, endDate, rentDay,
                    begDate,
                    endDate
            );
        }
    }

    /**
     * 初始化定位
     */
    public void initGps() {
        if(locationManager == null){
            locationManager = new LocationManager(mActivity);
        }
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                latLatitude = location.getLatitude();
                lonLongitude = location.getLongitude();
                locationManager.stopLocation();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TYPE_REQUEST_CITY: //城市列表
                if (data == null) return;
                int type = data.getIntExtra("type", 1);
                String requestData = data.getStringExtra("location");
                if (type == 1) {
                    getCompanyName = data.getStringExtra("company");
                    getCompanyId = data.getIntExtra("company_id", 1);
                    getCityName = requestData;
                    getCityId = data.getIntExtra("id", 0);
                    StringBuffer buffer = new StringBuffer();
                    if (!TextUtils.isEmpty(getCompanyName)) {
                        buffer.append(getCompanyName);
                    }
                    if (!TextUtils.isEmpty(getCityName)) {
                        buffer.append("(").append(getCityName).append(")");
                    }
                    if (buffer.length() > 0) {
                        tvHomeGetAddress.setText(buffer.toString());
                    } else {
                        tvHomeGetAddress.setText("");
                    }
                } else if (type == 2) {
                    outCompanyName = data.getStringExtra("company");
                    outCompanyId = data.getIntExtra("company_id", 1);
                    outCityName = requestData;
                    outCityId = data.getIntExtra("id", 0);
                    StringBuffer buffer = new StringBuffer();
                    if (!TextUtils.isEmpty(outCompanyName)) {
                        buffer.append(outCompanyName);
                    }
                    if (!TextUtils.isEmpty(outCityName)) {
                        buffer.append("(").append(outCityName).append(")");
                    }
                    if (buffer.length() > 0) {
                        tvHomeOutAddress.setText(buffer.toString());
                    } else {
                        tvHomeOutAddress.setText("");
                    }
                }
                break;
            case 108:
                if (resultCode == 200) {
                    begDate = data.getStringExtra("begDate");
                    endDate = data.getStringExtra("endDate");
                    rentDay = getCountDay(begDate, endDate);  //天数
                }

                tvHomeGetTime.setText(DateUtils.formatDate66(begDate));
                tvHomeOutTime.setText(DateUtils.formatDate66(endDate));
                tvHomeGetWeek.setText("周" + MyUtils.getWeek(begDate));
                tvHomeOutWeek.setText("周" + MyUtils.getWeek(endDate));
                tvHomeDay.setText(String.format("%1$s%2$s", rentDay, getString(R.string.rv_days)));
                break;
            default:
                break;
        }
    }

    @Override
    public void gpsChange(boolean b) {
        if(b){
            initGps();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GpsManager.getInstance(this).unbindGpsListener(this);
    }
}
