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.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.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.kongzue.dialogx.dialogs.PopTip;
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;

import io.reactivex.functions.Consumer;

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;

    protected HxpCabinetDAO hxpCabinetDAO;
    protected HxpDoorDAO hxpDoorDAO;
    protected HxpLayerDAO hxpLayerDAO;

    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);
        // 化学品搜索
        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(v -> addActivityHelp.save(false));
        //  称重存储
        binding.weighSaveBT.setOnClickListener(v -> addActivityHelp.save(true));
        // ml选择
        binding.chemicalSpecMlRB.setOnClickListener(v -> {
            String ml = binding.chemicalSpecMlRB.getText().toString();
            hxpChemicalVo.setSpecUnit(ml);
            binding.netWtTV.setText(ml);
        });
        // 选择
        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));
        // 重置
        binding.resetBT.setOnClickListener(v -> addActivityHelp.reset());
        // 归属人选择
        binding.belongRB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.belongLL.setVisibility(View.VISIBLE);
                binding.topicLL.setVisibility(View.GONE);
                hxpChemicalVo.setBelongType(2);
            }
        });
        // 课题组选择
        binding.topicRB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.topicLL.setVisibility(View.VISIBLE);
                binding.belongLL.setVisibility(View.GONE);
                hxpChemicalVo.setBelongType(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 = (CabinetLayerSelect) bundle.getSerializable("Change");
                            if (null != cabinetLayerSelect) {
                                hxpLayerDAO.change(cabinetLayerSelect.getCabinetId(), cabinetLayerSelect.getDoorId(), cabinetLayerSelect.getLayer());
                                inventoryItemBean.setCabinetId(cabinetLayerSelect.getCabinetId());
                                inventoryItemBean.setDoorId(cabinetLayerSelect.getDoorId());
                                inventoryItemBean.setLayer(cabinetLayerSelect.getLayer());

                                HxpCabinetVo hxpCabinetVo = hxpCabinetDAO.getById(cabinetLayerSelect.getCabinetId());
                                String cabinetName = hxpCabinetVo.getCabinetName();
                                cabinetName = TextUtils.isEmpty(cabinetName) ? "" : cabinetName;
                                HxpCabinetDoorVo hxpCabinetDoorVo = hxpDoorDAO.getById(cabinetLayerSelect.getDoorId());
                                String doorName = hxpCabinetDoorVo.getDoorName();
                                doorName = TextUtils.isEmpty(doorName) ? "" : doorName;
                                int layer = cabinetLayerSelect.getLayer();
                                binding.cabinetLayerSelectTV.setText(cabinetName + "-" + doorName + "-" + layer + "层");
                                binding.cabinetLayerSelectTV.setSelected(true);
                            }
                        }
                    }
                }
            }
        });
        binding.changeCabinetBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentActivityResultLauncher.launch(new Intent(AddActivity.this, ChangeCabinetActivity.class));
            }
        });

        // 返回
        binding.tvReturn.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        super.initData();
        showLoading("请稍等...", false);
        // 化学品类别列表获取
        addDisposable(ApiRepository.INSTANCE.getOptions("chemicals_category").subscribe(new Consumer<List<ChemicalTypeBean>>() {
            @Override
            public void accept(List<ChemicalTypeBean> chemicalTypeBeans) throws Exception {
                initUi();
                chemicalTypeList = chemicalTypeBeans;
                Intent getIntent = getIntent();
                if (null != getIntent && getIntent.hasExtra("data")) {
                    String data = getIntent.getStringExtra("data");
                    if ("qr".equals(data) && getIntent.hasExtra("Chemical")) {
                        String json = getIntent.getStringExtra("Chemical");
                        hxpChemicalVo = GsonUtils.fromJson(json, HxpChemicalVo.class);
                        addActivityHelp.qrInit();
                    }
                }
                dismissLoading();
            }
        }, throwable -> {
            dismissLoading();
            LogUtils.e(Log.getStackTraceString(throwable));
            PopTip.show("化学品类别获取失败!");
        }));
        addActivityHelp = new AddActivityHelp(AddActivity.this);
        // 默认归属人是登录人信息
        if (ChemicalApp.userData != null) {
            belongingPerson = new BelongingPersonBean(ChemicalApp.userData.getUserId(), ChemicalApp.userData.getUserName(), ChemicalApp.userData.getAccount(), "", "");
            String userName = belongingPerson.getUserName();
            userName = TextUtils.isEmpty(userName) ? "" : userName;
            String account = belongingPerson.getAccount();
            account = TextUtils.isEmpty(account) ? "" : account;
            binding.belongET.setText(userName + "-" + account);
            binding.belongET.setTag(belongingPerson.getUserId());
        }
    }

    private void initUi() {
        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(AddActivity.this, SplashActivity.class);
        }));

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

        HxpCabinetVo hxpCabinetVo = hxpCabinetDAO.getById(cabinetLayerSelect.getCabinetId());
        String cabinetName = hxpCabinetVo.getCabinetName();
        cabinetName = TextUtils.isEmpty(cabinetName) ? "" : cabinetName;

        HxpCabinetDoorVo hxpCabinetDoorVo = hxpDoorDAO.getById(cabinetLayerSelect.getDoorId());
        String doorName = hxpCabinetDoorVo.getDoorName();
        doorName = TextUtils.isEmpty(doorName) ? "" : doorName;
        int layer = cabinetLayerSelect.getLayer();
        binding.cabinetLayerSelectTV.setText(cabinetName + "-" + doorName + "-" + layer + "层");
        binding.cabinetLayerSelectTV.setSelected(true);
    }

    @Override
    protected void cdTime(int cd) {

    }

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