package com.example.chemical.ui.plan;

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

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
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.receiver.ScanKeyEventHelper;
import com.example.chemical.ui.SplashActivity;
import com.example.chemical.ui.common.BaseCountDownActivity;
import com.example.chemical.ui.plan.add.AddActivity;
import com.example.chemical.ui.plan.locker.LockerAdapter;
import com.example.chemical.ui.plan.room.RoomTool;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetDoorVo;
import com.example.chemical.ui.plan.room.dao.HxpCabinetDAO;
import com.example.chemical.ui.plan.room.dao.HxpDoorDAO;
import com.example.chemical.ui.plan.room.dao.HxpLayerDAO;
import com.example.chemical.utils.UiManager;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.ChemicalInfoBean;
import com.example.chemical.ui.plan.room.bean.input_add.InventoryItemBean;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetListVo;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetVo;
import com.example.chemical.ui.plan.room.bean.locker.CabinetLayerSelect;
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.ArrayList;
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> serverCabinetVoList;
    // 当前选择信息
    private CabinetLayerSelect nowSelectInfo;
    // 当前展示的待存储列表
    private List<InventoryItemBean> inventoryItemBeanList = new ArrayList<>();
    // 当前展示的待存储列表适配器
    private PlanAdapter planAdapter;
    // 柜子DAO
    private HxpCabinetDAO hxpCabinetDAO;
    // 柜门DAO
    private HxpDoorDAO hxpDoorDAO;
    // 柜层DAO
    private HxpLayerDAO hxpLayerDAO;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @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(view -> binding.lockerVP2.setCurrentItem(binding.lockerVP2.getCurrentItem() + 1, true));
        binding.lastBT.setOnClickListener(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;
            }
        });

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                LogUtils.d(result.getResultCode());
                //                try {
//                    String newB = "{\"anotherName\":\"ys\",\"casNum\":\"2024-07-2401\",\"chemicalCategory\":\"5\",\"chemicalCategoryName\":\"精神麻醉类\",\"chemicalDensity\":1.0,\"chemicalId\":1815944402825064449,\"chemicalLevel\":2,\"chemicalLevelName\":null,\"chemicalName\":\"乙酸\",\"chemicalPurity\":\"0.9\",\"createTime\":\"2024-07-24 02:57\",\"depositUnit\":\"KG\",\"packNum\":2.1,\"packUnit\":\"件\",\"specNum\":500.0,\"specUnit\":\"g\"}";
//                    HxpChemicalVo hxpChemicalVo = GsonUtils.fromJson(newB, HxpChemicalVo.class);
//                    InventoryItemBean inventoryItemBean = new InventoryItemBean();
//                    inventoryItemBean.setHxpChemicalVo(hxpChemicalVo);
//                    CabinetLayerSelect cabinetLayerSelect = hxpLayerDAO.getById(nowSelectInfo.getCabinetId(), nowSelectInfo.getDoorId(), nowSelectInfo.getLayer());
//                    if (cabinetLayerSelect == null) {
//                        cabinetLayerSelect = new CabinetLayerSelect(nowSelectInfo.getCabinetId(), nowSelectInfo.getDoorId(), nowSelectInfo.getLayer());
//                    }
//                    inventoryItemBeanList.add(inventoryItemBean);
//                    cabinetLayerSelect.setInventoryItemBeanList(inventoryItemBeanList);
//                    hxpLayerDAO.insert(cabinetLayerSelect);
//
//                    LogUtils.json(hxpLayerDAO.getAll());
//
//
////                    updateInventoryListByCabinet(nowSelectInfo, inventoryItemBeanList);
//
//                    if (binding.scanLL.getVisibility() == View.VISIBLE) {
//                        binding.scanLL.setVisibility(View.GONE);
//                        binding.planLV.setVisibility(View.VISIBLE);
//                    }
//
//                    planAdapter.notifyDataSetChanged();
//
//                } catch (Exception e) {
//                    LogUtils.e(Log.getStackTraceString(e));
//                }
            }
        });
        binding.inputBT.setOnClickListener(v -> {
            // 启动目标 Activity
            Intent intent = new Intent(PlanAddActivity.this, AddActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("LayerSelect", nowSelectInfo);
            intent.putExtra("data", bundle);
            intentActivityResultLauncher.launch(intent);
        });

        planAdapter = new PlanAdapter(this, inventoryItemBeanList);
        binding.planLV.setAdapter(planAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        hxpCabinetDAO = RoomTool.getInstance().hxpCabinetDAO();
        hxpDoorDAO = RoomTool.getInstance().hxpDoorDAO();
        hxpLayerDAO = RoomTool.getInstance().hxpLayerDAO();
        try {
            // 日期
            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();
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
    }

    /**
     * 获取实验室基本信息
     */
    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()) {
                            serverCabinetVoList = hxpCabinetVoList;
                            hxpCabinetDAO.insertAll(serverCabinetVoList);
                            for (int i = 0; i < serverCabinetVoList.size(); i++) {
                                HxpCabinetVo hxpCabinetVo = serverCabinetVoList.get(i);
                                List<HxpCabinetDoorVo> hxpCabinetDoorVoList = hxpCabinetVo.getCabinetDoorVoList();
                                if (null != hxpCabinetDoorVoList && !hxpCabinetDoorVoList.isEmpty()) {
                                    // 录入柜门
                                    hxpDoorDAO.insertAll(hxpCabinetDoorVoList);
                                    for (int j = 0; j < hxpCabinetDoorVoList.size(); j++) {
                                        HxpCabinetDoorVo hxpCabinetDoorVo = hxpCabinetDoorVoList.get(j);
                                        List<CabinetLayerSelect> cabinetLayerSelectList = hxpCabinetDoorVo.getCabinetLayerSelectList();
                                        if (null != cabinetLayerSelectList && !cabinetLayerSelectList.isEmpty()) {
                                            // 录入柜层
                                            hxpLayerDAO.insertAll(cabinetLayerSelectList);
                                        }

                                    }
                                }
                            }
                            lockerAdapter = new LockerAdapter(PlanAddActivity.this, serverCabinetVoList, fragmentCallBack);
                            binding.lockerVP2.setAdapter(lockerAdapter);
                            binding.lockerVP2.setOffscreenPageLimit(1);
                        } else {
                            showToast("未找到化学品柜!");
                        }
                    }

                    @Override
                    public void onFail(Throwable t) {
                        super.onFail(t);
                        showNetError(t);
                        dismissLoading();
                        LogUtils.d(ThreadUtils.isMainThread());
                    }
                });
            }
        }, throwable -> {
            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() {
        @Override
        public void onSelected(CabinetLayerSelect lastSelectInfo) {
            nowSelectInfo = lastSelectInfo;
            hxpLayerDAO.insert(lastSelectInfo);
            // 展示选择层数的待存储列表
            if (binding.inputRL.getVisibility() == View.GONE) {
                binding.inputRL.setVisibility(View.VISIBLE);
                binding.addIndexTV.setVisibility(View.GONE);
            }
            CabinetLayerSelect cabinetLayerSelect = hxpLayerDAO.getById(lastSelectInfo.getCabinetId(), lastSelectInfo.getDoorId(), lastSelectInfo.getLayer());
            if (null == cabinetLayerSelect) {
                inventoryItemBeanList.clear();
                if (binding.scanLL.getVisibility() != View.VISIBLE) {
                    binding.scanLL.setVisibility(View.VISIBLE);
                    binding.planLV.setVisibility(View.GONE);
                }
            } else {
                if (binding.scanLL.getVisibility() == View.VISIBLE) {
                    binding.scanLL.setVisibility(View.GONE);
                    binding.planLV.setVisibility(View.VISIBLE);
                }
                inventoryItemBeanList.addAll(cabinetLayerSelect.getInventoryItemBeanList());
            }
            planAdapter.notifyDataSetChanged();
        }

    };

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


}