package com.example.chemical.ui.add;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.example.chemical.ChemicalApp;
import com.example.chemical.databinding.ActivityPlanAddBinding;
import com.example.chemical.databinding.ActivityPlanAddBinding;
import com.example.chemical.receiver.ScanKeyEventHelper;
import com.example.chemical.ui.SplashActivity;
import com.example.chemical.ui.common.BaseCountDownActivity;
import com.example.chemical.utils.UiManager;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.ChemicalInfoBean;
import com.rc.httpcore.bean.locker.HxpCabinetListVo;
import com.rc.httpcore.bean.locker.HxpCabinetVo;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.client.HttpTool;
import com.rc.httpcore.exception.NetException;

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

import io.reactivex.functions.Consumer;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import okhttp3.Response;

/**
 * 待录入页面
 */
public class PlanAddActivity extends BaseCountDownActivity<ActivityPlanAddBinding> {

    private ActivityPlanAddBinding binding;
    // 柜子fragmentAdapter
    private LockerAdapter lockerAdapter;
    // 二维码/条形码扫描工具
    private ScanKeyEventHelper scanKeyEventHelper;
    // 实验室基本信息
    private ChemicalInfoBean chemicalInfo;
    // 实验室所有柜子信息
    private List<HxpCabinetVo> allCabinetVoList;

    // 待录入化学品信息
//    private Map<Long,List<>>

    @NonNull
    @Override
    protected ActivityPlanAddBinding createViewBinding() {
        return binding = ActivityPlanAddBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        binding.lockerVP2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                binding.countTV.setText((position + 1) + "/" + lockerAdapter.getItemCount());
            }
        });
        binding.nextBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.lockerVP2.setCurrentItem(binding.lockerVP2.getCurrentItem() + 1, true);
            }
        });
        binding.lastBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.lockerVP2.setCurrentItem(binding.lockerVP2.getCurrentItem() - 1, true);
            }
        });

        scanKeyEventHelper = new ScanKeyEventHelper(new Function1<String, Unit>() {
            @Override
            public Unit invoke(String s) {
                Log.d("结果", s);
                return null;
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        // 日期
        binding.nowTime.setText(TimeUtils.getNowString(new SimpleDateFormat("MM月dd日 EEEE ", Locale.getDefault())));
        // 用户
        Glide.with(this).load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + ChemicalApp.userData.getAvatar()).into(binding.imageName);
        String userName = ChemicalApp.userData.getUserName();
        binding.tvName.setText(TextUtils.isEmpty(userName) ? "" : userName);
        // 实验室logo
        Glide.with(this).load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + ChemicalApp.confs.getCircularLogo()).into(binding.image);
        // 实验室名称
        String subName = ChemicalApp.subjectName;
        subName = TextUtils.isEmpty(subName) ? "" : subName;
        // 房间号
        String roomNum = ChemicalApp.subRoom;
        roomNum = TextUtils.isEmpty(roomNum) ? "" : roomNum;
        binding.deptName.setText(subName + "-" + roomNum);
        // 退出
        binding.tvOutLogin.setOnClickListener(v -> callLogoutApi(aBoolean -> {
            ChemicalApp.userData = null;
            ChemicalApp.subjectId = null;
            UiManager.INSTANCE.switcherCashier(PlanAddActivity.this, SplashActivity.class);
            return null;
        }));

        //获取实验室基本信息
        getLabInfo();

    }

    /**
     * 获取实验室基本信息
     */
    private void getLabInfo() {
        showLoading("加载中...", false);
        // 实验室基本信息
        addDisposable(ApiRepository.INSTANCE.getRelList(ChemicalApp.subjectId).subscribe(new Consumer<ChemicalInfoBean>() {
            @Override
            public void accept(ChemicalInfoBean chemicalInfoBean) throws Exception {
                chemicalInfo = chemicalInfoBean;
                // 获取实验室柜子信息
                ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<List<HxpCabinetVo>>() {
                    @Override
                    public List<HxpCabinetVo> doInBackground() throws Throwable {
                        Response response = HttpTool.getCabinetList(chemicalInfoBean.getSubId());
                        if (response.isSuccessful()) {
                            String json = response.body().string();
                            HxpCabinetListVo hxpCabinetListVo = GsonUtils.fromJson(json, HxpCabinetListVo.class);
                            if (hxpCabinetListVo.getCode() == 200) {
                                return hxpCabinetListVo.getData();
                            } else {
                                throw new NetException("" + hxpCabinetListVo.getCode(), hxpCabinetListVo.getMessage());
                            }
                        } else {
                            throw new NetException("" + response.code(), response.message());
                        }
                    }

                    @Override
                    public void onSuccess(List<HxpCabinetVo> hxpCabinetVoList) {
                        dismissLoading();
                        if (null != hxpCabinetVoList && !hxpCabinetVoList.isEmpty()) {
                            lockerAdapter = new LockerAdapter(PlanAddActivity.this, allCabinetVoList = hxpCabinetVoList, fragmentCallBack);
                            binding.lockerVP2.setAdapter(lockerAdapter);

                        } else {
                            showToast("未找到化学品柜!");
                        }
                    }

                    @Override
                    public void onFail(Throwable t) {
                        super.onFail(t);
                        showNetError(t);
                        dismissLoading();
                        LogUtils.d(ThreadUtils.isMainThread());
                    }
                });
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtils.e(Log.getStackTraceString(throwable));
                dismissLoading();
                showNetError(throwable);
            }
        }));
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        scanKeyEventHelper.analysisKeyEvent(event);
        return super.dispatchKeyEvent(event);
    }

    FragmentCallBack fragmentCallBack = new FragmentCallBack() {
        /**
         * 柜层被选中
         * @param hxpCabinetVo 柜子信息
         * @param position     选中的是哪层
         */
        @Override
        public void onSelected(HxpCabinetVo hxpCabinetVo, int position) {

        }
    };

    @Override
    protected void onDestroy() {
        fragmentCallBack = null;
        super.onDestroy();
    }

}