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.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.LogUtils;
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.dao.HxpCabinetDAO;
import com.example.chemical.ui.plan.room.dao.HxpDoorDAO;
import com.example.chemical.ui.plan.room.dao.HxpInventoryDAO;
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.HxpCabinetVo;
import com.example.chemical.ui.plan.room.bean.locker.CabinetLayerSelect;

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

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

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

    protected ActivityPlanAddBinding binding;
    // 柜子fragmentAdapter
    protected LockerAdapter lockerAdapter;
    // 二维码/条形码扫描工具
    private ScanKeyEventHelper scanKeyEventHelper;
    // 实验室基本信息
    protected ChemicalInfoBean chemicalInfo;
    // 服务端实验室所有柜子信息
    protected List<HxpCabinetVo> cabinetVoList;
    // 当前展示的待存储列表
    protected List<InventoryItemBean> inventoryItemBeanList = new ArrayList<>();
    // 当前展示的待存储列表适配器
    protected PlanAdapter planAdapter;
    // 柜子DAO
    protected HxpCabinetDAO hxpCabinetDAO;
    // 柜门DAO
    protected HxpDoorDAO hxpDoorDAO;
    // 柜层DAO
    protected HxpLayerDAO hxpLayerDAO;
    // 待入库清单item
    protected HxpInventoryDAO hxpInventoryDAO;
    // 柜子fragments
    protected List<Fragment> cabinetFragmentList = new LinkedList<>();

    private PlanAddActivityHelp planAddActivityHelp;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

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

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        hxpCabinetDAO = RoomTool.getInstance().hxpCabinetDAO();
        hxpDoorDAO = RoomTool.getInstance().hxpDoorDAO();
        hxpLayerDAO = RoomTool.getInstance().hxpLayerDAO();
        hxpInventoryDAO = RoomTool.getInstance().hxpInventoryDAO();
        planAddActivityHelp = new PlanAddActivityHelp(this);
        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) {
                if (binding.inputRL.getVisibility() == View.GONE) {
                    showToast("请先选择化学品柜层!");
                    return null;
                }
                Log.d("结果", s);
                return null;
            }
        });

        // 待存储
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    planAddActivityHelp.updateInventoryUi();
                }
            }

        });

        // 手动录入化学品
        binding.inputBT.setOnClickListener(v -> intentActivityResultLauncher.launch(new Intent(PlanAddActivity.this, AddActivity.class)));

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

        LogUtils.json(hxpInventoryDAO.getAll());
    }

    @Override
    protected void initData() {
        super.initData();

        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() {
        planAddActivityHelp.getLabInfo();
    }

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


    protected FragmentCallBack fragmentCallBack = new FragmentCallBack() {
        @Override
        public void onSelected(CabinetLayerSelect lastSelectInfo) {
            planAddActivityHelp.selectCabinetLayer(lastSelectInfo);
        }
    };

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


}