package xn.hxp.ui.plan;

import android.content.Intent;
import android.database.DataSetObserver;
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.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ClickUtils;
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.kongzue.dialogx.dialogs.PopTip;
import com.rc.core.ui.activity.BaseActivity;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.ChemicalInfoBean;
import com.rc.httpcore.client.HttpTool;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import xn.hxp.app.ChemicalApp;
import xn.hxp.databinding.ActivityPlanAddBinding;
import xn.hxp.receiver.PortScanHelper;
import xn.hxp.ui.plan.add.AddActivity;
import xn.hxp.ui.plan.locker.LockerAdapter;
import xn.hxp.ui.plan.room.RoomTool;
import xn.hxp.ui.plan.room.bean.input_add.InventoryItemBean;
import xn.hxp.ui.plan.room.bean.locker.CabinetLayerSelect;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetDoorVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetLockVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetVo;
import xn.hxp.ui.plan.room.dao.HxpCabinetDAO;
import xn.hxp.ui.plan.room.dao.HxpDoorDAO;
import xn.hxp.ui.plan.room.dao.HxpInventoryDAO;
import xn.hxp.ui.plan.room.dao.HxpLabDirectorDAO;
import xn.hxp.ui.plan.room.dao.HxpLabSafeDAO;
import xn.hxp.ui.plan.room.dao.HxpLayerDAO;
import xn.hxp.ui.plan.unlock.UnlockActivity;

/**
 * 待录入页面
 */
public class PlanAddActivity extends BaseActivity {

    protected ActivityPlanAddBinding binding;
    // 柜子fragmentAdapter
    protected LockerAdapter lockerAdapter;
    // 实验室基本信息
    protected ChemicalInfoBean chemicalInfo;
    // 服务端实验室所有柜子信息
    protected List<HxpCabinetVo> cabinetVoList;
    // 当前展示的待存储列表
    protected List<InventoryItemBean> inventoryItemBeanList = new LinkedList<>();
    // 当前展示的待存储列表适配器
    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;


    @Override
    protected ViewBinding setViewBinding() {
        return binding = ActivityPlanAddBinding.inflate(getLayoutInflater());
    }


    @Override
    protected void onInit() {
        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(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                binding.lockerVP2.setCurrentItem(binding.lockerVP2.getCurrentItem() + 1, true);
            }
        });
        binding.lastBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                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(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View 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 ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                binding.subAdd.setEnabled(false);
                List<InventoryItemBean> inventoryItemBeans = hxpInventoryDAO.getAll();
                if (null == inventoryItemBeans || inventoryItemBeans.isEmpty()) {
                    PopTip.show("请录入化学品!");
                    binding.subAdd.setEnabled(true);
                    return;
                }
                showLoading("加载中...");
                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();
                    }

                    @Override
                    public void onFail(Throwable t) {
                        super.onFail(t);
                        dismissLoading();
                        PopTip.show(t.getMessage());
                        binding.subAdd.setEnabled(true);
                    }
                });
            }
        });
        planAddActivityHelp.updateInventoryUi();


        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(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                try {
                    HttpTool.logout();
                } catch (IOException e) {
                    LogUtils.e(Log.getStackTraceString(e));
                }
            }
        });
        binding.tvReturn.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                finish();
            }
        });
    }


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

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 消费掉外置RFID读卡器的输入，此页面不在白名单中
        if (xn.hxp.receiver.UhfRfidManager.INSTANCE.isEnabled(this) && xn.hxp.receiver.UhfRfidManager.INSTANCE.isUhfRfidEvent(this, event)) {
            return true;
        }
        // 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 cdFinish() {
        finish();
    }

    @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) {
                int size = 0;
                for (int i = 0; i < inventoryItemBeanList.size(); i++) {
                    InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(i);
                    size = size + inventoryItemBean.getSize();
                }
                binding.sizeTV.setText("总数:" + size);
            }
        }
    };

}