package com.stm.asset.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.seuic.uhf.EPC;
import com.stm.asset.R;
import com.stm.asset.base.StmApplication;
import com.stm.asset.model.InventoryInfo;
import com.stm.asset.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.TaskViewHolder> {

    private List<InventoryInfo> dataList;
    private List<InventoryInfo> advantageList;
    private final Context context;

    public TaskListAdapter(Context context) {
        this.dataList = new ArrayList<>();
        this.advantageList = new ArrayList<>();
        this.context = context;
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflater = LayoutInflater.from(context).inflate(R.layout.view_check_task_item, parent, false);
        return new TaskViewHolder(inflater);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        InventoryInfo taskInfo = dataList.get(position);
        holder.seqTxt.setText(taskInfo.getItem02());
        holder.nameTxt.setText(taskInfo.getName());
        holder.numberTxt.setText(taskInfo.getNumber());
        String statusName = "";
        if ("0".equals(taskInfo.getItem01())) {
            statusName = "未盘点";
        } else if ("1".equals(taskInfo.getItem01())) {
            statusName = "相符";
        } else if ("2".equals(taskInfo.getItem01())) {
            statusName = "盘亏";
        } else if ("3".equals(taskInfo.getItem01())) {
            statusName = "盘盈";
        }
        holder.statusTxt.setText(statusName);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    /**
     * 刷新数据
     */
    @SuppressLint("NotifyDataSetChanged")
    public void setData(List<InventoryInfo> data) {
        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        dataList.clear();
        if (advantageList == null) {
            advantageList = new ArrayList<>();
        }
        advantageList.clear();
        if (data != null && data.size() > 0) {
            dataList.addAll(data);
        }
        notifyDataSetChanged();
    }

    /**
     * 修改数据盘点状态
     */
    @SuppressLint("NotifyDataSetChanged")
    public void updateStatus(List<EPC> epcList) {
        if (epcList != null && epcList.size() > 0) {
            List<InventoryInfo> oldList = getCloneList();
            Set<String> advantageKey = new HashSet<>();
            for (EPC item : epcList) {
                String epcStr = item.getId();
                // 数字且位数是4的倍数
                if (!StringUtils.isEmptyOrNull(epcStr) && StringUtils.isNumber(epcStr) && epcStr.length() % 4 == 0) {
                    boolean exists = false;
                    for (InventoryInfo info : dataList) {
                        if (epcStr.equals(info.getNumber())) {
                            info.setItem01("1");
                            exists = true;
                        }
                    }
                    if (!exists && !advantageKey.contains(epcStr)) {
                        InventoryInfo advantageInfo = new InventoryInfo();
                        advantageInfo.setNumber(epcStr);
                        advantageInfo.setStatus("0");
                        advantageInfo.setItem01("3");
                        advantageList.add(advantageInfo);
                        advantageKey.add(epcStr);
                    }
                }
            }
            InventoryCallBack callback = new InventoryCallBack(oldList, dataList);
            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(callback);
            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                @Override
                public void run() {
                    diffResult.dispatchUpdatesTo(TaskListAdapter.this);
                }
            });
        }
    }

    private List<InventoryInfo> getCloneList() {
        List<InventoryInfo> cloneList = new ArrayList<>();
        if (dataList != null) {
            for (InventoryInfo info : dataList) {
                InventoryInfo clone = info.copy();
                cloneList.add(clone);
            }
        }
        return cloneList;
    }

    public List<InventoryInfo> queryResultData() {
        return dataList;
    }

    public List<InventoryInfo> queryAdvantageData() {
        return advantageList;
    }

    static class InventoryCallBack extends DiffUtil.Callback {

        List<InventoryInfo> oldList, newList;

        public InventoryCallBack(List<InventoryInfo> oldList, List<InventoryInfo> newList) {
            this.oldList = oldList;
            this.newList = newList;
        }

        @Override
        public int getOldListSize() {
            return oldList == null ? 0 : oldList.size();
        }

        @Override
        public int getNewListSize() {
            return newList == null ? 0 : newList.size();
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return Objects.equals(oldList.get(oldItemPosition).getNumber(), newList.get(newItemPosition).getNumber());
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return (Objects.equals(oldList.get(oldItemPosition).getStatus(), newList.get(newItemPosition).getStatus())
              && Objects.equals(oldList.get(oldItemPosition).getItem01(), newList.get(newItemPosition).getItem01()));
        }
    }

    static class TaskViewHolder extends RecyclerView.ViewHolder {
        TextView seqTxt, nameTxt, numberTxt, statusTxt;

        public TaskViewHolder(View itemView) {
            super(itemView);
            seqTxt = itemView.findViewById(R.id.task_item_seq_txt);
            nameTxt = itemView.findViewById(R.id.task_item_name_txt);
            numberTxt = itemView.findViewById(R.id.task_item_number_txt);
            statusTxt = itemView.findViewById(R.id.task_item_status_txt);
        }

    }

}
