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.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.model.AreaModel;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.StockLineAreaModel;
import com.ygtx.emcs.activity.model.StockLineModel;
import com.ygtx.emcs.comm.BaseActivity;
import com.ygtx.emcs.comm.CacheService;
import com.ygtx.emcs.comm.Res;
import com.ygtx.emcs.databinding.YgtxBindItemBinding;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.DateUtil;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


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

    private YgtxBindItemBinding binding;
    private Context context;
    private List<View> itemAreaView = new ArrayList<>();
    private StockLineModel lineModel;
    private String erpInstockCode;
    private Button submit;
    private BigDecimal totalQty;
    private String box_flag;
    private AreaModel areaModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = YgtxBindItemBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        context = this;
        if(Constant.user == null){
            ToastUtils.showToast(context, "请先登录");
            finish();
        }
        registerReceiver();
        initCommonTop2();
        initView();
        initData();
    }

    private void initData(){
        lineModel = (StockLineModel)getParamSerializable("stockLine");
        erpInstockCode = getParamString("erpInstockCode");
        binding.etItemCode.setText(lineModel.getItemCode());
        binding.etItemName.setText(lineModel.getItemName());
        binding.tvQty.setText(lineModel.getQuantity());
        binding.etItemSpec.setText(lineModel.getSpecification());
        binding.etBatch.setText(lineModel.getBatchCode());
        totalQty = new BigDecimal(lineModel.getQuantity());
        box_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "box_flag");
        if(StringUtils.isEmpty(box_flag)){
            ToastUtils.showToast(context, "请设置料框码的标识");
            finish();
        }

        if(lineModel.getLineId()!=null){
            searchLineTask(lineModel.getLineId());
        }else{
            searchEmptyArea();
        }

        if("1".equals(lineModel.getAutomatic())){
            submit.setText("绑定");
            binding.btAdd.setVisibility(View.GONE);
        }else{
            binding.btAdd.setOnClickListener(v -> {
                addAreaItem();
            });
        }

        if("2".equals(lineModel.getStatus())){
            submit.setVisibility(View.GONE);
            binding.btAdd.setVisibility(View.GONE);
            binding.etBatch.setEnabled(false);
            binding.etBatch.setTextColor(Color.BLUE);
        }else if(StringUtils.isEmpty(lineModel.getBatchCode())){
            getBatchCode(lineModel.getItemCode(), binding.etBatch);
        }
        binding.etItemName.setOnClickListener(view->{
            Bundle bundle = new Bundle();
            bundle.putString("areaCode", binding.etItemCode.getText().toString());
            bundle.putString("from", "1");
            toActivity(StockItemActivity.class, bundle);
        });
// ========================test========================
//        binding.etItemName.setOnClickListener(v->{
//            receiverTask("B0007");
//        });
//        binding.etItemCode.setOnClickListener(v->{
//            receiverTask("BOX000008");
//        });
// ========================test========================
    }

    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 -> {
            if("1".equals(lineModel.getAutomatic())){
                bindAutoLine("update");
            }else{
                String areaValue = getItemAreaValue();
                if(StringUtils.isEmpty(areaValue)){
                    ToastUtils.showToast(context, "请扫库位码并输入数量");
                    return;
                }
                saveLineArea(areaValue);
            }
        });
    }

    private View addAreaItem(){
        LayoutInflater inflater = LayoutInflater.from(this);
        View areaView = inflater.inflate(R.layout.ygtx_bind_item_area, null);
        areaView.findViewById(R.id.iv_del).setOnClickListener(v1 -> {
            binding.llBindArea.removeView(areaView);
            itemAreaView.remove(areaView);
        });
        binding.llBindArea.addView(areaView);
        itemAreaView.add(areaView);
        return areaView;
    }

    private void addFirst(){
        LayoutInflater inflater = LayoutInflater.from(this);
        View areaView = inflater.inflate(R.layout.ygtx_bind_item_area, null);
        ImageView del = areaView.findViewById(R.id.iv_del);
        EditText areaCodeET = areaView.findViewById(R.id.et_areaCode);
        TextView areaCodeTV = areaView.findViewById(R.id.tv_areaCode);
        EditText boxCode =areaView.findViewById(R.id.et_boxCode);
        TextView boxCodeTV = areaView.findViewById(R.id.tv_box_code);
        EditText qty = areaView.findViewById(R.id.et_qty);
        if("false".equals(box_flag)){
            boxCodeTV.setVisibility(View.GONE);
            boxCode.setVisibility(View.GONE);
        }
        if("1".equals(lineModel.getAutomatic())){
            areaCodeET.setVisibility(View.GONE);
            areaCodeTV.setVisibility(View.GONE);
            boxCode.setText(lineModel.getBoxCode());
            qty.setText(lineModel.getQuantity());
            if(StringUtils.isEmpty(lineModel.getBoxCode())){
                del.setVisibility(View.GONE);
            }else{
                del.setVisibility(View.VISIBLE);
            }
        }
        if("2".equals(lineModel.getStatus())){
            del.setVisibility(View.GONE);
            boxCode.setEnabled(false);
            qty.setEnabled(false);
            qty.setTextColor(Color.BLUE);
            boxCode.setTextColor(Color.BLUE);
        }
        //推荐库位，不能判断是否满
        if(areaModel!=null){
//            areaCodeET.setText(areaModel.getAreaCode());
        }
        del.setOnClickListener(v->{
            if("1".equals(lineModel.getAutomatic())){
                if(StringUtils.isEmpty(lineModel.getBoxCode())){
                    ToastUtils.showToast(context, "没有绑定料框");
                    return;
                }
                AlertDialog alert = new AlertDialog.Builder(StockInBindActivity.this)
                        .setTitle("提示")
                        .setMessage("确定撤消绑定吗?")
                        .setPositiveButton("确定",
                                (dialog, which) -> bindAutoLine("delete"))
                        .setNegativeButton("取消", null)
                        .setCancelable(true).create();
                alert.show();
            }else{
                binding.llBindArea.removeView(areaView);
                itemAreaView.remove(areaView);
            }
        });
        binding.llBindArea.addView(areaView);
        itemAreaView.add(areaView);
    }

    private void setItemAreaValue(List<StockLineAreaModel> stockLineAreaList){
        for (StockLineAreaModel lineAreaModel:stockLineAreaList){
            View areaView = addAreaItem();
            setItemValue(lineAreaModel, areaView);
        }
    }

    private void setItemValue(StockLineAreaModel lineAreaModel, View areaView){
        EditText qty = areaView.findViewById(R.id.et_qty);
        EditText areaCode = areaView.findViewById(R.id.et_areaCode);
        TextView areaCodeTV = areaView.findViewById(R.id.tv_areaCode);
        EditText boxCode =areaView.findViewById(R.id.et_boxCode);
        TextView boxCodeTV = areaView.findViewById(R.id.tv_box_code);
        ImageView del = areaView.findViewById(R.id.iv_del);
        if("false".equals(box_flag)){
            boxCodeTV.setVisibility(View.GONE);
            boxCode.setVisibility(View.GONE);
        }
        if("1".equals(lineModel.getAutomatic())){
            areaCode.setVisibility(View.GONE);
            areaCodeTV.setVisibility(View.GONE);
        }
        if("2".equals(lineModel.getStatus())){
            del.setVisibility(View.GONE);
            qty.setEnabled(false);
            areaCode.setEnabled(false);
            boxCode.setEnabled(false);
            qty.setTextColor(Color.BLUE);
            areaCode.setTextColor(Color.BLUE);
            boxCode.setTextColor(Color.BLUE);
        }
        qty.setText(lineAreaModel.getQuantity());
        areaCode.setText(lineAreaModel.getAreaCode());
        if(StringUtils.isEmpty(lineAreaModel.getBoxCode())){
            boxCode.setHint("无料框");
        }else{
            boxCode.setText(lineAreaModel.getBoxCode());
        }

    }

    private String getItemAreaValue(){
        StringBuilder val = new StringBuilder();
        for (View view:itemAreaView){
            EditText qtyET = view.findViewById(R.id.et_qty);
            String qty = qtyET.getText().toString();
            if(StringUtils.isEmpty(qty)){
                continue;
            }
            if(new BigDecimal(qty).compareTo(BigDecimal.ZERO) <= 0){
                continue;
            }
            EditText areaCode = view.findViewById(R.id.et_areaCode);
            EditText boxCode = view.findViewById(R.id.et_boxCode);
            val.append(",").append(areaCode.getText().toString())
                    .append("|").append(qty)
                    .append("|").append(boxCode.getText().toString());
        }
        return val.toString();
    }

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

    private void saveLineArea(String areaValue){
        BigDecimal inQty = calculateQty();
        if(inQty.compareTo(new BigDecimal(lineModel.getQuantity())) > 0){
            ToastUtils.showToast(context, "入库数量超过总量");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.SAVE_IN_STOCK_AREA);
        if(lineModel.getLineId()==null){
            ToastUtils.showToast(context, "入库单没有生成");
            return;
        }
        if(StringUtils.isEmpty(erpInstockCode)){
            ToastUtils.showToast(context, "入库单号不能为空");
            return;
        }
        String batchCode = binding.etBatch.getText().toString();
        if(StringUtils.isEmpty(batchCode)){
            ToastUtils.showToast(context, "批次号不能为空");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在提交数据");
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("erpInstockCode", erpInstockCode);
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        params.addBodyParameter("batchCode", batchCode);
        params.addBodyParameter("areaValue", areaValue);
        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) {
                        new Handler().postDelayed(()->{
                            EventMessage message = new EventMessage(2, erpInstockCode);
                            EventBus.getDefault().post(message);
                            finish();
                        }, 100);
                    }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(StockInBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void bindAutoLine(String opType){
        String boxCode = getBoxCode();
        if(StringUtils.isEmpty(boxCode)){
            ToastUtils.showToast(context, "料框不能为空");
            return;
        }
        BigDecimal inQty = calculateQty();
        if(inQty.compareTo(new BigDecimal(lineModel.getQuantity())) > 0){
            ToastUtils.showToast(context, "入库数量超过总量");
            return;
        }
        if(Constant.user==null || Constant.user.getUserId() == null){
            ToastUtils.showToast(context, "请先登录");
            return;
        }
        RequestParams params = httParams(Constant.BIND_IN_STOCK);
        if(lineModel.getLineId()==null){
            ToastUtils.showToast(context, "入库单没有生成");
            return;
        }
        if(StringUtils.isEmpty(erpInstockCode)){
            ToastUtils.showToast(context, "入库单号不能为空");
            return;
        }
        String batchCode = binding.etBatch.getText().toString();
        if(StringUtils.isEmpty(batchCode)){
            ToastUtils.showToast(context, "批次号不能为空");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在提交数据");
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("instockId", lineModel.getInstockId().toString());
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        params.addBodyParameter("itemName", lineModel.getItemName());
        params.addBodyParameter("itemId", lineModel.getItemId().toString());
        params.addBodyParameter("specification", lineModel.getSpecification());
        params.addBodyParameter("unitOfMeasure", lineModel.getUnitOfMeasure());
        params.addBodyParameter("automatic", lineModel.getAutomatic());
        params.addBodyParameter("batchCode", batchCode);
        params.addBodyParameter("boxCode", boxCode);
        params.addBodyParameter("orderQuantity", lineModel.getOrderQuantity().toString());
        params.addBodyParameter("quantity", inQty.toString());
        params.addBodyParameter("operType", opType);
        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) {
                        new Handler().postDelayed(()->{
                            EventMessage message = new EventMessage(2, erpInstockCode);
                            EventBus.getDefault().post(message);
                            finish();
                        }, 100);
                    }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(StockInBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void getBatchCode(String itemCode, EditText batchEdit){
        RequestParams params = httParams(Constant.BATCH_CODE);
        params.addBodyParameter("itemCode", itemCode);
        params.addBodyParameter("batchDate", DateUtil.getCurrDate(Constant.DATE_FORMATE));
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        JSONObject data = rs.getJSONObject("data");
                        batchEdit.setText(data.getString("batchCode"));
                    }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(StockInBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    private void searchLineTask(Long lineId) {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在查询");
        RequestParams params = httParams(Constant.ERP_IN_STOCK_AREA_LIST);
        params.addBodyParameter("lineId", lineId.toString());
        params.addBodyParameter("pageNum", "1");
        params.addBodyParameter("pageSize", "100");
        params.addBodyParameter("orderByColumn", "create_time");
        params.addBodyParameter("isAsc", "desc");
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    List<StockLineAreaModel> stockLineAreaModels = new ArrayList<>();
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<StockLineAreaModel>>() {}.getType();
                        int total = rs.getInt("total");
                        if(total == 0){
                            mylog.info("没有记录");
                            searchEmptyArea();
                            return;
                        }
                        stockLineAreaModels = new Gson().fromJson(rs.get("rows").toString(), rds);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    if(stockLineAreaModels.size()> 0){
                        setItemAreaValue(stockLineAreaModels);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally {
                    myProgress.close();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockInBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void searchEmptyArea() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在查询");
        RequestParams params = httParams(Constant.EMPTY_AREA);
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        areaModel = new Gson().fromJson(rs.get("data").toString(), AreaModel.class);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    addFirst();
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally {
                    myProgress.close();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockInBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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


    @Override
    public void receiverTask(String barcode) {
        System.out.println("扫码：" + barcode);
        if("2".equals(lineModel.getStatus())){
            return;
        }
        if(barcode.startsWith(box_flag)){
            bindBoxCode(barcode);
        }else{
            bindAreaCode(barcode);
        }
    }

    private void bindBoxCode(String barcode){
        if(!itemAreaView.isEmpty()){
            View view = itemAreaView.get(itemAreaView.size() - 1);
            EditText boxCodeET = view.findViewById(R.id.et_boxCode);
            String boxCode = boxCodeET.getText().toString();
            if(boxCode.equals(barcode)){
                return;
            }
            boxCodeET.setText(barcode);
        }
    }

    private void bindAreaCode(String barcode){
        BigDecimal inQty = calculateQty();
        BigDecimal reQty = new BigDecimal(lineModel.getQuantity()).subtract(inQty);
        String total = reQty.toString();
        if(reQty.compareTo(BigDecimal.ZERO) <= 0){
            total = "0";
        }
        for (View view:itemAreaView){
            EditText areaCodeET = view.findViewById(R.id.et_areaCode);
            EditText qtyET = view.findViewById(R.id.et_qty);
            String areaCode = areaCodeET.getText().toString();
            if(areaCode.equals(barcode)){
                return;
            }
            if(StringUtils.isEmpty(areaCode)){
                areaCodeET.setText(barcode);
                qtyET.setText(total);
                return;
            }
        }
        View areaView = addAreaItem();
        EditText areaCode = areaView.findViewById(R.id.et_areaCode);
        EditText qtyET = areaView.findViewById(R.id.et_qty);
        qtyET.setText(total);
        areaCode.setText(barcode);
    }

    private BigDecimal calculateQty(){
        BigDecimal inQty = BigDecimal.ZERO;
        for (View view:itemAreaView){
            EditText qtyET = view.findViewById(R.id.et_qty);
            String qty = qtyET.getText().toString();
            if(StringUtils.isEmpty(qty)){
                continue;
            }
            inQty = inQty.add(new BigDecimal(qty));
        }
        return inQty;
    }

    private String getBoxCode(){
        String boxCode = "";
        for (View view:itemAreaView){
            EditText boxCodeET = view.findViewById(R.id.et_boxCode);
            boxCode = boxCodeET.getText().toString();
        }
        return boxCode;
    }

    @Override
    protected String getCommonTopTitle() {
        return "绑定库位";
    }

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

}