package com.example.tyre.maintenance;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListPopupWindow;

import androidx.databinding.DataBindingUtil;

import com.example.tyre.R;
import com.example.tyre.databinding.ActivityCreateWorkOrderBinding;
import com.example.tyre.entity.BaseCar;
import com.example.tyre.entity.BaseTyre;
import com.example.tyre.maintenance.base.BaseActivity;
import com.example.tyre.maintenance.base.MyRecultCall;
import com.example.tyre.maintenance.base.MyResult;
import com.example.tyre.maintenance.dialog.TipResultDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.RequestBody;

public class CreateWorkOrderActivity extends BaseActivity {
    private final Handler handler = new Handler(Looper.getMainLooper());
    private TipResultDialog tipDialog;
    private ActivityCreateWorkOrderBinding binding;
    private ListPopupWindow lpw;
    private boolean isSearch = false;
    private List<BaseCar> baseCarList;
    private Map<String, Object> submitMap;
    private Runnable searchRunnable;
    private String typeTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_create_work_order);
        tipDialog = new TipResultDialog(this, this);

        initRFIDAndKeyReceiver();// 初始化RFID

        binding.createWorkCarNo.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) {
                Log.e("TAG", "onTextChanged:" + count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e("TAG", "afterTextChanged:" + s);
                if (isSearch) {
                    if (searchRunnable != null) {
                        handler.removeCallbacks(searchRunnable);
                    }
                    searchRunnable = () -> selectCarNo(s.toString());
                    handler.postDelayed(searchRunnable, 1000);
                }
                isSearch = true;
            }
        });
        lpw = new ListPopupWindow(this);
        lpw.setAnchorView(binding.createWorkCarNo);

        lpw.setWidth(400);
        lpw.setHeight(400);
        submitMap = new HashMap<>();
        lpw.setOnItemClickListener((parent, view, position, id) -> {
            isSearch = false;
            BaseCar baseCar = baseCarList.get(position);
            submitMap.put("vehicleId", baseCar.getId());
            submitMap.put("orderType", "1");
            String carNo = baseCar.getCarNo();
            submitMap.put("plateNumber", carNo);
            binding.createWorkCarNo.setText(carNo);
            lpw.dismiss();
        });
        List<String> list = Arrays.asList(getResources().getStringArray(R.array.zxzd));
        binding.orderCreateSite.setSelection(list.indexOf(SharedPreferencesUtils.getstring("workOrderSite", "光明修理厂")));
        binding.orderCreateSite.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                SharedPreferencesUtils.putstring("workOrderSite", list.get(i));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        typeTitle = getIntent().getStringExtra("title");
        binding.setTypeCode(typeTitle);// 传入页面控制显示轮胎还是车牌
        // 显示类型选择器
        if (typeTitle != null) {
            List<String> typeList = Arrays.asList(getResources().getStringArray(R.array.work_type));
            int index = typeList.indexOf(typeTitle);
            if (index != -1) {
                binding.orderCreateType.setSelection(index);
            }
        }

    }

    private void selectCarNo(String carNo) {

        Map<String, String> map = new HashMap<>();
        map.put("carNo", carNo);

        OkGo.<MyResult>post(MyUrl.url + "/tyre/car/PdaQueryCarList").tag(this)
                .upRequestBody(RequestBody.create(JSON, gson.toJson(map)))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        var body = response.body();
                        if (body.getCode() == 0) {

                            baseCarList = gson.fromJson(body.getJson(), new TypeToken<List<BaseCar>>() {
                            }.getType());
                            if (baseCarList == null || baseCarList.isEmpty()) {
                                lpw.dismiss();
                                return;
                            }
                            List<String> carNoList = new ArrayList<>(baseCarList.size());
                            baseCarList.forEach(car -> carNoList.add(car.getCarNo()));
                            lpw.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, carNoList));
                            lpw.show();
                            return;
                        }
                        tipDialog.show(false, null, body.getMsg(), false);
                    }
                });

    }

    public void openSelectCarDialog(View view) {

    }

    // 提交数据
    public void generateWorkOrder(View view) {

        Object vehicleId = submitMap.get("vehicleId");
        if (vehicleId == null) {
            tipDialog.show(false, null, "请先选择车辆/轮胎", false);
            return;
        }

        // 选车牌时候已插入id
        submitMap.put("typeCode", getTypeCode(binding.orderCreateType.getSelectedItem().toString()));
        submitMap.put("factoryId", getDeptId(binding.orderCreateSite.getSelectedItem().toString()));
        submitMap.put("createBy", SharedPreferencesUtils.getstring("user", "admin"));

        submitMap.put("status", "PROCESSING");
        submitMap.put("maintainDate", dateFormat.format(new Date()));
        OkGo.<MyResult>post(MyUrl.url + "/tyre/order/PDAAddMaintenanceOrder")
                .upRequestBody(RequestBody.create(JSON, gson.toJson(submitMap)))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        var body = response.body();
                        if (body.getCode() == 0) {
                            tipDialog.show(true, "发起成功!", "已加入【未完成】列表", true);
                        } else {
                            tipDialog.show(false, null, body.getMsg(), false);
                        }

                    }
                });
    }

    @Override
    public void sanEpcCall(String epc) {
        super.sanEpcCall(epc);
        binding.createWorkTyreRfid.setText(epc);
        findBaseTyre(epc);

    }


    private void findBaseTyre(String epc) {
        dialog.show();
        OkGo.<String>post(MyUrl.url + "/tyre/tyre/pdaQueryTyreInfo")
                .tag(this)
                .params("tyreEpc", epc)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dialog.dismiss();
                        try {
                            Gson gson = new Gson();
                            BaseTyre baseTyre = gson.fromJson(response.body(), BaseTyre.class);
                            if (baseTyre != null) {
                                // wtbm.setText(safeGetString(baseTyre.getTyreNo()));
                                submitMap.put("vehicleId", baseTyre.getTyreId());
                                submitMap.put("plateNumber", baseTyre.getTyreNo());
                                submitMap.put("orderType", "2");
                                return;
                            }
                            tipDialog.show(false, null, "未查询到轮胎信息", false);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}