package com.sxyz.rfid.ui.review.offline;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sxyz.rfid.R;
import com.sxyz.rfid.base.BaseActivity;
import com.sxyz.rfid.databinding.ActivityReviewOfflineBinding;
import com.sxyz.rfid.greendao.GreenDaoManager;
import com.sxyz.rfid.greendao.model.WmsInventoryTask;
import com.sxyz.rfid.greendao.model.WmsInventoryTaskDetail;
import com.sxyz.rfid.ui.review.offline.adapter.ReviewOfflineAdapter;
import com.sxyz.rfid.utils.StringUtil;
import com.sxyz.rfid.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import sql.com.yz.db.DaoSession;
import sql.com.yz.db.WmsInventoryTaskDao;
import sql.com.yz.db.WmsInventoryTaskDetailDao;

/**
 * 主要功能:  离线执行盘点列表
 *
 * @Description: 离线执行盘点列表
 * @Project: rfid-app
 * @Package: com.sxyz.rfid.ui.review.offline
 * @author: chunyuanwu
 * @date: 2026年01月15日 13:54
 * @version: 1.0.0
 */
public class ReviewOfflineActivity extends BaseActivity<ActivityReviewOfflineBinding> {
    private DaoSession daoSession;
    private List<WmsInventoryTask> mList = new ArrayList<>();
    private ReviewOfflineAdapter mAdapter;

    @Override
    public void initParms(Bundle mBundle) {

    }

    @Override
    protected ActivityReviewOfflineBinding getViewBinding() {
        return ActivityReviewOfflineBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        initToolBar("执行盘点列表");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter = new ReviewOfflineAdapter(R.layout.item_offline_review, mList);
        mBinding.recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void setListener() {
        mBinding.swipeRefreshLayout.setOnRefreshListener(this::getData);
        mBinding.searchEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mBinding.ivSearch.setVisibility(VISIBLE);
                } else {
                    mBinding.ivSearch.setVisibility(GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBinding.ivSearch.setOnClickListener(v -> {
            mBinding.searchEtInput.setText("");
            getData();
        });
        mBinding.searchEtInput.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                getData();
                return true;
            }
            return false;
        });

        mAdapter.setOnItemClickListener(new ReviewOfflineAdapter.OnItemClickListener() {
            @Override
            public void onDeleteClick(int position, WmsInventoryTask item) {
                //离线版不做删除操作
            }

            @Override
            public void onItemClick(int position, WmsInventoryTask item) {
                // 处理详情点击事件
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                startActivity(ReviewOfflineDetailActivity.class, bundle);
            }

            @Override
            public void onCopyClick(int position, WmsInventoryTask item) {
                StringUtil.copyToClipboard(mActivity, item.getTaskNo());
            }

            @Override
            public void onReviewTaskClick(int position, WmsInventoryTask item) {
                // 处理出库点击事件
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                startActivity(ReviewOfflineTaskActivity.class, bundle);
            }

            // 处理结束盘点点击事件 TODO
            @Override
            public void onStopTaskClick(int position, WmsInventoryTask item) {
                if (daoSession != null) {
                    //根据item.getTaskId()查询任务明细信息列表===========================================================================
                    List<WmsInventoryTaskDetail> mList = daoSession.getWmsInventoryTaskDetailDao().queryBuilder().where(WmsInventoryTaskDetailDao.Properties.TaskId.eq(item.getTaskId())).list();
                    if (mList != null && mList.size() > 0) {
                        int count = 0;
                        for (int i = 0; i < mList.size(); i++) {
                            //结束盘点：如果明细内有 待盘点0 的出库单，属于盘亏
                            if (mList.get(i).getCheckStatus().equals("0")) {
                                //计算有几个待盘点，就是盘亏数量
                                count++;//盘亏数量+1
                            }
                        }
                        if (count > 0) {
                            //盘亏数量大于0，提示盘亏数量
                            new AlertDialog.Builder(mActivity).setTitle("提示").setMessage("该盘点任务存在" + count + "个盘亏，是否继续结束？").setPositiveButton("确定", (dialog, which) -> {
                                int count1 = 0;
                                for (int i = 0; i < mList.size(); i++) {
                                    //结束盘点：如果明细内有 待盘点0 的出库单，属于盘亏
                                    if (mList.get(i).getCheckStatus().equals("0")) {
                                        //计算有几个待盘点，就是盘亏数量
                                        count1++;//盘亏数量+1
                                        mList.get(i).setDiffReason("pk");//盘亏
                                    }
                                    //更新数据库
                                    daoSession.getWmsInventoryTaskDetailDao().update(mList.get(i));
                                }
                            }).setNegativeButton("取消", null).show();
                        } else {
                            new AlertDialog.Builder(mActivity).setTitle("提示").setMessage("确定结束该盘点任务吗？").setPositiveButton("确定", (dialog, which) -> {
                                //盘亏数量等于0，直接结束，正常结束
                                WmsInventoryTask wmsInventoryTask = daoSession.getWmsInventoryTaskDao().load(item.getTaskId());
                                wmsInventoryTask.setTaskStatus("2");//设置为已结束
                                daoSession.getWmsInventoryTaskDao().update(wmsInventoryTask);
                            }).setNegativeButton("取消", null).show();
                        }
                    } else {
                        ToastUtil.showShort("暂无盘点明细数据，请先添加盘点明细数据");
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //刷新数据
        getData();
    }

    protected void getData() {
        daoSession = GreenDaoManager.getInstance().getDaoSession();
        if (daoSession == null) {
            //数据库不存在
            mList.clear();
            mAdapter.notifyDataSetChanged();
            mBinding.includedNoDb.llNoDb.setVisibility(View.VISIBLE);
        } else {
            //根据任务编号查询所有盘点任务
            mList = daoSession.queryBuilder(WmsInventoryTask.class).where(WmsInventoryTaskDao.Properties.TaskNo.like("%" + mBinding.searchEtInput.getText().toString() + "%")).build().forCurrentThread().list();
            //设置新的数据集
            mAdapter.setNewInstance(mList);
            //隐藏暂无数据布局
            mBinding.includedNoDb.llNoDb.setVisibility(View.GONE);
            //判断是否为空 如果为空 则显示暂无数据 否则 隐藏暂无数据
            if (mList.isEmpty()) {
                mBinding.includedNothing.llNothing.setVisibility(View.VISIBLE);
            } else {
                mBinding.includedNothing.llNothing.setVisibility(View.GONE);
            }
        }
        //关闭刷新动画
        mBinding.swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (daoSession != null) {
            try {
                daoSession.clear();
                GreenDaoManager.getInstance().closeConnection();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
