package com.ygtx.emcs.activity;

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

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.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
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.DictModel;
import com.ygtx.emcs.activity.model.EventMessage;
import com.ygtx.emcs.activity.model.MaterialStockModel;
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.Res;
import com.ygtx.emcs.databinding.YgtxBindItemBinding;
import com.ygtx.emcs.databinding.YgtxBindOutItemBinding;
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.HashMap;
import java.util.List;
import java.util.Map;


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

    private YgtxBindOutItemBinding binding;
    private Context context;
    private List<View> itemAreaView = new ArrayList<>();
    private StockLineModel lineModel;
    private String erpOutstockCode;
    private Button submit;
    private List<MaterialStockModel> materialStockModels = new ArrayList<>();
    private List<DictModel> dictModelList = new ArrayList<>();
    private BigDecimal totalQty;
    private PopupWindow popupWindow;
    private String fileName;

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

    private void initData(){
        lineModel = (StockLineModel)getParamSerializable("stockLine");
        erpOutstockCode = getParamString("erpOutstockCode");
        String from = getParamString("from");
//        if("1".equals(from)){
//            binding.llPrinter.setVisibility(View.GONE);
//        }
        binding.etItemCode.setText(lineModel.getItemCode());
        binding.etItemName.setText(lineModel.getItemName());
        binding.etItemSpec.setText(lineModel.getSpecification());
        binding.tvQty.setText(lineModel.getQuantity());
        if("2".equals(lineModel.getStatus())){
            submit.setVisibility(View.GONE);
            binding.btAdd.setVisibility(View.GONE);
//            binding.llPrinter.setVisibility(View.GONE);
            searchLineTask(lineModel.getLineId());
        }else{
            searchStock(lineModel.getItemCode());
            totalQty = new BigDecimal(lineModel.getQuantity());
        }
//        binding.etItemName.setOnClickListener(v->{
//            receiverTask("A0001");
//        });
//        binding.etItemCode.setOnClickListener(v->{
//            receiverTask("A0005");
//        });
    }

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

        binding.btAdd.setOnClickListener(v -> {
            addAreaItem();
        });

        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 -> {
            BigDecimal outOrderQty = calculateQty();
            if(outOrderQty.compareTo(totalQty) > 0){
                ToastUtils.showToast(context, "当前物品出库数量超过出库单数量");
                return;
            }
            if(outOrderQty.compareTo(totalQty) < 0){
                ToastUtils.showToast(context, "当前物品出库数量不足，不能出库");
                return;
            }
            String areaValue = getItemAreaValue();
            saveStockOut(areaValue);
        });

        binding.btnPrinter.setOnClickListener(v->{
            StockLineModel stockLineModel = new StockLineModel();
            stockLineModel.setLineId(lineModel.getLineId());
            String perBag = binding.etPerBag.getText().toString();
            if(StringUtils.isEmpty(perBag)){
                perBag = "1";
            }
            stockLineModel.setPerBag(new BigDecimal(perBag));
            printItem(stockLineModel);
        });

        binding.btnSelItem.setOnClickListener(this::selPrinterLabel);
    }

    private View addAreaItem(){
        LayoutInflater inflater = LayoutInflater.from(this);
        View areaView = inflater.inflate(R.layout.ygtx_bind_out_item_area, null);
        binding.llBindArea.addView(areaView);
        itemAreaView.add(areaView);
        return areaView;
    }

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

    private void setNewItemAreaValue(List<MaterialStockModel> materialStockModelList){
        for (MaterialStockModel lineAreaModel:materialStockModelList){
            if(StringUtils.isEmpty(lineAreaModel.getAreaCode())){
                continue;
            }
            View areaView = addAreaItem();
            setStockItemValue(lineAreaModel, areaView);
        }
    }

    private void setItemValue(StockLineAreaModel lineAreaModel, View areaView){
        EditText qty = areaView.findViewById(R.id.et_qty);
        TextView areaCode = areaView.findViewById(R.id.et_areaCode);
        TextView tv_batch_code = areaView.findViewById(R.id.tv_batch_code);
        TextView total = areaView.findViewById(R.id.tv_total);
        TextView stockTitle = areaView.findViewById(R.id.tv_stock_title);
        if("2".equals(lineModel.getStatus())){
            qty.setEnabled(false);
            stockTitle.setText("原库存:");
        }else{
            stockTitle.setText("库存:");
        }
        total.setText(lineAreaModel.getStockQuantity());
        areaCode.setText(lineAreaModel.getAreaCode());
        tv_batch_code.setText(lineAreaModel.getBatchCode());
        qty.setText(lineAreaModel.getQuantity());
    }

    private void setStockItemValue(MaterialStockModel stockModel, View areaView){
        EditText qty = areaView.findViewById(R.id.et_qty);
        TextView areaCode = areaView.findViewById(R.id.et_areaCode);
        TextView tv_batch_code = areaView.findViewById(R.id.tv_batch_code);
        TextView total = areaView.findViewById(R.id.tv_total);
        TextView stockTitle = areaView.findViewById(R.id.tv_stock_title);
        if("2".equals(lineModel.getStatus())){
            qty.setEnabled(false);
            stockTitle.setText("原库存:");
        }else{
            stockTitle.setText("库存:");
        }
        String quantity = stockModel.getQuantityOnhand().toString();
        total.setText(quantity);
        areaCode.setText(stockModel.getAreaCode());
        areaCode.setTag(stockModel.getMaterialStockId());
        tv_batch_code.setText(stockModel.getBatchCode());
        areaView.setTag(stockModel.getMaterialStockId());
    }

    private String getItemAreaValue(){
        StringBuilder val = new StringBuilder();
        String rs = null;
        for (View view:itemAreaView){
            EditText qty = view.findViewById(R.id.et_qty);
            String outQty = qty.getText().toString();
            if(StringUtils.isEmpty(outQty)){
                continue;
            }
            if(Double.parseDouble(outQty) <= 0){
                continue;
            }
            TextView total = view.findViewById(R.id.tv_total);
            TextView areaCode = view.findViewById(R.id.et_areaCode);
            val.append(",").append(areaCode.getText().toString())
                    .append("|")
                    .append(total.getText().toString())
                    .append("|")
                    .append(qty.getText().toString())
                    .append("|")
                    .append(areaCode.getTag());
        }
        if(val.length() > 0){
            rs = val.substring(1);
        }
        return rs;
    }

    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 saveStockOut(String areaValue){
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        RequestParams params = httParams(Constant.SAVE_OUT_STOCK_AREA);
        if(lineModel.getLineId()==null){
            ToastUtils.showToast(context, "出库单没有生成");
            return;
        }
        submit.setEnabled(false);
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        params.addBodyParameter("lineId", lineModel.getLineId().toString());
        params.addBodyParameter("erpOutstockCode", erpOutstockCode);
        params.addBodyParameter("itemCode", lineModel.getItemCode());
        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(3, "刷新出库单");
                            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();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.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 searchLineTask(Long lineId) {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.ERP_OUT_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("没有记录");
                            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();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void searchStock(String itemCode) {
       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", itemCode);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<MaterialStockModel>>() {}.getType();
                        materialStockModels = new Gson().fromJson(rs.get("data").toString(), rds);
                    }else if(rs.getInt("code") == 401){
                        ToastUtils.showToast(context, "会话过期");
                        logoutAuth(rs.getInt("code"));
                    }else{
                        ToastUtils.showToast(context, rs.getString("msg"));
                    }
                    if(materialStockModels.size()> 0){
                        setNewItemAreaValue(materialStockModels);
                        binding.tvNoStock.setVisibility(View.GONE);
                    }else{
                        binding.tvNoStock.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                HttpsUtil.parserError(StockOutBindActivity.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;
        }
        checkAreaCode(barcode);
    }

    private void checkAreaCode(String areaCode){
        if(materialStockModels.isEmpty()){
            return;
        }
        BigDecimal outOrderQty = calculateQty();
        if(outOrderQty.compareTo(totalQty) >= 0){
            ToastUtils.showToast(context, "当前出库数量超过出库单数量");
            return;
        }
        MaterialStockModel materialStockModel = getMaterialStock(areaCode);
        if(materialStockModel == null){
            ToastUtils.showToast(context, "该库位上没有需要的物品");
            return;
        }
        View areaView = getAreaView(materialStockModel.getMaterialStockId());
        if(areaView == null){
            ToastUtils.showToast(context, "库位码不可用");
            return;
        }
        BigDecimal stockQty = materialStockModel.getQuantityOnhand();
        String orderQty = totalQty.subtract(outOrderQty).toString();
        EditText qtyET = areaView.findViewById(R.id.et_qty);
        if(stockQty.compareTo(totalQty) == 0){
            qtyET.setText(orderQty);
        }
        else if(stockQty.compareTo(totalQty) > 0){
            qtyET.setText(orderQty);
        }else{
            String outStockQty = stockQty.toString();
            qtyET.setText(outStockQty);
        }
    }

    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 MaterialStockModel getMaterialStock(String areaCode){
        for (MaterialStockModel materialStockModel:materialStockModels){
           if(areaCode.equals(materialStockModel.getAreaCode())){
               return materialStockModel;
           }
        }
        return null;
    }

    private View getAreaView(Long materialId){
        for (View areaView:itemAreaView){
            if(materialId.equals(areaView.getTag())){
                return areaView;
            }
        }
        return null;
    }


    private void printItem(StockLineModel stockLineModel) {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在发送数据");
        RequestParams params = httParams(Constant.PRINTER_ITEM);
        params.addBodyParameter("lineId", stockLineModel.getLineId().toString());
        params.addBodyParameter("perBag", stockLineModel.getPerBag().toString());
        params.addBodyParameter("operator", Constant.user.getLoginName());
        params.addBodyParameter("fileName", fileName);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    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(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }

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

    private void searchItemLabel() {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        myProgress.show(context, "提示", "正在加载");
        RequestParams params = httParams(Constant.PRINTER_ITEM_SEL+"/" + PRINTER_ITEM_SEL_KEY);
        x.http().get(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject rs) {
                mylog.info(rs.toString());
                try {
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<DictModel>>() {}.getType();
                        dictModelList = new Gson().fromJson(rs.get("data").toString(), rds);
                        if(dictModelList.isEmpty()){
                            ToastUtils.showToast(context, "没有配置标签文件");
                            return;
                        }
                        if(StringUtils.isEmpty(fileName) && dictModelList.size()>0){
                            String label = dictModelList.get(0).getDictLabel();
                            if(label!=null && label.contains(".")){
                                label = label.split("\\.")[0];
                                binding.btnSelItem.setText(label);
                            }else{
                                binding.btnSelItem.setText(label);
                            }
                            fileName = dictModelList.get(0).getDictValue();
                        }
                    }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(StockOutBindActivity.this, ex);
                mylog.error("请求异常：", ex);
            }
            @Override
            public void onFinished() {
                myProgress.close();
            }
            @Override
            public void onCancelled(CancelledException arg0) {
                mylog.error("onRead:", arg0);
            }
        });
    }

    public void selPrinterLabel(View view){
        List<Map<String,String>> params = new ArrayList<>();
        if(!dictModelList.isEmpty()){
            dictModelList.forEach(item->{
                Map<String,String> param = new HashMap<>();
                param.put("name", item.getDictLabel());
                param.put("value", item.getDictValue());
                params.add(param);
            });
        }else{
            searchItemLabel();
        }
        View popup_list_view= LayoutInflater.from(context).inflate(R.layout.popupwindow_list_view,null);
        ListView mListView = popup_list_view.findViewById(R.id.lv_data);
        Button itemCancel = popup_list_view.findViewById(R.id.bt_item_cancel);
        itemCancel.setOnClickListener(v -> {
            if(popupWindow!=null){
                popupWindow.dismiss();
                setBackgroundAlpha(1.0f);
            }
        });
        mListView.setBackgroundResource(R.color.white);
        SimpleAdapter simplead = new SimpleAdapter(this, params,
                R.layout.popupwindow_list_item, new String[] { "name"},
                new int[] {R.id.tv_msg});
        mListView.setAdapter(simplead);
        mListView.setOnItemClickListener((parent, view1, position, id) -> {
            try {
                String value = params.get(position).get("value");
                String name = params.get(position).get("name");
                if(name!=null) {
                    if (name.contains(".")) {
                        name = name.split("\\.")[0];
                    }
                    binding.btnSelItem.setText(name);
                }
                fileName = value;
                popupWindow.dismiss();
                setBackgroundAlpha(1.0f);
            }catch (Exception ex){
                mylog.error("选择标签异常", ex);
            }
        });
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        double width = outMetrics.widthPixels*0.8;
        popupWindow = new PopupWindow(view, (int) width,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow.setContentView(popup_list_view);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        setBackgroundAlpha(0.5f);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

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

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

}