package com.ygtx.emcs.activity;

import static com.ygtx.emcs.comm.BaseApplication.mScanManager;
import static com.ygtx.emcs.util.Constant.CACHE_BIND_CONFIG;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockLineListViewAdapter;
import com.ygtx.emcs.activity.model.ItemModel;
import com.ygtx.emcs.activity.model.StockLineModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.databinding.YgtxStockInAddBinding;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.HttpsUtil;
import com.ygtx.emcs.util.MyProgress;
import com.ygtx.emcs.util.StringUtils;
import com.ygtx.emcs.util.ToastUtils;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;
import java.util.ArrayList;


public class StockInNewActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(StockInNewActivity.class);

    private YgtxStockInAddBinding binding;
    private Context context;
    private StockLineListViewAdapter stockLineListViewAdapter;
    private ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private PopupWindow popupWindow2;
    private EditText et_itemCode;
    private EditText et_qty;
    private EditText et_boxCode;
    private Button bt_ok;
    private StockLineModel stockLineModel;
    private String in_stock_flag;
    private String box_flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgtxStockInAddBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        registerReceiver();
        initCommonTop2();
        initView();
        initData();
    }

    int i = 0;
    private void initData(){
        binding.lvProduct.setOnItemLongClickListener((parent, view1, position, id) -> {
            stockLineList.remove(position);
            stockLineListViewAdapter.notifyDataSetChanged();
            return false;
        });
        stockLineListViewAdapter = new StockLineListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(stockLineListViewAdapter);
        binding.btnOk.setOnClickListener(v -> {
            pushData();
        });

        in_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "in_stock_flag");
        box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");

        binding.tvScanTips.setOnClickListener(view->{
            if(i == 0){
                receiverTask("RK_0909001");
                i ++;
                return;
            }
            if(i == 1){
                receiverTask("Box0002");
                i ++;
                return;
            }
            if(i == 2){
                receiverTask("01200102633");
                i=0;
            }
        });
    }

    private void initView(){
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(view -> {
            finish();
        });
    }


    public void pushData(){
        String inStockVal = binding.tvInCode.getText().toString();
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(StringUtils.isEmpty(inStockVal)){
            ToastUtils.showToast(context, "入库单号不能为空");
            return;
        }
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在上传");
        RequestParams params = httParams(Constant.STOCK_AUTO_ADD);
        params.addParameter("status", "0");
        params.addParameter("erpInstockCode", inStockVal);
        params.addParameter("rmsTaskInstockLineList", stockLineList);
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    ToastUtils.showToast(context, rs.getString("msg"));
                    if (rs.getInt("code") == 200) {
                        new Handler().postDelayed(()->{
                            setResult(RESULT_OK);
                            finish();
                        }, 100);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockInNewActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                progress.close();
            }

            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    public void getBoxByBoxCode(String boxCode) throws Throwable {
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框编码不能为空");
            return;
        }
        RequestParams params = httParams(Constant.BOX_VIEW);
        params.addParameter("boxCode", boxCode);
        try {
            JSONObject rs = x.http().getSync(params, JSONObject.class);
            parserItem(rs);
        }catch (Throwable ex){
            ex.printStackTrace();
            throw ex;
        }
    }

    private void parserItem(JSONObject rs) throws Exception {
        mylog.info(rs.toString());
        try {
            ToastUtils.showToast(context, rs.getString("msg"));
            if (rs.getInt("code") == 200 && rs.has("data")) {
                JSONObject data = rs.getJSONObject("data");
                ItemModel itemModel = new Gson().fromJson(data.toString(), ItemModel.class);
                stockLineModel.setBoxCode(itemModel.getBoxCode());
                stockLineModel.setItemCode(itemModel.getItemCode());
                stockLineModel.setItemName(itemModel.getItemName());
                stockLineModel.setSpecification(itemModel.getSpecification());
                stockLineModel.setUnitOfMeasure(itemModel.getUnitOfMeasure());
            }else{
                throw new Exception(rs.getString("msg"));
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private void registerReceiver() {
        if (mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            if(Constant.MODEL.contains("ET")) {
                filter.addAction(ET_SCAN_ACTION);
            }
            registerReceiver(mReceiver, filter);
        }
    }

    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        try {
            if(popupWindow2!=null && popupWindow2.isShowing()){
//                saveBoxItem();
            }else{
                if(barcode.startsWith(in_stock_flag)){
                    binding.tvInCode.setText(barcode);
                }else if(barcode.startsWith(box_flag)){
                    stockLineModel = new StockLineModel();
                    stockLineModel.setBoxCode(barcode);
                    getBoxByBoxCode(barcode);
                    boolean rs = isExist(barcode);
                    if(!rs){
                        openItem();
                    }
                }else{
                    binding.tvScanTips.setText("无效码");
                }
            }
        }catch (Throwable ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    private void saveBoxItem(){
        String boxCode = et_boxCode.getText().toString();
        String qty = et_qty.getText().toString();
        if(StringUtils.isEmpty(boxCode)) {
            ToastUtils.showToast(this, "料框码不能为空");
            return;
        }
        if(StringUtils.isEmpty(qty)) {
            ToastUtils.showToast(this, "入库数量不能为空");
            return;
        }
        if(isExist(boxCode)){
            ToastUtils.showToast(this, "已存在相同的料框号");
            return;
        }
        stockLineModel.setBoxCode(boxCode);
        stockLineModel.setQuantity(qty);
        stockLineList.add(0, stockLineModel);
        stockLineListViewAdapter.notifyDataSetChanged();
        if(popupWindow2!=null){
            popupWindow2.dismiss();
        }
    }

    private void openItem(){
        View view = binding.getRoot().getRootView();
        View popup_item_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_item,null);
        et_itemCode = popup_item_view.findViewById(R.id.et_itemCode);
        et_itemCode.setText(stockLineModel.getItemName());
        et_boxCode = popup_item_view.findViewById(R.id.et_boxCode);
        et_boxCode.setText(stockLineModel.getBoxCode());
        bt_ok = popup_item_view.findViewById(R.id.bt_ok);
        et_qty = popup_item_view.findViewById(R.id.et_qty);
        bt_ok.setOnClickListener(v->{
            saveBoxItem();
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow2 = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow2.setContentView(popup_item_view);
        popupWindow2.setOutsideTouchable(true);
        popupWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow2.setFocusable(true);
        popupWindow2.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popupWindow2.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private boolean isExist(String boxCode){
        for (StockLineModel stockLineModel :stockLineList){
            if(stockLineModel.getBoxCode().equals(boxCode)){
                ToastUtils.showToast(this, "料框正在使用");
                return true;
            }
        }
        return false;
    }


    @Override
    protected String getCommonTopTitle() {
        return "新增入库";
    }

    @Override
    protected int getCommonTopICO() {
        return 0;
    }

}