package com.naz.sdkdemo.activity;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
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.ApplyTrademarkCompleteAdapter;
import com.naz.sdkdemo.adaapter.RepairTrademarkCompleteAdapter;
import com.naz.sdkdemo.base.BaseActivity;
import com.naz.sdkdemo.base.CallbackNew;
import com.naz.sdkdemo.bean.LbBean;
import com.naz.sdkdemo.bean.StockInfo;
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.weight.GridSpaceItemDecoration;
import com.naz.sdkdemo.weight.RecycleViewDivider;
import com.naz.sdkdemo.weight.UserCache;

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

public class RepairTrademarkCompleteActivity extends BaseActivity {

   private RecyclerView rvContent;
   private TextView tvTrademark;
   private RepairTrademarkCompleteAdapter mAdapter;
   private List<StockInfo> mList;
   private TrademarkInfo mSelectInfo;
   private List<TrademarkInfo> mData;
   private List<String> outList = new ArrayList<>();
   private SerialPortManager serialPortManager;
   private SerialIPManager serialIPManager1;
   private SerialIPManager serialIPManager2;
   private SerialIPManager serialIPManager3;
   private SerialIPManager serialIPManager4;
   private SerialIPManager serialIPManager5;
   private SerialIPManager serialIPManager6;
   private SerialIPManager serialIPManager7;
   private SerialIPManager serialIPManager8;
   private SerialIPManager serialIPManager9;
   private SerialIPManager serialIPManager10;
   private SerialIPManager serialIPManager11;
   private SerialIPManager serialIPManager12;
   private List<String> qrCodeList = new ArrayList<>();
   private int markNum = 0;
   private int totalMark = 0;

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

   @Override
   protected void initView() {
      mSelectInfo = (TrademarkInfo)getIntent().getSerializableExtra("data");
      tvTrademark = findViewById(R.id.tv_trademark);
      tvTrademark.setText(mSelectInfo.material_code_show);
      rvContent = findViewById(R.id.rv_content);
      rvContent.setLayoutManager(new GridLayoutManager(this, 2));
      GridSpaceItemDecoration itemDecoration = new GridSpaceItemDecoration(MyUtils.dp2px(this, 12), true);
      itemDecoration.setEndFromSize(0);
      rvContent.addItemDecoration(itemDecoration);
      mAdapter = new RepairTrademarkCompleteAdapter(mList);
      mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
         @Override
         public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

         }
      });
      rvContent.setAdapter(mAdapter);
//      findViewById(R.id.btn_sure).setOnClickListener(new View.OnClickListener() {
//         @Override
//         public void onClick(View v) {
//            next();
//         }
//      });
      Bundle bundle = getIntent().getExtras();
      mData = (List<TrademarkInfo>) bundle.getSerializable("info");

      List<LbBean> list = new ArrayList<>();
      list.clear();
      for (TrademarkInfo trademarkInfo: mData) {
         LbBean lb = new LbBean();
         lb.title = trademarkInfo.prod_trademark_compare_view.brand_code_show;
         lb.num = ""+trademarkInfo.getOrderCount();
         lb.restore_qty = trademarkInfo.count;
         lb.product_code = trademarkInfo.material_code;
         lb.product_code_show = trademarkInfo.material_code_show;
         lb.order_item_id = trademarkInfo.id;
         lb.order_item_id_show = trademarkInfo.exe_sale_order_b.no;
         list.add(lb);
      }
      requestList(list);
      serialIPManager1 = scanPort(UserCache.getPort());
      serialIPManager2 =scanPort(UserCache.getPort()+1);
      serialIPManager3 =scanPort(UserCache.getPort()+2);
      serialIPManager4 =scanPort(UserCache.getPort()+3);
      serialIPManager5 =scanPort(UserCache.getPort()+4);
      serialIPManager6 =scanPort(UserCache.getPort()+5);
      serialIPManager7 =scanPort(UserCache.getPort()+6);
      serialIPManager8 =scanPort(UserCache.getPort()+7);
      serialIPManager9 =scanPort(UserCache.getPort()+8);
      serialIPManager10 =scanPort(UserCache.getPort()+9);
      serialIPManager11 =scanPort(UserCache.getPort()+10);
      serialIPManager12 =scanPort(UserCache.getPort()+11);
   }

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

         @Override
         public void receiveData(String data) {
            Log.e("--------->","-------->data="+data);
            if (qrCodeList.contains(data))
               return;
            String[] a = data.split("code=");
            if (a.length > 0){
               String b = a[a.length-1];
               String[] c= b.split("&");
               if (c.length > 0){
                  data = c[0];
               }
            }
            qrCodeList.add(data);
            for (StockInfo stockInfo: mList) {
               if (stockInfo.box_code.equals(outList.get(markNum))){
                  mList.get(mList.indexOf(stockInfo)).out_qty = stockInfo.out_qty+1;
                  mAdapter.setNewData(mList);
               }
            }
            markNum++;
//            mList.get(0).out_qty = markNum;
//            mAdapter.setNewData(mList);
            if (markNum == totalMark){
               next();
            }else {
               serialPortManager.outOfMark(getNumber(outList.get(markNum-1)));
            }
         }
      });
      return serialIPManager;
   }

   private void requestList(List<LbBean> list){
      ApiHelper.getLB(this, list, new CallbackNew<List<StockInfo>>() {
         @Override
         public void onResult(List<StockInfo> storehouseInfos) {
            if (null == mList) {
               mList = new ArrayList<>();
            }
            mList.clear();
            if (null != storehouseInfos) {
               mList.addAll(storehouseInfos);
            }
            mAdapter.setNewData(mList);
//            totalMark = 2;
//            outOfMark();
            if (mList.size()>0){
               outList.clear();
               for (StockInfo bean: mList) {
                  if (bean.send_qty>0){
                     totalMark+=bean.send_qty;
                     for (int i = 0; i < bean.send_qty; i++) {
                        outList.add(bean.box_code);
                     }
                  }
               }
               Log.e("-------->","-------->totalMark = "+totalMark);
               outOfMark();
            }
         }
      });
   }

   private void outOfMark() {
      serialPortManager = new SerialPortManager();
      serialPortManager.init(this, UserCache.getSerialName(), UserCache.getSerialRate(), new SerialPortManager.SerialCallBack() {
         @Override
         public void dataCallBack(String data) {
            Log.e("--------->","------->data="+data);
         }

         @Override
         public void openCallBack(int code) {
            if (code == 1){
               Log.e("--------->","------->出标1");
               if (outList.size()>0){
                  serialPortManager.outOfMark(getNumber(outList.get(0)));
               }
//               next();
//               loopDoorClose();
            }else {
               Toast.makeText(RepairTrademarkCompleteActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
            }
         }

         @Override
         public void closeCallBack(int code) {

         }
      });
   }

   private void next() {
      ApiHelper.lendBind(mList.get(0).material_code, mList.get(0).material_code_show, mSelectInfo.no, qrCodeList, this, new CallbackNew<Integer>() {
         @Override
         public void onResult(Integer integer) {
            if (integer == 1){
//               finish();
               List<StockInfo> list = new ArrayList<>();
               for (int i = 0; i < mList.size(); i++) {
                  StockInfo stockInfo = mList.get(i);
                  if (stockInfo.send_qty>0){
                     list.add(stockInfo);
                  }
               }
               ApiHelper.brandRecharge(mSelectInfo, mData, list, RepairTrademarkCompleteActivity.this, new CallbackNew<Integer>() {
                  @Override
                  public void onResult(Integer integer) {


                     if (integer == 1){
                        new Handler().postDelayed(new Runnable() {
                           @Override
                           public void run() {
                              finish();
                           }
                        }, 10*1000);
                     }
                  }
               });
            }
         }
      });
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();
      serialPortManager.close();
      serialIPManager1.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager2.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager3.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager4.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager5.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager6.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager7.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager8.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager9.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager10.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager11.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
      serialIPManager12.close(new SerialIPManager.CloseCallBack() {
         @Override
         public void closeResult(int code) {

         }
      });
   }

   private int getNumber(String boxCode){
      int number = 0;
      switch (boxCode){
         case "CK00004":
            number = 1;
            break;
         case "CK00005":
            number = 2;
            break;
         case "CK00006":
            number = 3;
            break;
         case "CK00007":
            number = 4;
            break;
         case "CK00008":
            number = 5;
            break;
         case "CK00009":
            number = 6;
            break;
         case "CK00010":
            number = 7;
            break;
         case "CK00011":
            number = 8;
            break;
         case "CK00012":
            number = 9;
            break;
         case "CK00013":
            number = 10;
            break;
         case "CK00014":
            number = 11;
            break;
         case "CK00015":
            number = 12;
            break;
      }
      return number;
   }
}
