package com.tjzhxx.union.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
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 DataEditeZywwActivity extends BaseActivity {
    @BindView(R.id.iv_type1)
    ImageView ivType1;
    @BindView(R.id.iv_type2)
    ImageView ivType2;
    @BindView(R.id.iv_type3)
    ImageView ivType3;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.spiner)
    Spinner spiner;
    @BindView(R.id.hosiptial)
    EditText hosiptial;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.unit)
    EditText unit;
    @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;
    private Resucekey key3;
    private Resucekey key4;
    private Resucekey key5;

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

    @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);
        final String[] type = getResources().getStringArray(R.array.type);
        spiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                key2.setInfovalue(type[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        queryrescuelistforapp();
        initDate();
    }

    private void initDate() {
        key1 = new Resucekey();
        key1.setInfokey("illnesskind");
        key1.setInfodisstr("患病类型");
        key1.setIsmust(1);
        key1.setInfovalue("工伤(职业病)");//默认值
        key1.setIsuseauditing(1);

        key2 = new Resucekey();
        key2.setInfokey("illness");
        key2.setInfodisstr("患病名称");
        key2.setIsmust(1);
        key2.setIsuseauditing(1);


        key3 = new Resucekey();
        key3.setInfokey("inhospital");
        key3.setInfodisstr("入住医院");
        key3.setIsmust(1);
        key3.setIsuseauditing(1);


        key4 = new Resucekey();
        key4.setInfokey("inhospitaldate");
        key4.setInfodisstr("入院日期");
        key4.setIsmust(1);
        key4.setIsuseauditing(1);

        key5 = new Resucekey();
        key5.setInfokey("employeeinfo");
        key5.setInfodisstr("单位及职务");
        key5.setIsmust(0);
        key5.setIsuseauditing(1);


    }

    @OnClick({R.id.type1, R.id.type2, R.id.type3, R.id.date, R.id.submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.type1:
                key1.setInfovalue("工伤(职业病)");
                ivType1.setImageResource(R.mipmap.icon_checkbox_select);
                ivType2.setImageResource(R.mipmap.icon_checkbox_normal);
                ivType3.setImageResource(R.mipmap.icon_checkbox_normal);
                name.setVisibility(View.VISIBLE);
                spiner.setVisibility(View.GONE);
                break;
            case R.id.type2:
                key1.setInfovalue("指定重病");
                ivType1.setImageResource(R.mipmap.icon_checkbox_normal);
                ivType2.setImageResource(R.mipmap.icon_checkbox_select);
                ivType3.setImageResource(R.mipmap.icon_checkbox_normal);
                name.setVisibility(View.GONE);
                spiner.setVisibility(View.VISIBLE);
                break;
            case R.id.type3:
                key1.setInfovalue("其他");
                ivType1.setImageResource(R.mipmap.icon_checkbox_normal);
                ivType2.setImageResource(R.mipmap.icon_checkbox_normal);
                ivType3.setImageResource(R.mipmap.icon_checkbox_select);
                name.setVisibility(View.VISIBLE);
                spiner.setVisibility(View.GONE);
                break;
            case R.id.date:
                showTimeDialog();
                break;
            case R.id.submit:
                submit();
                break;
        }
    }

    public void submit() {
        doclist.clear();
        resucekeys.clear();
        if (key2.getIsmust() == 1){
            if (name.getVisibility() == View.VISIBLE && TextUtils.isEmpty(name.getText().toString())){
                showSnackBar("请输入患病名称");
                return;
            }
        }

        if (key3.getIsmust() == 1){
            if (TextUtils.isEmpty(hosiptial.getText().toString())){
                showSnackBar("请输入入住医院");
                return;
            }
        }
        if (key4.getIsmust() == 1){
            if (TextUtils.isEmpty(date.getText().toString())){
                showSnackBar("请选择入院时间");
                return;
            }
        }
        if (key5.getIsmust() == 1){
            if (TextUtils.isEmpty(unit.getText().toString())){
                showSnackBar("请输入单位及职务");
                return;
            }
        }
        key2.setInfovalue(name.getText().toString());
        key3.setInfovalue(hosiptial.getText().toString());
        key4.setInfovalue(date.getText().toString());
        key5.setInfovalue(unit.getText().toString());
        resucekeys.add(key1);
        resucekeys.add(key2);
        resucekeys.add(key3);
        resucekeys.add(key4);
        resucekeys.add(key5);

        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("2");
        request.setDoclist(new Gson().toJson(doclist));
        request.setValuelist(new Gson().toJson(resucekeys));
        subapplywithdocandinfoforapp(request);
    }

    private void queryrescuelistforapp() {
        services.queryrescuelistforapp(2)
                .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);
    }

}
