package com.bbitcn.silk.ui.activity;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bbitcn.silk.adapter.ItemContentAdapter;
import com.bbitcn.silk.adapter.TarePageAdapter;
import com.bbitcn.silk.base.BaseActivity;
import com.bbitcn.silk.databinding.ActivityTareBinding;
import com.bbitcn.silk.databinding.ItemInfoContentBinding;
import com.bbitcn.silk.model.InfoContent;
import com.bbitcn.silk.model.net.QueryList;
import com.bbitcn.silk.model.net.ToTareSubmit;
import com.bbitcn.silk.ui.dialog.ConfirmDialog;
import com.bbitcn.silk.ui.dialog.SpinnerDialog;
import com.bbitcn.silk.ui.fragment.TareInfoFragment;
import com.bbitcn.silk.utils.MMKVUtil;
import com.bbitcn.silk.utils.database.PriceDataBase;
import com.bbitcn.silk.utils.database.TareDataBase;
import com.bbitcn.silk.utils.global.Global;
import com.bbitcn.silk.utils.global.SpinnerList;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

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

import es.dmoral.toasty.Toasty;

/**
 * @Description 扣皮定价界面
 * @Author DuanKaiji
 * @CreateTime 2024年03月27日 15:12
 */
public class TareActivity extends BaseActivity<ActivityTareBinding, TareActivityPresenter> {
    QueryList.DataDTO data;
    TarePageAdapter adapter;

    @Override
    public void initView() {
        data = GsonUtils.fromJson(getIntent().getStringExtra("data"), QueryList.DataDTO.class);
        binding.include.tvName.setText(data.getNhName());
        binding.include.tvId.setText(data.getCzCode());
        binding.include.recycleView.setLayoutManager(new LinearLayoutManager(mContext));
        binding.include.view4.setVisibility(View.GONE);
        binding.include.llExertFunc.setVisibility(View.VISIBLE);
        binding.include.tvConfirm.setVisibility(View.GONE);
        binding.include.tvCancel.setOnClickListener(v -> new ConfirmDialog(mContext, "弃售", "确定要弃售" + data.getCzCode() + "吗？",
                () -> presenter.cancel(data.getCzSysid())).show());
        List<InfoContent> temp = new ArrayList<>();
        for (QueryList.DataDTO.ItemsDTO itemsDTO : data.getItems()) {
            temp.add(new InfoContent(itemsDTO.getSgTypeName(), itemsDTO.getBaoshu(), itemsDTO.getMaozhong(), itemsDTO.getPrice()));
        }
        binding.include.cardState.setVisibility(View.GONE);
        binding.include.recycleView.setAdapter(new ItemContentAdapter(temp, ItemInfoContentBinding.class, null));
        adapter = new TarePageAdapter(this, data);
        binding.viewPage2.setUserInputEnabled(false);
        binding.viewPage2.setAdapter(adapter);
        binding.viewPage2.setOffscreenPageLimit(adapter.getItemCount());
        //给tabLayout添加tab
        for (int i = 0; i < data.getItems().size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab());
        }
        new TabLayoutMediator(binding.tabLayout, binding.viewPage2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int i) {
                tab.setText(data.getItems().get(i).getSgTypeName());
            }
        }).attach();
        presenter.getNotice().observe(this, integer -> {
            if (integer == 0) {
                //保存成功
                finish();
                //删除缓存
                TareDataBase.removeCatchById(data);
            }
        });
    }

    @Override
    public void initListener() {
        super.initListener();
        View.OnClickListener setUnit = view -> new SpinnerDialog(mContext, "默认定价单位", "请选择单位", SpinnerList.UNIT, selString -> {
            MMKVUtil.put(Global.UNIT, selString);
            binding.tvUnit.setText("单位：" + selString);
            Toasty.success(mContext, "设置成功").show();
            refreshPageUnit();
        }).show();
        binding.ivBack.setOnClickListener(v -> finish());
        binding.tvUnit.setOnClickListener(setUnit);
        binding.ivUnit.setOnClickListener(setUnit);
        binding.btnSubmit.setOnClickListener(v -> {
            ToTareSubmit item = new ToTareSubmit();
            item.setCzsysid(data.getCzSysid());
            List<ToTareSubmit.ItemsDTO> itemsDTOS = new ArrayList<>();
            //获取ViewPage2中的每个Fragment
            for (int i = 0; i < adapter.getItemCount(); i++) {
                TareInfoFragment fragment = adapter.getFragment(i);
                double price;
                double net;
                double skin;
                if (StringUtils.isEmpty(fragment.getSkin())) {
                    errorTips(data.getItems().get(i).getSgTypeName() + "的皮重不能为空");
                    return;
                }
                try {
                    // 不可为空 不可为“数据错误”
                    price = Double.parseDouble(fragment.getPrice());
                    net = Double.parseDouble(fragment.getNet());
                    skin = Double.parseDouble(fragment.getSkin());
                } catch (Exception e) {
                    errorTips("请检查" + data.getItems().get(i).getSgTypeName() + "的价格、皮重与净重是否正确");
                    return;
                }
                QueryList.DataDTO.ItemsDTO itemsDTO = data.getItems().get(i);
                // 不可为0
                if (price == 0) {
                    errorTips(itemsDTO.getSgTypeName() + "的价格不可为0，请检查");
                    return;
                }
                double[] minMax = PriceDataBase.getCatchById(itemsDTO.getSgTypeName());
                if (price < minMax[0] || price > minMax[1]) {
                    errorTips(itemsDTO.getSgTypeName() + "的今日价格为￥" + minMax[0] + "~" + minMax[1] + "，请检查");
                    return;
                }
                if (net == 0) {
                    errorTips(itemsDTO.getSgTypeName() + "的净重不可为0，请检查");
                    return;
                }
                ToTareSubmit.ItemsDTO dto = new ToTareSubmit.ItemsDTO();
                dto.setSgtypesysid(itemsDTO.getSgTypeSysid());
                //可为空
                String ti_skin = fragment.getSkin();
                String ti_tare = fragment.getTare();
                dto.setPizhong(StringUtils.isEmpty(ti_skin) ? 0 : Double.parseDouble(ti_skin) / Global.getUnitInt());
                dto.setKouzhong(StringUtils.isEmpty(ti_tare) ? 0 : Double.parseDouble(ti_tare) / Global.getUnitInt());
                dto.setPrice(price * Global.getUnitInt());
                itemsDTOS.add(dto);
            }
            item.setItems(itemsDTOS);
            presenter.tareSubmit(item);
        });
    }

    /**
     * 刷新子页面单位
     */
    private void refreshPageUnit() {
        for (int i = 0; i < adapter.getItemCount(); i++) {
            TareInfoFragment fragment = adapter.getFragment(i);
            fragment.refreshUnit();
        }
    }

}
