package com.example.chemical.ui.plan.save_list;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.GsonUtils;
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.ActivitySaveListBinding;
import com.example.chemical.ui.MainActivity;
import com.example.chemical.ui.SplashActivity;
import com.example.chemical.ui.common.BaseCountDownActivity;
import com.example.chemical.ui.plan.PlanAddActivity;
import com.example.chemical.ui.plan.PlanAddData;
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.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.utils.UiManager;
import com.kongzue.dialogx.dialogs.PopTip;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.UserValidationBean;
import com.rc.httpcore.client.ApiRepository;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.disposables.Disposable;

public class SaveListActivity extends BaseCountDownActivity<ActivitySaveListBinding> {

    protected ActivitySaveListBinding binding;
    private SaveListAdapter saveListAdapter;
    private Map<Long, List<SaveListBean>> saveListBeanMap = new TreeMap<>();
    protected HxpInventoryDAO inventoryDAO;
    protected HxpCabinetDAO cabinetDAO;
    protected HxpDoorDAO doorDAO;

    protected PlanAddData planAddData;
    protected UserValidationBean userValidation1;
    protected UserValidationBean userValidation2;

    protected Disposable unlockDisposable, unlockStatusDisposable;
    protected CountDownTimer unlockStatusCDTimer;

    @NonNull
    @Override
    protected ActivitySaveListBinding createViewBinding() {
        ChemicalApp.confs.setBackTime(10);
        binding = ActivitySaveListBinding.inflate(getLayoutInflater());
        return binding;
    }

    @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);
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }

        // 退出
        binding.tvOutLogin.setOnClickListener(v -> callLogoutApi(aBoolean -> {
            ChemicalApp.userData = null;
            ChemicalApp.subjectId = null;
            UiManager.INSTANCE.switcherCashier(SaveListActivity.this, SplashActivity.class);
        }));

        inventoryDAO = RoomTool.getInstance().hxpInventoryDAO();
        cabinetDAO = RoomTool.getInstance().hxpCabinetDAO();
        doorDAO = RoomTool.getInstance().hxpDoorDAO();
        List<InventoryItemBean> inventoryItemBeanList = inventoryDAO.getAll();

        for (int i = 0; i < inventoryItemBeanList.size(); i++) {
            InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(i);
            SaveListBean saveListBean = new SaveListBean();
            HxpCabinetVo cabinetVo = cabinetDAO.getById(inventoryItemBean.getCabinetId());
            saveListBean.setCabinetId(cabinetVo.getCabinetId());
            saveListBean.setCabinetName(cabinetVo.getCabinetName());
            HxpCabinetDoorVo doorVo = doorDAO.getById(inventoryItemBean.getDoorId());
            saveListBean.setDoorId(doorVo.getDoorId());
            saveListBean.setDoorName(doorVo.getDoorName());
            saveListBean.setInventoryItemBean(inventoryItemBean);

            List<SaveListBean> saveListBeanList = saveListBeanMap.get(doorVo.getDoorId());
            if (null == saveListBeanList) {
                saveListBeanList = new ArrayList<>();
                saveListBean.setTitle(true);
            } else {
                saveListBean.setTitle(false);
            }
            List<HxpCabinetLockVo> hxpCabinetLockVoList = doorVo.getCabinetLockVoList();
            saveListBean.setUnlock(null != hxpCabinetLockVoList && !hxpCabinetLockVoList.isEmpty());

            saveListBeanList.add(saveListBean);
            saveListBeanMap.put(doorVo.getDoorId(), saveListBeanList);
        }

        saveListAdapter = new SaveListAdapter(this, saveListBeanMap);
        binding.saveLV.setAdapter(saveListAdapter);
        List<String> logs = splitStringIntoChunks(GsonUtils.toJson(saveListBeanMap), 500);
        for (int i = 0; i < logs.size(); i++) {
            Log.d("Jacye", logs.get(i));
        }

        Intent getIntent = getIntent();
        if (null != getIntent && getIntent.hasExtra("data")) {
            planAddData = GsonUtils.fromJson(getIntent.getStringExtra("data"), PlanAddData.class);
            userValidation1 = GsonUtils.fromJson(getIntent.getStringExtra("userValidation1"), UserValidationBean.class);
            userValidation2 = GsonUtils.fromJson(getIntent.getStringExtra("userValidation2"), UserValidationBean.class);
        }

        binding.exit.setOnClickListener(v -> UiManager.INSTANCE.switcher(SaveListActivity.this, MainActivity.class));

        setCTime(10);
    }

    public List<String> splitStringIntoChunks(String inputString, int chunkSize) {
        if (chunkSize <= 0) {
            throw new IllegalArgumentException("Chunk size must be greater than 0");
        }

        List<String> result = new ArrayList<>();
        int startIndex = 0;

        while (startIndex < inputString.length()) {
            int endIndex = Math.min(startIndex + chunkSize, inputString.length());
            String chunk = inputString.substring(startIndex, endIndex);
            result.add(chunk);
            startIndex = endIndex;
        }

        return result;
    }

    @Override
    protected void cdTime(int cd) {
        binding.exit.setText("结束" + cd + "s");
    }
}