package com.naz.sdkdemo.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.naz.sdkdemo.R;
import com.naz.sdkdemo.adaapter.FullApplyTrademarkSelectAdapter;
import com.naz.sdkdemo.base.BaseActivity;
import com.naz.sdkdemo.base.Callback;
import com.naz.sdkdemo.base.CallbackNew;
import com.naz.sdkdemo.bean.OperateResult;
import com.naz.sdkdemo.bean.OrderListInfo;
import com.naz.sdkdemo.bean.ScanInfo;
import com.naz.sdkdemo.bean.TrademarkInfo;
import com.naz.sdkdemo.helper.SerialIPManager;
import com.naz.sdkdemo.helper.SerialPortManager;
import com.naz.sdkdemo.http.ApiHelper;
import com.naz.sdkdemo.utils.MyUtils;
import com.naz.sdkdemo.utils.SerialUtil;
import com.naz.sdkdemo.weight.RecycleViewDivider;
import com.naz.sdkdemo.weight.UserCache;
import com.naz.sdkdemo.weight.XToast;

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

public class FullApplyTrademarkSelectActivity extends BaseActivity {

   private RecyclerView rvContent;
   private FullApplyTrademarkSelectAdapter mAdapter;
   private List<TrademarkInfo> mList;
   private boolean mSelectAll;
   private TextView tvSelectAll;
   private TextView tvSbAll;
   private TextView tvCount;
   private TrademarkInfo mSelectInfo;
   private EditText etSearch;
   private TextView tvProductName;
   private float remainCount = 0;

   private SerialIPManager serialIPManager;
   private List<String> qrCodeList = new ArrayList<>();
   private int selectCount = 0;

   @Override
   protected int getLayoutResId() {
      return R.layout.activity_full_apply_trademark_select;
   }

   @Override
   protected void initView() {
      mSelectInfo = (TrademarkInfo)getIntent().getSerializableExtra("info");
      etSearch = findViewById(R.id.et_search);
      tvSbAll = findViewById(R.id.tv_sb_num);
      tvProductName = findViewById(R.id.tv_product_name);
      tvCount = findViewById(R.id.tv_select_num);
      if (null != mSelectInfo) {
         tvProductName.setText(mSelectInfo.material_code_show);
         remainCount = mSelectInfo.qty;
         tvSbAll.setText(String.valueOf((int) mSelectInfo.qty));
      }
      findViewById(R.id.tv_search).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            requestList();
         }
      });
      rvContent = findViewById(R.id.rv_content);
      mAdapter = new FullApplyTrademarkSelectAdapter(mList);
      mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
         @Override
         public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
            baseQuickAdapter.notifyItemChanged(i, "change");
            TrademarkInfo info = (TrademarkInfo)baseQuickAdapter.getItem(i);
            if (info.select) {
               mSelectAll = false;
            } else {
               boolean all = true;
               for (int j = 0; j < baseQuickAdapter.getData().size(); j++) {
                  if (j != i) {
                     info = (TrademarkInfo)baseQuickAdapter.getItem(j);
                     if (!info.select) {
                        all = false;
                        break;
                     }
                  }
               }
               mSelectAll = all;
            }
            selectCount = 0;
            for (int m = 0; m < baseQuickAdapter.getData().size(); m++) {
               TrademarkInfo trademarkInfo = (TrademarkInfo)baseQuickAdapter.getItem(m);
               if (m == i){
                  if (!trademarkInfo.select) {
                     selectCount += trademarkInfo.qty - trademarkInfo.out_stock_qty_total;
                  }
               }else {
                  if (trademarkInfo.select) {
                     selectCount += trademarkInfo.qty - trademarkInfo.out_stock_qty_total;
                  }
               }
            }
            tvCount.setText(String.valueOf(selectCount));
            updateSelectAllUi();
         }
      });
      rvContent.setLayoutManager(new LinearLayoutManager(this));
      rvContent.setAdapter(mAdapter);
      rvContent.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL,
              MyUtils.dp2px(this, 8), R.color.transparent));
      tvSelectAll = findViewById(R.id.tv_select_all);
      tvSelectAll.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            mSelectAll = !mSelectAll;
            for (TrademarkInfo info : mList) {
               info.select = mSelectAll;
            }
            updateSelectAllUi();
            mAdapter.notifyDataSetChanged();
         }
      });
      findViewById(R.id.btn_sure).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            sure();
         }
      });

      findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            finish();
         }
      });

      serialIPManager = new SerialIPManager();
      serialIPManager.init();
      serialIPManager.connect(UserCache.getIP(), UserCache.getPort()+12, new SerialIPManager.ConnectCallBack() {
         @Override
         public void connectResult(int code) {
            if (code == 0){
               Toast.makeText(FullApplyTrademarkSelectActivity.this, "请确认串口服务器正常开启", Toast.LENGTH_SHORT).show();
            }
         }

         @Override
         public void receiveData(String data) {
            Log.e("--------->","-------->data="+data);
            if (qrCodeList.contains(data))
               return;
            qrCodeList.add(data);
            etSearch.setText(data);
         }
      });
   }

   private void updateSelectAllUi() {
      tvSelectAll.setCompoundDrawablesWithIntrinsicBounds(mSelectAll ? R.mipmap.icon_selected :
              R.mipmap.icon_unselect, 0, 0, 0);
   }

   private void requestList(){
      if (null == mSelectInfo) {
         return;
      }
      String orderId = etSearch.getText().toString();
      String codeStr = mSelectInfo.material_code;
//      orderId = "SO202401160004";
//      String codeStr = "BC060201000001";
      if (TextUtils.isEmpty(orderId)) {
         Toast.makeText(this, "请输入订单号", Toast.LENGTH_SHORT).show();
         return;
      }
      ApiHelper.getOrderList(orderId, codeStr, this,1 , new Callback(){
         @Override
         public void onSuccess(int code, String msg, Object data) {
            if (null == mList) {
               mList = new ArrayList<>();
            }
            mList.clear();
            if (data instanceof OrderListInfo) {
               mList.addAll(((OrderListInfo) data).content);
            }
            mAdapter.setNewData(mList);
         }
      });
   }

   private void sure() {
      if (remainCount <= selectCount) {
         XToast.showToast("请重新选择");
         return;
      }
      ApiHelper.operateApply(this, 3, new CallbackNew<OperateResult>() {
         @Override
         public void onResult(OperateResult operateResult) {
//            next();
            ApiHelper.loopMonitionOpen(FullApplyTrademarkSelectActivity.this, 2, new Callback() {
               @Override
               public void onSuccess(int code, String msg, Object data) {
                  openDoor();
               }
            });
         }
      });
   }

   private SerialPortManager serialPortManager;
   private void openDoor() {
      serialPortManager = new SerialPortManager();
      serialPortManager.init(this, UserCache.getSerialName(), UserCache.getSerialRate(), new SerialPortManager.SerialCallBack() {
         @Override
         public void dataCallBack(String data) {
            Log.e("--------->","------->data="+data);
            byte[] aar = SerialUtil.hexStringToByteArray(data);
            if (aar!=null && aar.length>1){
               if (aar[1] == (byte) 0x06){
                  startNext();
               }
            }
         }

         @Override
         public void openCallBack(int code) {
            if (code == 1){
               serialPortManager.openDoor(1, 1);
            }else {
               Toast.makeText(FullApplyTrademarkSelectActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
            }
         }

         @Override
         public void closeCallBack(int code) {

         }
      });
   }

   private void startNext() {
      ApiHelper.operateRecord(this, 1, new CallbackNew<OperateResult>() {
         @Override
         public void onResult(OperateResult operateResult) {
            Intent intent = new Intent(FullApplyTrademarkSelectActivity.this, FullApplyTrademarkScanActivity.class);
            intent.putExtra("info", mSelectInfo);
            startActivity(intent);
            finish();
         }
      });
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();
      if (serialPortManager!=null){
         serialPortManager.close();
      }
      ApiHelper.cancelLoop();
      serialIPManager.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
   }
}
