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.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.BoxItemListViewAdapter;
import com.ygtx.emcs.activity.model.ItemModel;
import com.ygtx.emcs.activity.model.StockLineModel;
import com.ygtx.emcs.activity.model.StockModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.databinding.YgtxBoxBindBinding;
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 BoxBindActivity extends BaseActivity {
    public static Logger mylog =Logger.getLogger(BoxBindActivity.class);

    private YgtxBoxBindBinding binding;
    private Context context;
    private BoxItemListViewAdapter boxItemListViewAdapter;
    private ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private StockModel stockModel = new StockModel();
    private String box_flag;
    private EditText inputServer;
    private AlertDialog dialog;

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

    private void initData(){
        binding.lvProduct.setOnItemLongClickListener((parent, view1, position, id) -> {
            stockLineList.remove(position);
            boxItemListViewAdapter.notifyDataSetChanged();
            return false;
        });
        boxItemListViewAdapter = new BoxItemListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(boxItemListViewAdapter);
        binding.btnOk.setOnClickListener(v -> {
            pushData();
        });
        box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("Box0002");
//        });
//        binding.tvScanTips.setOnLongClickListener(view->{
//            receiverTask("090160008120");
//            return false;
//        });
        inputServer = new EditText(this);
    }

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

    private void closeBtn(){
        binding.btnOk.setBackgroundColor(Color.parseColor("#CCCCCC"));
        binding.btnOk.setEnabled(false);
    }

    public void pushData(){
        String boxCode = binding.tvBoxCode.getText().toString();
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框码不能为空");
            return;
        }
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在上传");
        RequestParams params = httParams(Constant.BOX_ADD);
        params.addParameter("boxCode", boxCode);
        params.addParameter("wmRmsBoxItemList", stockLineList);
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        ToastUtils.showToast(context, "绑定成功");
                        closeBtn();
                        stockLineList.clear();
                        binding.tvBoxCode.setText("");
                        boxItemListViewAdapter.notifyDataSetChanged();
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    public void getBoxByBoxCodeList(String boxCode) throws Throwable {
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框编码不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress progress = MyProgress.getInstance();
        progress.show(context, "提示", "正在查询");
        RequestParams params = httParams(Constant.BOX_LIST_VIEW);
        params.addParameter("boxCode", boxCode);
        try {
            x.http().get(params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject result) {
                    try {
                        parserItemList(result);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showToast(context, e.getMessage());
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    HttpsUtil.parserError(BoxBindActivity.this, ex);
                    mylog.error("请求异常：", ex);
                }
                @Override
                public void onCancelled(CancelledException cex) {
                    HttpsUtil.parserError(BoxBindActivity.this, cex);
                }
                @Override
                public void onFinished() {
                    progress.close();
                }
            });
        }catch (Throwable ex){
            ex.printStackTrace();
            throw ex;
        }
    }

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

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

    private void parserItemList(JSONObject rs) throws Exception {
        mylog.info(rs.toString());
        try {
            if (rs.getInt("code") == 200 && rs.has("data")) {
                JSONObject data = rs.getJSONObject("data");
                stockModel = new Gson().fromJson(data.toString(), StockModel.class);
                stockLineList.clear();
                stockLineList.addAll(stockModel.getWmRmsBoxItemList());
                boxItemListViewAdapter.notifyDataSetChanged();
            }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(barcode.startsWith(box_flag)){
                binding.tvBoxCode.setText(barcode);
                getBoxByBoxCodeList(barcode);
            }else{
                StockLineModel stockLineModel = getItemData(barcode);
                if(stockLineModel != null){
                    StockLineModel existStockLine = isExist(stockLineModel.getItemCode());
                    if(existStockLine != null){
                        openQty(stockLineModel, existStockLine);
                    }else if(stockLineList.size() > 0){
                        ToastUtils.showToast(context, "不同物料不能放在一个料框");
                    }else{
                        openQty(stockLineModel, null);
                    }
                }
            }
        }catch (Throwable ex){
            mylog.error("任务发送异常：", ex);
            ToastUtils.showToast(context, "发送异常");
        }
    }

    private void openQty(StockLineModel stockLineModel, StockLineModel existStockLine){
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("请输入数量")
                .setIcon(R.mipmap.logo)
                .setView(inputServer)
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(getString(R.string.sure), null);
        if(dialog==null){
            dialog = builder.show();
        }else{
            dialog.show();
        }
        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v){
                String qty = inputServer.getText().toString();
                if(StringUtils.isEmpty(qty)){
                    ToastUtils.showToast(context, "请输入数量");
                    return;
                }
                if(existStockLine != null){
                    BigDecimal existQty = new BigDecimal(existStockLine.getItemQuantity());
                    BigDecimal currentQty = new BigDecimal(qty);
                    currentQty = existQty.add(currentQty);
                    stockLineModel.setItemQuantity(currentQty.toString());
                    stockLineList.clear();
                }else{
                    stockLineModel.setItemQuantity(qty);
                }
                stockLineList.add(0, stockLineModel);
                boxItemListViewAdapter.notifyDataSetChanged();
                binding.btnOk.setBackgroundColor(Color.parseColor("#03A9E4"));
                binding.btnOk.setEnabled(true);
                inputServer.setText("");
                dialog.dismiss();
            }
        });
    }


    private StockLineModel isExist(String itemCode){
        for (StockLineModel stockLineModel :stockLineList){
            if(stockLineModel.getItemCode().equals(itemCode)){
                return stockLineModel;
            }
        }
        return null;
    }


    @Override
    protected String getCommonTopTitle() {
        return "物料绑定";
    }

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

}