package com.example.bpa.view.from;

import static android.media.CamcorderProfile.get;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.bpa.R;
import com.example.bpa.service.DeviceData;
import com.example.bpa.config.DataBus;
import com.example.bpa.db.QueryDB;
import com.example.bpa.db.mode.BPA_MATERIAL;
import com.example.bpa.db.mode.BPA_SILOS;
import com.example.bpa.db.mode.BPA_SILOSANDMATERIAL;
import com.example.bpa.helper.FlashHelper;
import com.example.bpa.helper.T;
import com.example.bpa.view.adapter.lc_item_adapter;
import com.example.bpa.view.adapter.selectitem_adapter;
import com.example.bpa.view.control.ItemClickListener;
import com.example.bpa.view.control.MyLayoutManager;
import com.example.bpa.view.mode.lcMode;

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

/**
 * 料仓设置
 */
public class lcsz_activity extends AppCompatActivity implements View.OnClickListener {
    //region 变量
    /**
     * 返回按钮
     */
    ImageView gongneng_fanhui;
    /**
     * 标题设置
     */
    TextView gongneng_title;
    RecyclerView recyclerView;
    //物料listview
    ListView materiallist;
    //materiallist父控件
    View material_parent;
    //物料列表
    ArrayList<BPA_MATERIAL> bpa_materials = new ArrayList<>();
    //当前选中的料仓id
    lc_item_adapter.MyLCViewHolder currentSilo;
    //当前料仓集合
    List<lcMode> datas = new ArrayList<lcMode>();
    //endregion

    //region 私有函数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lcsz);
        Init();
        initEvents();
        Run();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //endregion

    //region 公共函数

    /**
     * 初始化
     */
    private void Init() {
        gongneng_fanhui = this.findViewById(R.id.gongneng_fanhui);
        gongneng_title = this.findViewById(R.id.gongneng_title);
        //通过Activity.getIntent()获取当前页面接收到的Intent。 getXxxExtra方法获取Intent传递过来的数据
        String msg = getIntent().getStringExtra("data");
        gongneng_title.setText(msg);
        //横向排列
        recyclerView = this.findViewById(R.id.lc_view);
        materiallist = this.findViewById(R.id.materials);
        material_parent = (View) materiallist.getParent();
        try {
            //加载 recyclercview数据
            MyLayoutManager layout = new MyLayoutManager();
            //必须，防止recyclerview高度为wrap时测量item高度0
            layout.setAutoMeasureEnabled(true);
            recyclerView.setLayoutManager(layout);
            //获取料仓数据
            ArrayList<BPA_SILOS> bpa_silos = QueryDB.GetSilosALL();
            //加载materials数据
            if (bpa_silos.size() > 0) {
                for (BPA_SILOS silo : bpa_silos) {
//                    String resmaterialid =  QueryDB.GetMaterialList(silo.id).size()==0? "-1" : QueryDB.GetMaterialList(silo.id).get(0);
//                    String material_name = "未设置";
//                    String material_id = "";
//                    if (resmaterialid != "-1"){
//                        BPA_MATERIAL res= QueryDB.GetMaterialbyid(resmaterialid);
//                        if (res!=null) {
//                            material_name = res.name;
//                            material_id = res.id;
//                        }
//
//                    }
                    List<BPA_MATERIAL> m = QueryDB.GetMaterialBySilosID(silo.id);
                    if (m.size() > 0) {
                        datas.add(new lcMode(silo.id, silo.num, m.get(0).name, "0", m.get(0).id, silo.warningValue, silo.thrsoleValue,silo.name));
                    } else {
                        datas.add(new lcMode(silo.id, silo.num, "未设置", "0", "", silo.warningValue, silo.thrsoleValue,silo.name));
                    }
                }
            }
            lc_item_adapter adapter = new lc_item_adapter(this, datas);

            recyclerView.setAdapter(adapter);

            //加载listview 数据
            bpa_materials = QueryDB.GetMaterialALL();

            BPA_MATERIAL wsz = new BPA_MATERIAL();
            wsz.name = "未设置";
            wsz.id = "";
            bpa_materials.add(wsz);
            selectitem_adapter selectadapter = new selectitem_adapter(lcsz_activity.this, R.layout.selectitem_item, bpa_materials);
            materiallist.setAdapter(selectadapter);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化按钮事件
     */
    private void initEvents() {
        gongneng_fanhui.setOnClickListener(this);

        recyclerView.addOnItemTouchListener(new ItemClickListener(recyclerView, new ItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
                if (viewHolder instanceof lc_item_adapter.MyLCViewHolder) {
                    View listViewParent = (View) materiallist.getParent();
                    listViewParent.setVisibility(View.VISIBLE);
                    currentSilo = null;
                    currentSilo = (lc_item_adapter.MyLCViewHolder) viewHolder;
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        }));
        //endregion

        //region   materials点击事件
        materiallist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayAdapter viewHolder = (ArrayAdapter) materiallist.getAdapter();
                if (viewHolder instanceof selectitem_adapter) {
                    material_parent.setVisibility(View.GONE);//隐藏父控件
                    if (currentSilo != null) {
                        BPA_SILOSANDMATERIAL item = new BPA_SILOSANDMATERIAL();
                        BPA_MATERIAL material = ((selectitem_adapter) viewHolder).getItem(position);
                        item.silosID = currentSilo.id;
                        item.materialID = material.id;
                        //更新
                        if (QueryDB.UpdateSilosAndMaterial(item)) {
                            currentSilo.materialName.setText(material.name);
                            T.show(lcsz_activity.this, "更新成功");
                            datas.get(currentSilo.getNum() - 1).materialId = item.materialID;
                            datas.get(currentSilo.getNum() - 1).materialName = material.name;
                            currentSilo.startFlick();
                        }
                    }
                }
            }
        });

        //region   materials父控件点击事件
        material_parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                material_parent.setVisibility(View.GONE);//隐藏materiallist
            }
        });
        //endregion

    }

    /**
     * 页面点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gongneng_fanhui://返回按钮
                this.finish();
                break;
        }
    }

    //endregion

    //region 线程
    /**
     * 实时显示线程
     */
    public void Run() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (DataBus.getInstance().PlcIsConnect) {
                    try {
                        lcsz_activity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                for (int i = 0; i < datas.size(); i++) {
                                    int num = datas.get(i).num;
                                    int val = DeviceData.Get().getCallCurrentWeight(num);
                                    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(i);
                                    if (viewHolder != null) {
                                        lc_item_adapter.MyLCViewHolder hold = (lc_item_adapter.MyLCViewHolder) viewHolder;
                                        //hold.silosmargin.setText(new java.text.DecimalFormat("#.00").format(val)+"g");
                                        hold.silosmargin.setText(val + "g");

                                        if (!datas.get(i).materialId.isEmpty()) {
                                            if (val < datas.get(i).warningValue)//补料
                                            {
                                                hold.image_yj.setVisibility(View.VISIBLE);
                                            } else {
                                                hold.image_yj.setVisibility(View.GONE);
                                                FlashHelper.getInstance().stopFlick(hold.image_yj);
                                            }

                                            if (val < datas.get(i).thrsoleValue)//告警
                                            {
                                                hold.image_gj.setVisibility(View.VISIBLE);
                                            } else {
                                                hold.image_gj.setVisibility(View.GONE);
                                                FlashHelper.getInstance().stopFlick(hold.image_gj);
                                            }
                                        } else {
                                            hold.image_yj.setVisibility(View.GONE);
                                            hold.image_gj.setVisibility(View.GONE);
                                            hold.stopFlick();
                                        }
                                    }
                                }
                            }
                        });
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
    //endregion
}