package com.tjzhxx.union.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.tjzhxx.union.R;
import com.tjzhxx.union.adapter.RescuestyleAdapter;
import com.tjzhxx.union.custom_view.CustomDatePicker;
import com.tjzhxx.union.entity.BaseResponse;
import com.tjzhxx.union.entity.Doclist;
import com.tjzhxx.union.entity.Rescuestyle;
import com.tjzhxx.union.entity.Resucekey;
import com.tjzhxx.union.entity.request.DataZywwRequest;
import com.tjzhxx.union.public_store.ConstDefine;
import com.tjzhxx.union.public_store.TimeUtil;
import com.tjzhxx.union.public_store.retrofit.RetrofitUtils;
import com.tjzhxx.union.public_store.retrofit.UnionServices;
import com.tjzhxx.union.public_store.rx.DefaultSubscriber;
import com.tjzhxx.union.public_store.rx.ProgressSubscriber;
import com.tjzhxx.union.system.BaseActivity;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 描述:
 *
 * @author yhx
 * @create 2021/9/7  11:45 PM
 */
public class DataEditeJtccActivity extends BaseActivity {
    @BindView(R.id.price)
    EditText price;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private List<Rescuestyle> list = new ArrayList<>();
    private List<Resucekey> resucekeys = new ArrayList<>();
    private List<Doclist> doclist = new ArrayList<>();
    private RescuestyleAdapter adapter;
    private UnionServices services;
    private Resucekey key1;
    private Resucekey key2;

    @Override
    public int getContentViewLayoutID() {
        return R.layout.activity_data_edite_jtcc;
    }

    @Override
    public void bindViewAndEvent(Bundle savedInstanceState) {
        initTitle("家庭财产损失资料填写");
        services = RetrofitUtils.createApi(UnionServices.class, ConstDefine.HttpAdress);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RescuestyleAdapter(this, list);
        recyclerView.setAdapter(adapter);
        queryrescuelistforapp();
        initDate();
    }

    private void initDate() {
        key1 = new Resucekey();
        key1.setInfokey("firemoney");
        key1.setInfodisstr("火灾损失金额");
        key1.setIsmust(1);
        key1.setIsuseauditing(1);

        key2 = new Resucekey();
        key2.setInfokey("firedate");
        key2.setInfodisstr("火灾时间");
        key2.setIsmust(1);
        key2.setIsuseauditing(1);




    }

    @OnClick({R.id.date, R.id.submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.date:
                showTimeDialog();
                break;
            case R.id.submit:
                submit();
                break;
        }
    }

    public void submit() {
        doclist.clear();
        resucekeys.clear();
        if (key1.getIsmust() == 1){
            if (TextUtils.isEmpty(price.getText().toString())){
                showSnackBar("请输入火灾损失金额");
                return;
            }
        }
        if (key2.getIsmust() == 1){
            if (TextUtils.isEmpty(date.getText().toString())){
                showSnackBar("请选择火灾时间");
                return;
            }
        }
        key1.setInfovalue(price.getText().toString());
        key2.setInfovalue(date.getText().toString());
        resucekeys.add(key1);
        resucekeys.add(key2);
        for (Rescuestyle rescuestyle : list) {
            if (rescuestyle.getIsmust().equals("1") && TextUtils.isEmpty(rescuestyle.getImageUrl())) {
                showSnackBar("请上传" + rescuestyle.getDockind());
                return;
            } else {
                Doclist bean = new Doclist();
                bean.setDocstyle(rescuestyle.getDockind());
                bean.setDocurl(rescuestyle.getImageUrl());
                doclist.add(bean);
            }
        }

        DataZywwRequest request = new DataZywwRequest();
        request.setApplytelno(ConstDefine.userInfo.getTelno());
        request.setWid(ConstDefine.userInfo.getWid());
        request.setRescuestyle("6");
        request.setDoclist(new Gson().toJson(doclist));
        request.setValuelist(new Gson().toJson(resucekeys));
        subapplywithdocandinfoforapp(request);
    }

    private void queryrescuelistforapp() {
        services.queryrescuelistforapp(6)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<List<Rescuestyle>>>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new DefaultSubscriber<BaseResponse<List<Rescuestyle>>>(this) {
                    @Override
                    public void success(BaseResponse<List<Rescuestyle>> value) {
                        if (value.getData() != null) {
                            list.clear();
                            list.addAll(value.getData());
                            adapter.notifyDataSetChanged();
                        }
                    }

                });
    }

    private void subapplywithdocandinfoforapp(DataZywwRequest request) {
        services.subapplywithdocandinfoforapp(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new ProgressSubscriber<BaseResponse>(this) {
                    @Override
                    public void success(BaseResponse value) {
                        showSnackBar("提交成功");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 1500);
                    }

                });
    }
    private void showTimeDialog() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String endSong = sdf.format(new Date());
        String nowSong = TimeUtil.getDateByYear(endSong, -20, "yyyy-MM-dd HH:mm");

        CustomDatePicker customDatePicker = new CustomDatePicker(mContext, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                date.setText(time.split(" ")[0]);
            }
        }, nowSong, endSong); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 显示时和分
        customDatePicker.setIsLoop(true); // 允许循环滚动
        customDatePicker.show(nowSong);
    }

}
