package xn.hxp.ui.plan.save_list;

import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kongzue.dialogx.dialogs.PopTip;
import com.rc.httpcore.bean.BelongingPersonBean;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.bean.TopicDataBean;
import com.rc.httpcore.client.ApiRepository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import xn.hxp.app.ChemicalApp;
import xn.hxp.databinding.ItemSaveListBinding;
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.HxpCabinetDoorVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetLockVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetVo;
import xn.hxp.ui.plan.room.dao.HxpDoorDAO;
import xn.hxp.weidith.TextTool;

public class SaveListAdapter extends BaseAdapter {

    private SaveListActivity activity;
    private List<SaveListBean> saveListBeanList = new ArrayList<>();
    private HxpDoorDAO doorDAO;
    private Map<Long, List<SaveListBean>> saveListBeanMap;

    /**
     * @param activity
     * @param saveListBeanMap <doorId,>
     */
    public SaveListAdapter(SaveListActivity activity, Map<Long, List<SaveListBean>> saveListBeanMap) {
        Set<Long> keySet = saveListBeanMap.keySet();
        for (Long doorId : keySet) {
            saveListBeanList.addAll(saveListBeanMap.get(doorId));
        }
        this.saveListBeanMap = saveListBeanMap;
        this.activity = activity;
        doorDAO = RoomTool.getInstance().hxpDoorDAO();
    }

    @Override
    public int getCount() {
        return saveListBeanList.size();
    }

    @Override
    public SaveListBean getItem(int position) {
        return saveListBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        SaveListBean saveListBean = getItem(position);
        ViewHolder viewHolder;
        if (convertView == null) {
            ItemSaveListBinding binding = ItemSaveListBinding.inflate(LayoutInflater.from(activity), parent, false);
            convertView = binding.getRoot();
            viewHolder = new ViewHolder(binding);
            convertView.setTag(viewHolder);
            //  开门
            binding.unlockBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                @Override
                public void onDebouncingClick(View v) {
                    HxpCabinetDoorVo doorVo = doorDAO.getById(saveListBean.getDoorId());
                    List<HxpCabinetLockVo> lockVoList = doorVo.getCabinetLockVoList();
                    if (null != lockVoList && !lockVoList.isEmpty()) {
                        HxpCabinetLockVo lockVo = lockVoList.get(0);
                        unlock(lockVo);
                    }
                }
            });
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        try {
            if (null != saveListBean) {
                if (saveListBean.isTitle()) {
                    viewHolder.binding.titlleLL.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.binding.titlleLL.setVisibility(View.GONE);
                }
                if (saveListBean.isUnlock()) {
                    viewHolder.binding.unlockBT.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.binding.unlockBT.setVisibility(View.GONE);
                }

                // 需要展示数量时
                if (position == 0) {
                    viewHolder.binding.sumTV.setVisibility(View.VISIBLE);
                    if (null != saveListBeanMap) {
                        int countSize = 0;
                        for (int i = 0; i < saveListBeanList.size(); i++) {
                            SaveListBean saveBean = saveListBeanList.get(i);
                            InventoryItemBean inventoryItemBean = saveBean.getInventoryItemBean();
                            if (null != inventoryItemBean) {
                                countSize = countSize + inventoryItemBean.getSize();
                            }
                        }
                        if (countSize > 0) {
                            viewHolder.binding.sumTV.setText("数量:" + countSize);
                        }
                    }
                } else {
                    viewHolder.binding.sumTV.setVisibility(View.GONE);
                }
                String cabinetName = saveListBean.getCabinetName();
                cabinetName = TextUtils.isEmpty(cabinetName) ? "" : cabinetName;
                String doorName = saveListBean.getDoorName();
                doorName = TextUtils.isEmpty(doorName) ? "" : doorName;
                viewHolder.binding.cabinetTV.setText(cabinetName + "-" + doorName);

                InventoryItemBean inventoryItemBean = saveListBean.getInventoryItemBean();
                if (null != inventoryItemBean) {
                    HxpChemicalVo chemicalVo = inventoryItemBean.getHxpChemicalVo();
                    if (null != chemicalVo) {
                        // 化学品名称
                        String chemicalName = chemicalVo.getChemicalName();
                        viewHolder.binding.name.setText(TextUtils.isEmpty(chemicalName) ? "" : cabinetName);
                        viewHolder.binding.name.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                            @Override
                            public void onDebouncingClick(View v) {
                                TextTool.showPop(activity, viewHolder.binding.name);
                            }
                        });
                        // CAS
                        String casNum = chemicalVo.getCasNum();
                        viewHolder.binding.cas.setText(TextUtils.isEmpty(casNum) ? "" : casNum);
                        // 类别
                        String chemicalCategoryName = chemicalVo.getChemicalCategoryName();
                        viewHolder.binding.type.setText(TextUtils.isEmpty(chemicalCategoryName) ? "" : chemicalCategoryName);
                        // 级别
                        int level = chemicalVo.getChemicalLevel();
                        viewHolder.binding.level.setText(1 == level ? "管控" : "非管控");
                        // 规格
                        double specNum = chemicalVo.getSpecNum();
                        String specUnit = chemicalVo.getSpecUnit();
                        specUnit = TextUtils.isEmpty(specUnit) ? "" : specUnit;
                        viewHolder.binding.specs.setText(specNum + "/" + specUnit);
                        // 净含量
                        double netWt = chemicalVo.getNetContent();
                        viewHolder.binding.netWT.setText(netWt + specUnit);
                        // 数量
                        int size = inventoryItemBean.getSize();
                        viewHolder.binding.hxpSum.setText(String.valueOf(size));
                        // 归属
                        BelongingPersonBean personBean = inventoryItemBean.getBelongingPersonBean();
                        TopicDataBean topicDataBean = inventoryItemBean.getTopicDataBean();
                        String name;
                        if (null == personBean) {
                            name = topicDataBean.getTopicName();
                        } else {
                            name = personBean.getUserName();
                        }
                        viewHolder.binding.owner.setText(TextUtils.isEmpty(name) ? "" : name);
                    }
                }
            }
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        return convertView;
    }

    static class ViewHolder {
        ItemSaveListBinding binding;

        public ViewHolder(ItemSaveListBinding binding) {
            this.binding = binding;
        }
    }

    /**
     * 单独开锁
     */
    public void unlock(HxpCabinetLockVo nowLockVo) {
        activity.showLoading("开锁中...");
        Map<String, Object> map = new HashMap<>();
        map.put("subId", ChemicalApp.subjectId);
        map.put("subName", ChemicalApp.subjectName);


        HxpCabinetDoorVo hxpDoorVo = doorDAO.getById(nowLockVo.getDoorId());


        if (null != hxpDoorVo) {
            map.put("doorId", hxpDoorVo.getDoorId());
            map.put("doorName", hxpDoorVo.getDoorName());
            HxpCabinetVo hxpCabinetVo = activity.cabinetDAO.getById(hxpDoorVo.getCabinetId());
            if (null != hxpCabinetVo) {
                map.put("cabinetId", hxpCabinetVo.getCabinetId());
                map.put("cabinetName", hxpCabinetVo.getCabinetName());
            }
        }
        List<String> lockNumList = new ArrayList<>();
        lockNumList.add(nowLockVo.getLockNum());
        map.put("lockNumList", lockNumList);
        map.put("operationType", 3);
        if (ChemicalApp.subRoom != null) {
            map.put("subRoom", ChemicalApp.subRoom);
        }
        map.put("type", true);
        if (activity.userValidation1 != null) {
            map.put("oneUserId", activity.userValidation1.getUserId());
            map.put("oneUserName", activity.userValidation1.getUserName());
        }
        if (null != activity.userValidation2) {
            map.put("twoUserId", activity.userValidation2.getUserId());
            map.put("twoUserName", activity.userValidation2.getUserName());
        }
        LogUtils.json("手动开锁", map);
        activity.unlockDisposable = ApiRepository.INSTANCE.lockOperate(map).subscribe(aBoolean -> {
            LogUtils.d("手动开锁", nowLockVo.getLockNum(), nowLockVo.getLockName(), aBoolean);
            if (aBoolean) {
                activity.unlockStatusCDTimer = new CountDownTimer(30 * 1000, 3000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        if (null != activity.unlockStatusDisposable) {
                            activity.delDisposable(activity.unlockStatusDisposable);
                        }
                        activity.unlockStatusDisposable = ApiRepository.INSTANCE.getLocks(ChemicalApp.subjectId, nowLockVo.getLockNum()).subscribe(aBoolean -> {
                            LogUtils.d("手动开锁查询状态", nowLockVo.getLockNum(), nowLockVo.getLockName(), aBoolean);
                            if (aBoolean) {
                                activity.unlockStatusCDTimer.cancel();
                                PopTip.show("开门成功!");
                                activity.dismissLoading();
                            }
                        }, throwable -> LogUtils.e(Log.getStackTraceString(throwable)));
                        activity.addDisposable(activity.unlockStatusDisposable);
                    }

                    @Override
                    public void onFinish() {
                        LogUtils.d("手动开锁失败", nowLockVo.getLockNum(), nowLockVo.getLockName());
                        activity.dismissLoading();

                        if (null != hxpDoorVo) {
                            PopTip.show(hxpDoorVo.getDoorName() + "开门失败!");
                        } else {
                            PopTip.show("开门失败!");
                        }
                    }
                };
                activity.unlockStatusCDTimer.start();
            } else {
                nowLockVo.setUnlockType(2);
            }
        }, throwable -> LogUtils.e(Log.getStackTraceString(throwable)));
        activity.addDisposable(activity.unlockDisposable);
    }
}
