package com.ygtx.emcs.activity;

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

import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockChangeItemViewAdapter;
import com.ygtx.emcs.activity.adapter.StockItemViewAdapter;
import com.ygtx.emcs.activity.model.BoxCodeModel;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.MaterialStockModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.comm.Res;
import com.ygtx.emcs.databinding.YgtxStockChangeBinding;
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.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


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

    private YgtxStockChangeBinding binding;
    private Context context;
    private StockChangeItemViewAdapter stockChangeItemViewAdapter;
    private ArrayList<MaterialStockModel> materialStockModels = new ArrayList<>();
    private String box_flag;
    private MaterialStockModel materialStockModel;
    private String boxCode;
    private Button submit;
    private String from;
    private String srcArea;
//    private BoxCodeModel srcBox;
    private BoxCodeModel tarBox;

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

    private void initData(){
        box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");
        if(StringUtils.isEmpty(box_flag)){
            ToastUtils.showToast(context, "请设置料框码的标识");
            finish();
        }
        boxCode = getParamString("boxCode");
        from = getParamString("from");
        if(!StringUtils.isEmpty(boxCode)){
            binding.tvSrcCode.setText(boxCode);
            loadErpTask(boxCode);
        }
        if("1".equals(from)){
            binding.tvSrcCode.setEnabled(false);
        }
        stockChangeItemViewAdapter = new StockChangeItemViewAdapter(materialStockModels, context);
        binding.lvProduct.setAdapter(stockChangeItemViewAdapter);
        binding.lvProduct.setOnItemClickListener((parent, view, position, id) -> {
            materialStockModel = materialStockModels.get(position);
            Long selId = materialStockModel.getMaterialStockId();
            if("1".equals(materialStockModel.getSel())){
                materialStockModel.setSel("0");
                materialStockModel = null;
            }else{
                materialStockModel.setSel("1");
            }
            materialStockModels.forEach(item->{
                if(!item.getMaterialStockId().equals(selId)){
                    item.setSel("0");
                }
            });
            stockChangeItemViewAdapter.notifyDataSetChanged();
        });
//        binding.tvSrcCode.setOnClickListener(view->{
//            receiverTask("BOX000026");
//        });
//        binding.tvTargetCode.setOnClickListener(view->{
//            receiverTask("BOX000028");
//        });
    }

    private void initView(){
        ImageView back = findViewById(R.id.c_iv_common_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(view -> {
            finish();
        });
        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 -> {
            String srcCode = binding.tvSrcCode.getText().toString();
            if(srcCode.startsWith(box_flag)){
                loadSrcBox(srcCode, 1);
            }else{
                sendChange();
            }
        });
        binding.btnFrom.setOnClickListener(v->{
            String srcCode = binding.tvSrcCode.getText().toString();
            if(!StringUtils.isEmpty(srcCode)){
                loadErpTask(srcCode);
            }
        });

        binding.tvTargetCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                String val = s.toString();
                if(val.startsWith(box_flag)){
                    binding.llTargetArea.setVisibility(View.VISIBLE);
                    if(val.length() > 8){
                        loadBox(val, false);
                    }
                }else{
                    binding.llTargetArea.setVisibility(View.GONE);
                }
            }
        });

        binding.btnTo.setOnClickListener(v->{
            String tarCode = binding.tvTargetCode.getText().toString();
            if(!StringUtils.isEmpty(tarCode)){
                if(tarCode.startsWith(box_flag)){
                    binding.llTargetArea.setVisibility(View.VISIBLE);
                    loadBox(tarCode, true);
                }else{
                    binding.llTargetArea.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);
        String srcCode = binding.tvSrcCode.getText().toString();
        String tarCode = binding.tvTargetCode.getText().toString();
        if(!barcode.startsWith(box_flag)
                && !barcode.startsWith(AUTO_KEY)
                && !barcode.startsWith(HAND_KEY)){
            return;
        }
        if(binding.llTargetArea.getVisibility()==View.VISIBLE
                &&!StringUtils.isEmpty(srcCode)
                &&!StringUtils.isEmpty(tarCode)){
            if(barcode.startsWith(AUTO_KEY) || barcode.startsWith(HAND_KEY)){
                binding.tvTargetArea.setText(barcode);
                return;
            }
        }

        if(StringUtils.isEmpty(srcCode)
                ||!StringUtils.isEmpty(tarCode)){
            binding.tvSrcCode.setText(barcode);
            loadErpTask(barcode);
        }else if(StringUtils.isEmpty(tarCode)){
            binding.tvTargetCode.setText(barcode);
            if(barcode.startsWith(box_flag)){
                binding.llTargetArea.setVisibility(View.VISIBLE);
                loadBox(barcode, true);
            }else{
                binding.tvTargetArea.setText("");
                binding.llTargetArea.setVisibility(View.GONE);
            }
        }
    }

    private void loadErpTask(String searchCode) {
        if(StringUtils.isEmpty(searchCode)){
            searchCode = binding.tvSrcCode.getText().toString();
        }
        if(StringUtils.isEmpty(searchCode)){
            ToastUtils.showToast(context, "库位号不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.STOCK_LIST_STOCK);
        params.addBodyParameter("itemCode", searchCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    materialStockModels.clear();
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<MaterialStockModel>>() {}.getType();
                        List<MaterialStockModel> stockModels = new Gson().fromJson(rs.get("data").toString(), rds);
                        materialStockModels.addAll(stockModels);
                        stockChangeItemViewAdapter.notifyDataSetChanged();
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    if(materialStockModels.size() == 0){
                        binding.lvProduct.setVisibility(View.GONE);
                        binding.tvEmpty.setVisibility(View.VISIBLE);
                    }else{
                        binding.lvProduct.setVisibility(View.VISIBLE);
                        binding.tvEmpty.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

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

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

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

    public void loadBox(String boxCode, boolean isShow){
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框号不能为空");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        if(isShow) {
            myProgress.show(context, "提示", "正在加载");
        }
        RequestParams params = httParams(Constant.BOX_INFO);
        params.addBodyParameter("boxCode", boxCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        tarBox = new Gson().fromJson(rs.get("data").toString(), BoxCodeModel.class);
                        binding.tvTargetArea.setText(tarBox.getAreaCode());
                        stockChangeItemViewAdapter.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(StockChangeActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    public void loadSrcBox(String boxCode, int type){
        if(StringUtils.isEmpty(boxCode)){
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.BOX_INFO);
        params.addBodyParameter("boxCode", boxCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        BoxCodeModel srcBox = new Gson().fromJson(rs.get("data").toString(), BoxCodeModel.class);
                        srcArea = srcBox.getAreaCode();
                        if(type == 1){
                            sendChange();
                        }
                    }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(StockChangeActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    public void sendChange(){
        String srcCode = binding.tvSrcCode.getText().toString();
        String tarCode = binding.tvTargetCode.getText().toString();
        String tarArea = binding.tvTargetArea.getText().toString();
        if(StringUtils.isEmpty(srcCode)){
            ToastUtils.showToast(context, "来源位置不能为空");
            return;
        }
        if(StringUtils.isEmpty(tarCode)){
            ToastUtils.showToast(context, "目标位置不能为空");
            return;
        }
        Optional<MaterialStockModel> optional = materialStockModels.stream().filter(item->"1".equals(item.getSel())).findFirst();
        optional.ifPresent(stockModel -> materialStockModel = stockModel);
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在提交数据");
        RequestParams params = httParams(Constant.CHANGE_BOX_AREA);
        if(srcCode.startsWith(box_flag)){
            params.addBodyParameter("boxCodeOld", srcCode);
            if(!StringUtils.isEmpty(srcArea)){
                params.addBodyParameter("areaCodeOld", srcArea);
            }
        }else{
            params.addBodyParameter("areaCodeOld", srcCode);
        }
        if(tarCode.startsWith(box_flag)){
            params.addBodyParameter("boxCodeNew", tarCode);
            params.addBodyParameter("areaCodeNew", tarArea);
        }else{
            params.addBodyParameter("areaCodeNew", tarCode);
        }
        if(materialStockModel!=null){
            params.addBodyParameter("materialStockId", materialStockModel.getMaterialStockId().toString());
        }
        params.addBodyParameter("updateBy", 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) {
                        loadErpTask(null);
                        new Handler().postDelayed(()->{
                            EventMessage message = new EventMessage(4, "刷新出库单明细");
                            EventBus.getDefault().post(message);
                        }, 100);
                        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();
                }finally {
                    myProgress.close();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockChangeActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    @Override
    protected String getCommonTopTitle() {
        return "物料整理";
    }

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

}