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

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
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 com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.chemical.ChemicalApp;
import com.example.chemical.databinding.ActivityAddBinding;
import com.example.chemical.ui.SplashActivity;
import com.example.chemical.ui.common.BaseCountDownActivity;
import com.example.chemical.ui.plan.change.ChangeCabinetActivity;
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.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.HxpLayerDAO;
import com.example.chemical.utils.UiManager;
import com.example.chemical.weidith.ChemicalTypeDialog;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.BelongingPersonBean;
import com.rc.httpcore.bean.ChemicalTypeBean;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.bean.HxpControlConfig;
import com.rc.httpcore.bean.TopicDataBean;
import com.rc.httpcore.client.ApiRepository;

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

public class AddActivity extends BaseCountDownActivity<ActivityAddBinding> {
    protected ActivityAddBinding binding;

    // 化学品信息
    protected HxpChemicalVo hxpChemicalVo = new HxpChemicalVo();
    // 化学品清单item
    protected InventoryItemBean inventoryItemBean;
    // 课题组
    protected TopicDataBean topicDataBean;
    // 化学品类别
    protected List<ChemicalTypeBean> chemicalTypeList;
    // 归属人
    protected BelongingPersonBean belongingPerson;
    // 化学品基础参数配置
    protected HxpControlConfig hxpControlConfig;

    private AddActivityHelp addActivityHelp;

    private HxpCabinetDAO hxpCabinetDAO;
    private HxpDoorDAO hxpDoorDAO;
    private HxpLayerDAO hxpLayerDAO;

    // 当前选中信息
    protected CabinetLayerSelect cabinetLayerSelect;
    // 当前选中的柜子
    protected HxpCabinetVo sqlHxpCabinetVo;
    // 当前选中的柜门
    protected HxpCabinetDoorVo sqlHxpCabinetDoorVo;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    protected HxpInventoryDAO hxpInventoryDAO;

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

    @Override
    protected void initViews(@Nullable Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        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(AddActivity.this, SplashActivity.class);
                return null;
            }));
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        // 化学品搜索
        binding.chemicalSearchBT.setOnClickListener(v -> {
            Editable chemicalSearchETText = binding.chemicalSearchET.getText();
            if (null == chemicalSearchETText || TextUtils.isEmpty(chemicalSearchETText)) {
                binding.chemicalSearchET.setError("请输入化学品名称");
                return;
            }
            addActivityHelp.hxpSearch(chemicalSearchETText);
        });
        binding.chemicalSearchET.setOnEditorActionListener((v, actionId, event) -> {
            binding.chemicalSearchBT.performClick();
            return true;
        });
        //CAS搜索
        binding.casBT.setOnClickListener(v -> {
            Editable casETText = binding.casET.getText();
            if (null == casETText || TextUtils.isEmpty(casETText)) {
                binding.casET.setError("请输入CAS码");
                return;
            }
            addActivityHelp.hxpSearch(casETText);
        });
        binding.casET.setOnEditorActionListener((v, actionId, event) -> {
            binding.casBT.performClick();
            return true;
        });
        // 类别选择
        binding.chemicalCategoryTV.setOnClickListener(v -> {
            new ChemicalTypeDialog(AddActivity.this, chemicalTypeList, data -> {
                binding.chemicalCategoryTV.setText(data.getLabel());
                binding.chemicalCategoryTV.setTag(data.getValue());
            }).show();
        });
        // 归属人搜索
        binding.belongBT.setOnClickListener(v -> {
            Editable belongETText = binding.belongET.getText();
            if (null == belongETText || TextUtils.isEmpty(belongETText)) {
                binding.belongET.setError("请输入姓名或工号");
                return;
            }
            addActivityHelp.belongSearch(belongETText);
        });
        binding.belongET.setOnEditorActionListener((v, actionId, event) -> {
            binding.belongBT.performClick();
            return true;
        });
        // 课题组搜索
        binding.topicBT.setOnClickListener(v -> {
            if (null == belongingPerson) {
                binding.topicET.setText("请先选择归属人");
                return;
            }
            addActivityHelp.topicSearch(belongingPerson.getUserId());
        });
        binding.topicET.setOnEditorActionListener((v, actionId, event) -> {
            binding.topicBT.performClick();
            return true;
        });
        //  存储
        binding.saveBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        //  称重存储
        binding.weighSaveBT.setOnClickListener(v -> addActivityHelp.weighSave());
        // ml选择
        binding.chemicalSpecMlRB.setOnClickListener(v -> {
            String ml = binding.chemicalSpecMlRB.getText().toString();
            hxpChemicalVo.setSpecUnit(ml);
            binding.netWtTV.setText(ml);
        });
        // g选择
        binding.chemicalSpecGRB.setOnClickListener(v -> {
            String g = binding.chemicalSpecGRB.getText().toString();
            hxpChemicalVo.setSpecUnit(g);
            binding.netWtTV.setText(g);
        });
        // 管控级别
        binding.uncontrolledRB.setOnClickListener(v -> hxpChemicalVo.setChemicalLevel(2));
        binding.controlledRB.setOnClickListener(v -> hxpChemicalVo.setChemicalLevel(1));


        // 位置选择
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    Intent resultData = result.getData();
                    if (null != resultData && resultData.hasExtra("data")) {
                        Bundle bundle = resultData.getBundleExtra("data");
                        if (null != bundle) {
                            cabinetLayerSelect = (CabinetLayerSelect) bundle.getSerializable("Change");
                        }
                    }
                }
            }
        });
        binding.changeCabinetBT.setOnClickListener(v -> intentActivityResultLauncher.launch(new Intent(AddActivity.this, ChangeCabinetActivity.class)));
    }

    @Override
    protected void initData() {
        super.initData();
        hxpCabinetDAO = RoomTool.getInstance().hxpCabinetDAO();
        hxpDoorDAO = RoomTool.getInstance().hxpDoorDAO();
        hxpLayerDAO = RoomTool.getInstance().hxpLayerDAO();
        hxpInventoryDAO = RoomTool.getInstance().hxpInventoryDAO();
        CabinetLayerSelect cabinetLayerSelect = hxpLayerDAO.getChanged();
        inventoryItemBean = new InventoryItemBean(cabinetLayerSelect.getCabinetId(), cabinetLayerSelect.getDoorId(), cabinetLayerSelect.getLayer());
        this.cabinetLayerSelect = hxpLayerDAO.getById(cabinetLayerSelect.getCabinetId(), cabinetLayerSelect.getDoorId(), cabinetLayerSelect.getLayer());
        int layer = this.cabinetLayerSelect.getLayer();
        sqlHxpCabinetVo = hxpCabinetDAO.getById(cabinetLayerSelect.getCabinetId());
        String cabinetName = sqlHxpCabinetVo.getCabinetName();
        cabinetName = TextUtils.isEmpty(cabinetName) ? "" : cabinetName;
        sqlHxpCabinetDoorVo = hxpDoorDAO.getById(cabinetLayerSelect.getDoorId());
        String doorName = sqlHxpCabinetDoorVo.getDoorName();
        doorName = TextUtils.isEmpty(doorName) ? "" : doorName;
        binding.cabinetLayerSelectTV.setText(cabinetName + "-" + doorName + "-" + layer + "层");
        binding.cabinetLayerSelectTV.setSelected(true);
        // 化学品类别列表获取
        addDisposable(ApiRepository.INSTANCE.getOptions("chemicals_category").subscribe(chemicalTypeBeans -> chemicalTypeList = chemicalTypeBeans, throwable -> {
            LogUtils.e(Log.getStackTraceString(throwable));
            ToastUtils.showLong("化学品类别获取失败!");
        }));

        addActivityHelp = new AddActivityHelp(AddActivity.this);
    }

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