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

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ygtx.emcs.R;
import com.ygtx.emcs.activity.adapter.StockOutAdapter;
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.YgtxStockInBinding;
import com.ygtx.emcs.util.Constant;
import com.ygtx.emcs.util.HttpsUtil;
import com.ygtx.emcs.util.MyProgress;
import com.ygtx.emcs.util.Permission;
import com.ygtx.emcs.util.StringUtils;
import com.ygtx.emcs.util.ToastUtils;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

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


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

    private YgtxStockInBinding binding;
    private Context context;
    private StockOutAdapter listViewAdapter;
    private ArrayList<StockModel> mList;
    private ActivityResultLauncher<Intent> launcher;


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

    private void initData(){
        mList = new ArrayList<>();
        listViewAdapter = new StockOutAdapter(mList, context);
        binding.swipeContainer.setAdapter(listViewAdapter);
        binding.swipeContainer.setVisibility(View.GONE);
        binding.tvEmpty.setVisibility(View.VISIBLE);
        binding.swipeContainer.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);
        binding.swipeContainer.setProgressViewEndTarget(true, 200);
        binding.swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchTask(0);
            }
        });
        binding.lvStock.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                StockModel stockModel = mList.get(position);
                Bundle bundle = new Bundle();
                bundle.putString("erpOutstockCode", stockModel.getErpOutstockCode());
                bundle.putString("from", "1");
                toActivity(StockOutNewActivity.class, bundle);
            }
        });
        binding.swipeContainer.autoRefresh();
    }

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

//        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 -> {
//            Intent intent = new Intent(context, StockOutNewActivity.class);
//            launcher.launch(intent);
//        });
//        launcher = registerForActivityResult(
//                new ActivityResultContracts.StartActivityForResult(),
//                result -> {
//                    if (result.getResultCode() == RESULT_OK) {
//                        if(result.getData()!=null) {
//                            searchTask(0);
//                        }
//                    }
//                }
//        );
        binding.tvEmpty.setOnClickListener(view->{
            searchTask(0);
        });
    }

    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);
        checkOrderCode(barcode);
    }

    private void checkOrderCode(String barcode){
        String in_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "in_stock_flag");
        if(StringUtils.isEmpty(in_stock_flag)){
            ToastUtils.showToast(context, "请设置入库单编码的标识");
            return;
        }
        if(barcode.startsWith(in_stock_flag)){
            Bundle bundle = new Bundle();
            bundle.putString("erpInstockCode", barcode);
            toTopActivity(StockInNewActivity.class, bundle);
            finish();
            return;
        }
        String out_stock_flag = CacheService.getInstance(context).getCache(CACHE_BIND_CONFIG, "out_stock_flag");
        if(StringUtils.isEmpty(out_stock_flag)){
            ToastUtils.showToast(context, "请设置出库单编码的标识");
            return;
        }
        if(barcode.startsWith(out_stock_flag)){
            Bundle bundle = new Bundle();
            bundle.putString("erpOutstockCode", barcode);
            toTopActivity(StockOutNewActivity.class, bundle);
            finish();
        }
    }

    private void searchTask(int from) {
        if(Constant.user==null || Constant.user.getUserId() == null){
            return;
        }
        MyProgress myProgress = MyProgress.getInstance();
        if(from == 0) {
            myProgress.show(context, "提示", "正在加载");
        }
        RequestParams params = httParams(Constant.STOCK_OUT_LIST);
        params.addBodyParameter("pageNum", "1");
        params.addBodyParameter("pageSize", "100");
        params.addBodyParameter("fromType", "0");
        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 {
                    if (rs.getInt("code") == 200) {
                        Type rds = new TypeToken<List<StockModel>>() {}.getType();
                        int total = rs.getInt("total");
                        if(total == 0){
                            mylog.info("没有记录");
                            return;
                        }
                        if(from == 0) {
                            mList.clear();
                            List<StockModel> stockModels = new Gson().fromJson(rs.get("rows").toString(), rds);
                            mList.addAll(stockModels);
                            showGroup(stockModels);
                            listViewAdapter.notifyDataSetChanged();
                            binding.swipeContainer.setRefreshing(false);
                            binding.swipeContainer.setLoading(false);
                        }
                        if(from == 1){
                            List<StockModel> stockModels = new Gson().fromJson(rs.get("rows").toString(), rds);
                            showGroup(stockModels);
                            updateList(stockModels);
                        }
                    }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(StockOutActivity.this, ex);
                mylog.error("请求异常：", ex);
            }

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

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

    private void showGroup(List<StockModel> list){
        if(list.size() > 0) {
            binding.swipeContainer.setVisibility(View.VISIBLE);
            binding.tvEmpty.setVisibility(View.GONE);
        }else{
            binding.swipeContainer.setVisibility(View.GONE);
            binding.tvEmpty.setVisibility(View.VISIBLE);
        }
    }

    public void updateList(List<StockModel> n_list){
        if(n_list.size() >= mList.size()){
            updateList1(n_list);
        }else{
            updateList2(n_list);
        }
    }

    public void updateList1(List<StockModel> n_list){
        List<StockModel> nList = new ArrayList<>();
        for (StockModel stockModel:n_list){
            String id = stockModel.getOutstockId();
            boolean isAdd = true;
            for (StockModel nTaskModel:mList){
                if(id.equals(nTaskModel.getOutstockId())){
                    isAdd = false;
                    nTaskModel.setStatus(stockModel.getStatus());
                }
            }
            if(isAdd){
                nList.add(stockModel);
            }
        }
        mList.addAll(nList);
        listViewAdapter.notifyDataSetChanged();
    }

    public void updateList2(List<StockModel> n_list){
        List<StockModel> nList = new ArrayList<>();
        for (StockModel stockModel:mList){
            String id = stockModel.getOutstockId();
            boolean isDel = true;
            for (StockModel nTaskModel:n_list){
                if(id.equals(nTaskModel.getOutstockId())){
                    isDel = false;
                    stockModel.setStatus(nTaskModel.getStatus());
                }
            }
            if(isDel) {
                nList.add(stockModel);
            }
        }
        for (StockModel stockModel:nList){
            mList.remove(stockModel);
        }
        listViewAdapter.notifyDataSetChanged();
    }

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

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

}