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.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockOutListViewAdapter;
import com.ygtx.emcs.activity.model.EventMessage;
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.comm.Res;
import com.ygtx.emcs.databinding.YgtxStockOutAddBinding;
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.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
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;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


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

    private YgtxStockOutAddBinding binding;
    private Context context;
    private StockOutListViewAdapter stockLineListViewAdapter;
    private final ArrayList<StockLineModel> stockLineList = new ArrayList<>();
    private String out_stock_flag;
    private String box_flag;
    private String from;
    private StockModel stockModel;
    private String erpOutstockCode;
    private boolean isSubmit = true;
    private final Handler handler = new Handler();
    private Runnable runnable;
    private StockLineModel selItem;

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

    private void reloadData(){
        runnable = () -> {
            if(Constant.user != null && !StringUtils.isEmpty(erpOutstockCode)) {
                loadErpTask(0);
            }
            reloadData();
        };
        handler.postDelayed(runnable, 3000);
    }


    private void initData(){
        erpOutstockCode = getParamString("erpOutstockCode");
        if(!StringUtils.isEmpty(erpOutstockCode)){
            binding.tvOutCode.setText(erpOutstockCode);
            loadErpTask(1);
        }
        stockLineListViewAdapter = new StockOutListViewAdapter(stockLineList, context);
        binding.lvProduct.setAdapter(stockLineListViewAdapter);
        binding.lvProduct.setOnItemClickListener((parent, view, position, id) -> {
            StockLineModel stockLineModel = stockLineList.get(position);
            stockLineModel.setCkType(stockModel.getCkType());
            if("1".equals(from) && !"2".equals(stockLineModel.getStatus())){
                return;
            }
            stockOut(stockLineModel);
        });
        binding.lvProduct.setOnItemLongClickListener((parent, view, position, id) -> {
            StockLineModel stockLineModel = stockLineList.get(position);
            if("1".equals(stockLineModel.getStatus())){
                AlertDialog alert = new AlertDialog.Builder(StockOutNewActivity.this)
                        .setTitle("提示")
                        .setMessage("确定撤消任务吗?")
                        .setPositiveButton("确定",
                                (dialog, which) -> cancelSend(stockLineModel))
                        .setNegativeButton("取消", null)
                        .setCancelable(true).create();
                alert.show();
            }
            return true;
        });

        out_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "out_stock_flag");
        if(StringUtils.isEmpty(out_stock_flag)){
            ToastUtils.showToast(context, "请设置出库单编码的标识");
            finish();
        }
        box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");
        if(StringUtils.isEmpty(box_flag)){
            ToastUtils.showToast(context, "请设置料框码的标识");
            finish();
        }
        reloadData();
// ========================test========================
//        binding.tvScanTips.setOnClickListener(view->{
//            receiverTask("CK_20250429004");
//        });
//        binding.tvOutCode.setOnClickListener(view->{
//            receiverTask("BOX000008");
//        });
//        binding.tvOutCode.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                receiverTask("BOX000020");
//                return true;
//            }
//        });
// ========================test========================
    }

    private void stockOut(StockLineModel stockLineModel){
        Bundle bundle = new Bundle();
        bundle.putString("erpOutstockCode", stockModel.getErpOutstockCode());
        bundle.putSerializable("stockLine", stockLineModel);
        bundle.putSerializable("from", from);
        toActivity(StockOutBindActivity.class, bundle);
    }

    private void initView(){
        from = getParamString("from");
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(view -> {
            finish();
        });
        if("1".equals(from)){
            binding.tvScanTips.setVisibility(View.GONE);
            binding.btnOk.setVisibility(View.GONE);
            Button submit = findViewById(R.id.c_iv_common_submit);
            submit.setBackgroundColor(Res.getColor("transparent"));
            submit.setTextColor(Res.getColor("white"));
            submit.setVisibility(View.VISIBLE);
            submit.setText("同步");
            submit.setOnClickListener(view -> {
                if(stockModel!=null) {
                    syncErp();
                }
            });
        }
        if(!"1".equals(from)) {
            Button submit = findViewById(R.id.c_iv_common_submit);
            submit.setBackgroundColor(Res.getColor("transparent"));
            submit.setTextColor(Res.getColor("white"));
            submit.setVisibility(View.VISIBLE);
            submit.setText("出库记录");
            submit.setOnClickListener(view -> {
                toActivity(StockOutActivity.class);
            });
        }
    }

    private void initLoadData(){
        boolean isAuto = stockLineList.stream().anyMatch(item->"1".equals(item.getAutomatic()));
        if(isAuto&&!"2".equals(stockModel.getStatus())){
            binding.btnOk.setVisibility(View.VISIBLE);
            binding.btnOk.setOnClickListener(v->{
                sendStockOut();
            });
        }else{
            binding.btnOk.setVisibility(View.GONE);
        }
    }

    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);
        if("1".equals(from)) {
            return;
        }
        String inCode = binding.tvOutCode.getText().toString();
        if(barcode.startsWith(out_stock_flag)){
            try {
                binding.tvOutCode.setText(barcode);
                erpOutstockCode = barcode;
                loadErpTask(1);
            }catch (Throwable ex){
                mylog.error("任务发送异常：", ex);
                ToastUtils.showToast(context, "发送异常");
            }
        }else if(barcode.startsWith(box_flag)){
            selItem = null;
            findCheckItem(barcode);
            if(selItem == null){
                ToastUtils.showToast(context, barcode + "没有可以核对的记录");
                return;
            }
            checkOutLine(selItem);
        }else{
            if(StringUtils.isEmpty(inCode)){
                ToastUtils.showToast(context, "请扫出库单号");
                return;
            }
            selItem = null;
            findItemCode(barcode);
            checkItem(barcode);
        }
    }

    private void findCheckItem(String barcode){
        int i;
        for(i=0;i<stockLineList.size();i++){
            StockLineModel item = stockLineList.get(i);
            stockLineList.forEach(lineItem->lineItem.setSel("0"));
            if(barcode.equals(item.getBoxCode())
                    &&"1".equals(item.getAutomatic())
                    &&"2".equals(item.getStatus())
                    &&!"1".equals(item.getOutCheck())){
                selItem = item;
                selItem.setSel("1");
                break;
            }
        }
        stockLineListViewAdapter.notifyDataSetChanged();
        if(selItem!=null){
            binding.lvProduct.smoothScrollToPosition(i, 3);
            binding.lvProduct.smoothScrollToPositionFromTop(i, 0, 500);
        }
    }

    private void findItemCode(String barcode){
        int i;
        for(i=0;i<stockLineList.size();i++){
            StockLineModel item = stockLineList.get(i);
            stockLineList.forEach(lineItem->lineItem.setSel("0"));
            if(barcode.equals(item.getItemCode())){
                selItem = item;
                selItem.setSel("1");
                break;
            }
        }
        stockLineListViewAdapter.notifyDataSetChanged();
        if(selItem!=null){
            binding.lvProduct.smoothScrollToPosition(i, 3);
            binding.lvProduct.smoothScrollToPositionFromTop(i, 0, 500);
        }
    }

    private void findBoxCode(String barcode){
        int i;
        boolean isScroll = false;
        for(i=0;i<stockLineList.size();i++){
            StockLineModel item = stockLineList.get(i);
            stockLineList.forEach(lineItem->lineItem.setSel("0"));
            if(barcode.equals(item.getBoxCode())){
                selItem = item;
                selItem.setSel("1");
                isScroll = true;
                break;
            }
        }
        stockLineListViewAdapter.notifyDataSetChanged();
        if(selItem!=null && isScroll){
            binding.lvProduct.smoothScrollToPosition(i, 3);
            binding.lvProduct.smoothScrollToPositionFromTop(i, 0, 500);
        }
    }

    private void checkItem(String barcode) {
        Optional<StockLineModel> optionalStockLineModel1 = stockLineList.stream().filter(item -> item.getItemCode().equals(barcode)
                && "0".equals(item.getStatus())).findFirst();
        Optional<StockLineModel> optionalStockLineModel = stockLineList.stream().filter(item -> item.getItemCode().equals(barcode)).findFirst();
        if (optionalStockLineModel1.isPresent()) {
            stockOut(optionalStockLineModel1.get());
            return;
        }
        if (optionalStockLineModel.isPresent()) {
            stockOut(optionalStockLineModel.get());
            return;
        }
        ToastUtils.showToast(context, "出库单不存在" + barcode + "物品");
    }

    private void loadErpTask(int show) {
        if(StringUtils.isEmpty(erpOutstockCode)){
            erpOutstockCode = binding.tvOutCode.getText().toString();
        }
        if(StringUtils.isEmpty(erpOutstockCode)){
            ToastUtils.showToast(context, "出库单号不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(!isSubmit){
            return;
        }
        isSubmit = false;
        MyProgress myProgress = MyProgress.getInstance();
        if(show == 1) {
            myProgress.show(context, "提示", "正在加载");
        }
        RequestParams params = httParams(Constant.ERP_OUT_STOCK);
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
//        params.addBodyParameter("isAutomatic", "0");
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    stockLineList.clear();
                    if (rs.getInt("code") == 200) {
                        stockModel = new Gson().fromJson(rs.get("data").toString(), StockModel.class);
                        if(stockModel.getRmsTaskOutstockLineList()!=null) {
                            stockLineList.addAll(stockModel.getRmsTaskOutstockLineList());
                            if(selItem!=null){
                                findBoxCode(selItem.getBoxCode());
                            }
                        }
                        initLoadData();
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    stockLineListViewAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                    mylog.error("回调异常:", e);
                }
            }

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

            @Override
            public void onFinished() {
                myProgress.close();
                isSubmit = true;
            }

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

    private void syncErp(){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.SYNC_OUT_STOCK);
        if(stockModel==null){
//            ToastUtils.showToast(context, "出库单不存在");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        params.addBodyParameter("outstockId", stockModel.getOutstockId());
        params.addBodyParameter("operator", Constant.user.getLoginName());
        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) {
                        ToastUtils.showToast(context, "同步请求成功");
                    }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(StockOutNewActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void cancelSend(StockLineModel lineModel){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(lineModel==null){
            ToastUtils.showToast(context, "出库单物品");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.CANCEL_PUSH_LINE);
        params.addBodyParameter("outstockId", stockModel.getOutstockId());
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("operator", Constant.user.getLoginName());
        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, rs.getString("msg"));
                        loadErpTask(1);
                    }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(StockOutNewActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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


    private void checkOutLine(StockLineModel lineModel){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(lineModel == null){
            ToastUtils.showToast(context, "找不到核对的记录");
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.CHECK_OUT_LINE);
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("outstockId", stockModel.getOutstockId());
        params.addBodyParameter("boxCode", lineModel.getBoxCode());
        params.addBodyParameter("itemId", lineModel.getItemId().toString());
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        params.addBodyParameter("quantity", lineModel.getQuantity());
        params.addBodyParameter("operator", Constant.user.getLoginName());
        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) {
                        ToastUtils.showToast(context, "核对成功");
                        loadErpTask(1);
                    }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(StockOutNewActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void sendStockOut(){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        if(stockModel.getOutstockId()==null){
            ToastUtils.showToast(context, "出库单没有生成");
            return;
        }
        binding.btnOk.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.SEND_STOCK_OUT);
        params.addBodyParameter("outstockId", stockModel.getOutstockId());
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        params.addBodyParameter("fromType", "0");
        params.addBodyParameter("taskType", "2");
        params.addBodyParameter("path", "/ckgl");
        params.addBodyParameter("outstockBatch", "1");
        params.addBodyParameter("operator", Constant.user.getLoginName());
        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, rs.getString("msg"));
                    }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(StockOutNewActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

            @Override
            public void onFinished() {
                myProgress.close();
                binding.btnOk.setEnabled(true);
            }

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

    public void setSel(List<StockLineModel> lineModels){
        if(selItem != null){
            Optional<StockLineModel> optional1 = lineModels.stream().filter(item->item.getItemId().equals(selItem.getItemId())).findFirst();
            if(optional1.isPresent()){
                StockLineModel sel = optional1.get();
                sel.setSel("1");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void onReceiveMsg(EventMessage message){
        if(message.getType() == 3){
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                if(StringUtils.isEmpty(erpOutstockCode)){
                    erpOutstockCode = message.getMessage();
                }
                if(!StringUtils.isEmpty(erpOutstockCode)) {
                    loadErpTask(1);
                }
            }, 1000);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getCommonTopTitle() {
        return "出库单信息";
    }

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

}