package com.example.chemical.ui.plan;

import android.content.Intent;
import android.database.DataSetObserver;
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.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.PortScanHelper;
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.input_add.InventoryItemBean;
import com.example.chemical.ui.plan.room.bean.locker.CabinetLayerSelect;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetDoorVo;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetLockVo;
import com.example.chemical.ui.plan.room.bean.locker.HxpCabinetVo;
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.HxpLabDirectorDAO;
import com.example.chemical.ui.plan.room.dao.HxpLabSafeDAO;
import com.example.chemical.ui.plan.room.dao.HxpLayerDAO;
import com.example.chemical.ui.plan.unlock.UnlockActivity;
import com.example.chemical.utils.UiManager;
import com.kongzue.dialogx.dialogs.PopTip;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.ChemicalInfoBean;

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

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

    protected ActivityPlanAddBinding binding;
    // 柜子fragmentAdapter
    protected LockerAdapter lockerAdapter;
    // 实验室基本信息
    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;
    // 实验室负责人DAO
    protected HxpLabDirectorDAO labDirectorDAO;
    // 实验室安全员DAO
    protected HxpLabSafeDAO labSafeDAO;
    // 待入库清单item
    protected HxpInventoryDAO hxpInventoryDAO;
    // 柜子fragments
    protected List<Fragment> cabinetFragmentList = new LinkedList<>();

    private PlanAddActivityHelp planAddActivityHelp;

    protected ActivityResultLauncher<Intent> intentActivityResultLauncher;
    protected PortScanHelper portScanHelper;

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

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        hxpCabinetDAO = RoomTool.getInstance().hxpCabinetDAO();
        hxpCabinetDAO.deleteAll();
        hxpDoorDAO = RoomTool.getInstance().hxpDoorDAO();
        hxpDoorDAO.deleteAll();
        hxpLayerDAO = RoomTool.getInstance().hxpLayerDAO();
        hxpLayerDAO.deleteAll();
        hxpInventoryDAO = RoomTool.getInstance().hxpInventoryDAO();
        hxpInventoryDAO.deleteAll();
        labDirectorDAO = RoomTool.getInstance().hxpLabDirectorDAO();
        labDirectorDAO.deleteAll();
        labSafeDAO = RoomTool.getInstance().hxpLabSafeDAO();
        labSafeDAO.deleteAll();

        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));

        // 待存储
        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);
        planAdapter.registerDataSetObserver(dataSetObserver);

        // 确认入库
        binding.subAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<InventoryItemBean> inventoryItemBeans = hxpInventoryDAO.getAll();
                if (null == inventoryItemBeans || inventoryItemBeans.isEmpty()) {
                    PopTip.show("请录入化学品!");
                    return;
                }
                showLoading("加载中...", false);
                ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<PlanAddData>() {
                    @Override
                    public PlanAddData doInBackground() throws Throwable {
                        List<InventoryItemBean> inventoryItemBeanList = hxpInventoryDAO.getAll();
                        List<HxpCabinetVo> cabinetList = hxpCabinetDAO.getAll();
                        List<HxpCabinetDoorVo> doorList = hxpDoorDAO.getAll();
                        // 删除清单外的柜门
                        for (int i = 0; i < doorList.size(); i++) {
                            HxpCabinetDoorVo doorVo = doorList.get(i);
                            boolean hasDoorId = false;
                            for (int j = 0; j < inventoryItemBeanList.size(); j++) {
                                InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(j);
                                if (inventoryItemBean.getDoorId() == doorVo.getDoorId()) {
                                    hasDoorId = true;
                                    break;
                                }
                            }
                            if (!hasDoorId) {
                                doorList.remove(i);
                                i--;
                            }

                        }
                        // 删除没有智能锁的柜门
                        Iterator<HxpCabinetDoorVo> doorVoIterator = doorList.iterator();
                        while (doorVoIterator.hasNext()) {
                            HxpCabinetDoorVo doorVo = doorVoIterator.next();
                            List<HxpCabinetLockVo> hxpCabinetLockVoList = doorVo.getCabinetLockVoList();
                            if (null == hxpCabinetLockVoList || hxpCabinetLockVoList.isEmpty()) {
                                doorVoIterator.remove();
                            } else {
                                HxpCabinetLockVo cabinetLockVo = hxpCabinetLockVoList.get(0);
                                if (2 != cabinetLockVo.getUnlockingMethod()) {
                                    doorVoIterator.remove();
                                }
                            }
                        }
                        // 删除不需要开门的柜子
                        Iterator<HxpCabinetVo> cabinetVoIterator = cabinetList.iterator();
                        while (cabinetVoIterator.hasNext()) {
                            HxpCabinetVo cabinetVo = cabinetVoIterator.next();
                            boolean hasDoor = false;
                            for (int i = 0; i < doorList.size(); i++) {
                                HxpCabinetDoorVo doorVo = doorList.get(i);
                                if (cabinetVo.getCabinetId() == doorVo.getCabinetId()) {
                                    hasDoor = true;
                                    break;
                                }
                            }
                            if (!hasDoor) {
                                cabinetVoIterator.remove();
                            }
                        }
                        PlanAddData planAddData = new PlanAddData();
                        planAddData.setCabinetList(cabinetList);
                        planAddData.setDoorList(doorList);
                        return planAddData;
                    }

                    @Override
                    public void onSuccess(PlanAddData planAddData) {
                        dismissLoading();
                        List<HxpCabinetVo> cabinetList = planAddData.getCabinetList();
                        List<HxpCabinetDoorVo> doorList = planAddData.getDoorList();
                        // 不需要开门
                        if (null == doorList || cabinetList == null || cabinetList.isEmpty() || doorList.isEmpty()) {
                            planAddActivityHelp.save();
                            return;
                        }
                        String json = GsonUtils.toJson(planAddData);
                        Intent intent = new Intent(PlanAddActivity.this, UnlockActivity.class);
                        intent.putExtra("data", json);
                        startActivity(intent);
                        finish();
                    }
                });
            }
        });
        planAddActivityHelp.updateInventoryUi();
    }

    @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);

            //获取实验室基本信息
            getLabInfo();
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        // 退出
        binding.tvOutLogin.setOnClickListener(v -> callLogoutApi(aBoolean -> {
            ChemicalApp.userData = null;
            ChemicalApp.subjectId = null;
            UiManager.INSTANCE.switcherCashier(PlanAddActivity.this, SplashActivity.class);
        }));
        binding.tvReturn.setOnClickListener(v -> finish());
    }


    /**
     * 获取实验室基本信息
     */
    private void getLabInfo() {
        planAddActivityHelp.getLabInfo();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // https://labcontrol.nwafu.edu.cn/api/?code=5020641&type=9
        if (null != portScanHelper) {
            portScanHelper.dispatchKeyEvent(event);
        }
        return super.dispatchKeyEvent(event);
    }


    /**
     * 柜层选择监听
     */
    protected FragmentCallBack fragmentCallBack = new FragmentCallBack() {
        @Override
        public void onSelected(CabinetLayerSelect lastSelectInfo) {
            if (binding.addIndexTV.getVisibility() == View.VISIBLE) {
                binding.addIndexTV.setVisibility(View.GONE);
            }
            planAddActivityHelp.startScanEventListener();
            planAddActivityHelp.selectCabinetLayer(lastSelectInfo);
        }
    };

    @Override
    protected void cdTime(int cd) {
        binding.tvReturn.setText("返回" + cd + "s");
    }

    @Override
    protected void onDestroy() {
        fragmentCallBack = null;
        super.onDestroy();
        planAdapter.unregisterDataSetObserver(dataSetObserver);
        intentActivityResultLauncher.unregister();
        if (null != portScanHelper) {
            portScanHelper = null;
        }
    }

    DataSetObserver dataSetObserver = new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            if (null == inventoryItemBeanList || inventoryItemBeanList.isEmpty()) {
                planAddActivityHelp.updateInventoryUi();
            }
            int size = 0;
            for (int i = 0; i < inventoryItemBeanList.size(); i++) {
                InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(i);
                size = size + inventoryItemBean.getSize();
            }
            binding.sizeTV.setText("总数:" + size);
        }
    };

}