package xn.hxp.ui.plan.add;

import android.app.DatePickerDialog;
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.viewbinding.ViewBinding;

import com.blankj.utilcode.util.ClickUtils;
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.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.kongzue.dialogx.dialogs.PopTip;
import com.rc.core.ui.activity.BaseActivity;
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 com.rc.httpcore.client.HttpTool;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import io.reactivex.rxjava3.functions.Consumer;
import xn.hxp.app.ChemicalApp;
import xn.hxp.databinding.ActivityAddBinding;
import xn.hxp.ui.plan.change.ChangeCabinetActivity;
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.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.HxpLayerDAO;
import xn.hxp.weidith.ChemicalTypeDialog;


public class AddActivity extends BaseActivity {
    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;

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

        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);
        binding.sizeET.setText("1");
        binding.sizeET.setEnabled(false);
    }

    @Override
    protected void cdFinish() {
        finish();
    }

    @Override
    protected void cdTime(int cd) {

    }

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

    @Override
    protected void onInit() {
        // 化学品搜索
        binding.chemicalSearchBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View 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(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View 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(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                new ChemicalTypeDialog(AddActivity.this, chemicalTypeList, data -> {
                    binding.chemicalCategoryTV.setText(data.getLabel());
                    binding.chemicalCategoryTV.setTag(data.getValue());
                }).show();
            }
        });
        // 归属人搜索
        binding.belongBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View 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(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View 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 ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                addActivityHelp.save(false);
            }
        });
        //  称重存储
        binding.weighSaveBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                addActivityHelp.save(true);
            }
        });
        // ml选择
        binding.chemicalSpecMlRB.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                String ml = binding.chemicalSpecMlRB.getText().toString();
                hxpChemicalVo.setSpecUnit(ml);
                binding.netWtTV.setText(ml);
            }
        });
        // 选择
        binding.chemicalSpecGRB.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                String g = binding.chemicalSpecGRB.getText().toString();
                hxpChemicalVo.setSpecUnit(g);
                binding.netWtTV.setText(g);
            }
        });
        // 管控级别
        binding.uncontrolledRB.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                hxpChemicalVo.setChemicalLevel(2);
            }
        });
        binding.controlledRB.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                hxpChemicalVo.setChemicalLevel(1);
            }
        });
        // 重置
        binding.resetBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                addActivityHelp.reset();
            }
        });
        // 归属人选择
        binding.belongRB.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                binding.belongLL.setVisibility(View.VISIBLE);
                binding.topicLL.setVisibility(View.GONE);
                hxpChemicalVo.setBelongType(2);
            }
        });
        // 课题组选择
        binding.topicRB.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                binding.topicLL.setVisibility(View.VISIBLE);
                binding.belongLL.setVisibility(View.GONE);
                hxpChemicalVo.setBelongType(1);
            }
        });
        // 过期日期
        binding.chemicalExpiresTV.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(AddActivity.this);
                datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
                datePickerDialog.setOnDateSetListener((view, year, month, dayOfMonth) -> {
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(year, month, dayOfMonth, 23, 59, 59);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                    String date = simpleDateFormat.format(calendar.getTime());
                    hxpChemicalVo.setExpireTime(date);
                    binding.chemicalExpiresTV.setText(date);
                    datePickerDialog.dismiss();
                });
                datePickerDialog.show();
            }
        });

        // 位置选择
        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.insert(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 ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                intentActivityResultLauncher.launch(new Intent(AddActivity.this, ChangeCabinetActivity.class));
            }
        });

        // 返回
        binding.tvReturn.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                finish();
            }
        });

        showLoading("请稍等...");
        // 化学品类别列表获取
        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());
        }

        List<String> msclist = new ArrayList<>();
        List<BleDevice> bleDeviceList = BleManager.getInstance().getAllConnectedDevice();
        LogUtils.d(bleDeviceList);
        if (null != bleDeviceList) {
            for (int i = 0; i < bleDeviceList.size(); i++) {
                BleDevice bleDevice = bleDeviceList.get(i);
                msclist.add(bleDevice.getMac());
            }
        }
        LogUtils.d(msclist);
    }

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