package com.xxrv.carpurchase.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.base.utils.ui.datetime.picker.simple.SampleDateTimeActivity;
import com.base.utils.ui.datetime.selector.util.DateUtil;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.bigkoo.pickerview.TimePickerView;
import com.frame.base.url.Constance;
import com.frame.base.view.StarBar;
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.glide.GlideApp;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.DateUtils;
import com.xxrv.carpurchase.R;
import com.xxrv.carpurchase.R2;
import com.xxrv.carpurchase.api.CarPurchaseApi;
import com.xxrv.carpurchase.presenter.CarPurchasePresenter;
import com.yuyife.okgo.OkGoUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

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

/**
 * 预约信息
 */
public class ReservationInformationActivity extends BaseStatusActivity<CarPurchasePresenter> {


    @BindView(R2.id.iv_car_goods)
    ImageView ivCarGoods;
    @BindView(R2.id.tv_car_name)
    TextView tvCarName;
    @BindView(R2.id.tv_car_context)
    TextView tvCarContext;
    @BindView(R2.id.tv_point)
    TextView tvPoint;
    @BindView(R2.id.starbar1)
    StarBar starbar1;
    @BindView(R2.id.ll_content)
    LinearLayout llContent;
    @BindView(R2.id.tv_car_price)
    TextView tvCarPrice;
    @BindView(R2.id.et_name)
    EditText etName;
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.tv_date)
    TextView tvDate;
    @BindView(R2.id.tv_branch_office_name)
    TextView tvBranchOfficeName;
    @BindView(R2.id.tv_branch_office_address)
    TextView tvBranchOfficeAddress;
    @BindView(R2.id.et_remark)
    EditText etRemark;

    private String id;

    private LocationManager locationManager;
    private double latLatitude = 0;
    private double lonLongitude;
    private String nowCity = "";
    private  int company_id;

    public static Intent getIntent(Context context, String id, String icon, String name, String keyword, int score, double buyPrice) {
        return new Intent(context, ReservationInformationActivity.class)
                .putExtra("id", id)
                .putExtra("icon", icon)
                .putExtra("name", name)
                .putExtra("keyword", keyword)
                .putExtra("score", score)
                .putExtra("buyPrice", buyPrice);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("预约信息");
        permissionProcess();
        initData(intent);
    }

    private void initData(Intent intent) {
        id = intent.getStringExtra("id");
        String icon = intent.getStringExtra("icon");
        String name = intent.getStringExtra("name");
        String keyword = intent.getStringExtra("keyword");
        int scores = intent.getIntExtra("score", 0);
        double buyPrice = intent.getDoubleExtra("buyPrice", 0);

        float score = (float) scores / 10;

        GlideManager.getInstance(mActivity).loadImage(icon, ivCarGoods);
        tvCarName.setText(name);
        tvCarContext.setText(keyword);
        starbar1.setStarMark(score);
        tvPoint.setText(score + "分");
        tvCarPrice.setText("¥" + buyPrice);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
         switch (requestType){
             case 1:
                 showToast("预约成功！");
                 finish();
                 break;
         }
    }

    @OnClick({R2.id.ll_item_select_date, R2.id.ll_item_select_branch_office, R2.id.tv_item_submit})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_select_date) {
            initTimePicker1();

        } else if (id == R.id.ll_item_select_branch_office) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_SELECTSHOP)
                    .withDouble("mLat",latLatitude)
                    .withDouble("mLon",lonLongitude)
                    .withString("cityName",nowCity)
                    .navigation(mActivity,122);
        } else if (id == R.id.tv_item_submit) {
            upDate();
        }
    }

    /**
     * 提交数据
     */
    private void upDate() {
        String name = etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            showToast("姓名不能为空！");
            return;
        }

        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast("电话不能为空！");
            return;
        }

        if (phone.length() != 11) {
            showToast("手机号码不正确！");
            return;
        }

        String date = tvDate.getText().toString();
        if (TextUtils.isEmpty(date)){
            showToast("预约时间不能为空！");
            return;
        }

//        String branchoffice = tvBranchOfficeName.getText().toString();
//        if (TextUtils.isEmpty(branchoffice)){
//            showToast("分公司不能为空！");
//            return;
//        }

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

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("bookTime", DateUtils.StringToTimeMillis2(date));
        map.put("companyId", company_id);
        map.put("contactName", name);
        map.put("contactPhone", phone);
        map.put("modelId", id);
        map.put("remark", etRemark.getText().toString().trim());

        mPresenter.postBodyData(RvFrameConfig.HOST, 1, CarPurchaseApi.HTTP_URL_BUYVEHICLEFORM, BaseBean.class, map,headMap, true);
    }


    private void initTimePicker1() {//选择出生年月日
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        SimpleDateFormat formatter_year = new SimpleDateFormat("yyyy ");
        String year_str = formatter_year.format(curDate);
        int year_int = (int) Double.parseDouble(year_str);

        SimpleDateFormat formatter_mouth = new SimpleDateFormat("MM ");
        String mouth_str = formatter_mouth.format(curDate);
        int mouth_int = (int) Double.parseDouble(mouth_str);

        SimpleDateFormat formatter_day = new SimpleDateFormat("dd ");
        String day_str = formatter_day.format(curDate);
        int day_int = (int) Double.parseDouble(day_str);

        SimpleDateFormat formatter_hh = new SimpleDateFormat("HH ");
        String hh_str = formatter_hh.format(curDate);
        int hh_int = (int) Double.parseDouble(hh_str);

        SimpleDateFormat formatter_mm = new SimpleDateFormat("mm ");
        String mm_str = formatter_mm.format(curDate);
        int mm_int = (int) Double.parseDouble(mm_str);

        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(year_int, mouth_int - 1, day_int, hh_int, mm_int);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year_int, mouth_int + 1, day_int);

        //时间选择器
        TimePickerView build = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                tvDate.setText(DateUtils.formatDate55(date));
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "时", "分", "")//默认设置为年月日时分秒
                .isCenterLabel(false)
                .setSubmitColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTextColorOut(Color.GRAY)//设置没有被选中项的颜色
                .setContentSize(21)
                .setDate(selectedDate)
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(-10, 0, 10, 0, 0, 0)//设置X轴倾斜角度[ -90 , 90°]
                .setRangDate(selectedDate, endDate)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
        build.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 122 && resultCode == RESULT_OK) {
            company_id = data.getIntExtra("company_id", 0);
            String company = data.getStringExtra("company");
            String address = data.getStringExtra("address");
            tvBranchOfficeName.setText(company);
            tvBranchOfficeAddress.setText(address);
        }
    }



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

        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            new RxPermission(mActivity).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(mActivity);
        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();
                latLatitude = location.getLatitude();
                lonLongitude = location.getLongitude();
                nowCity = location.getCity();
                locationManager.stopLocation();
            }
        });
    }
}
