package com.example.tyre.maintenance;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;

import com.example.tyre.R;
import com.example.tyre.UpActivity;
import com.example.tyre.databinding.ActivityWorkExecuteBinding;
import com.example.tyre.entity.AjaxResult;
import com.example.tyre.entity.BaseCar;
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.been.BaseTyre;
import com.example.tyre.maintenance.been.BizOrderTireDetail;
import com.example.tyre.maintenance.been.Order;
import com.example.tyre.maintenance.dialog.TipResultDialog;
import com.example.tyre.maintenance.dialog.TireUpdateDialog;
import com.example.tyre.util.CommonDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
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.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import okhttp3.RequestBody;

public class WorkExecuteActivity extends BaseActivity implements TireUpdateDialog.TireUpdateDialogSaveListener {
    private ActivityWorkExecuteBinding binding;
    private Map<String, BaseTyre> tyreMap;
    private Map<String, BizOrderTireDetail> infoMap;
    private TireUpdateDialog tireUpdateDialog;// 点击轮胎弹窗
    private Map<String, Object> orderSubmitMap;
    private List<BizOrderTireDetail> tireDetails;
    private List<File> fileList;
    private TipResultDialog tipDialog;
    private List<BaseTyre> baseTyreList;
    private String epcTag = "";// 屏蔽重复查询
    private String carNo;
    private ActivityResultLauncher<Intent> launcher;
    private boolean orderState;// 工单状态
    private Order order;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_work_execute);
        initRFID();
        Intent intent = getIntent();
        infoMap = new HashMap<>();
        // 订单状态
        orderState = intent.getBooleanExtra("orderState", false);
        binding.setOrderState(orderState);
        carNo = intent.getStringExtra("carNo");
        binding.setCarNo(carNo);
        tyreMap = new HashMap<>();
        // selectCarNo(carNo);
        selectTire(carNo);
        orderSubmitMap = new HashMap<>();
        order = gson.fromJson(intent.getStringExtra("json"), Order.class);
        if (order != null) {
            binding.workLicheng.setText(order.getInputMileage());
            binding.workBuchong.setText(order.getDescription());
        }
        orderSubmitMap.put("order", order);
        tireDetails = new ArrayList<>();
        fileList = new ArrayList<>();
        orderSubmitMap.put("tireDetails", tireDetails);
        binding.setSite(intent.getStringExtra("site"));
        binding.setDate(intent.getStringExtra("maintainDate"));
        tireUpdateDialog = new TireUpdateDialog(this, this);

        tireClick();
        tipDialog = new TipResultDialog(this, this);

        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                selectTire(carNo);
            }
        });
    }

    // 点击轮胎
    private void tireClick() {
        if (orderState) {
            return;
        }
        binding.tireClick1.layoutTireInfo.setOnClickListener(view -> {
            showDialog("左前轮");
        });
        binding.tireClick2.layoutTireInfo.setOnClickListener(view -> {
            showDialog("右前轮");
        });
        binding.tireClick3.layoutTireInfo.setOnClickListener(view -> {
            showDialog("左外轮");
        });
        binding.tireClick4.layoutTireInfo.setOnClickListener(view -> {
            showDialog("左内轮");
        });
        binding.tireClick5.layoutTireInfo.setOnClickListener(view -> {
            showDialog("右内轮");
        });
        binding.tireClick6.layoutTireInfo.setOnClickListener(view -> {
            showDialog("右外轮");
        });

    }

    // 显示轮胎弹窗
    private void showDialog(String location) {
        String s = binding.workLicheng.getText().toString();
        if (s.isEmpty()) {
            Toast.makeText(context, "先填写里程信息", Toast.LENGTH_SHORT).show();
            return;
        }
        BaseTyre baseTyre = tyreMap.get(location);
        if (baseTyre == null) {
            try {
                if (keyReceiver != null) {
                    unregisterReceiver(keyReceiver);
                }
            } catch (Exception e) {

            }

            Intent intent = new Intent(this, UpActivity.class);
            intent.putExtra("dataType", true);
            intent.putExtra("location", location);
            intent.putExtra("carNo", carNo);
            intent.putExtra("licheng", s);
            launcher.launch(intent);
        } else {
            initKeyRecriver(this::readEPC);
           BizOrderTireDetail tag=
                    tireDetails.stream().filter(tire -> tire.getPositionName().equals(location)).findFirst().orElse(null);
            tireUpdateDialog.setBaseTyre(baseTyre, tag);
        }

    }

    // 查询轮胎信息
    private void selectTire(String carNo) {
        OkGo.<String>post(MyUrl.url + "/tyre/tyre/getCarBingTire").tag(this).params("carNo", carNo).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                binding.setTire1(new BaseTyre());
                binding.setTire2(new BaseTyre());
                binding.setTire3(new BaseTyre());
                binding.setTire4(new BaseTyre());
                binding.setTire5(new BaseTyre());
                binding.setTire6(new BaseTyre());
                baseTyreList = gson.fromJson(response.body(), new TypeToken<List<BaseTyre>>() {
                }.getType());
                tireUpdateDialog.setBaseTyreList(baseTyreList);
                if (baseTyreList == null || baseTyreList.isEmpty()) return;
                baseTyreList.forEach(tire -> {
                    String wheelPostion = tire.getWheelPostion();
                    tyreMap.put(wheelPostion, tire);
                    initTire(wheelPostion, tire);

                });
            }
        });
        /*        .execute(new MyRecultCall(dialog, this) {
            @Override
            public void onSuccess(Response<MyResult> response) {
                super.onSuccess(response);
                var body = response.body();
                // if (body.getCode() == 0) {
                    List<BaseTyre> baseTyreList =
                            gson.fromJson(body.getJson(), new TypeToken<List<BaseTyre>>() {
                            }.getType());
                    if (baseTyreList == null || baseTyreList.isEmpty()) return;
                    baseTyreList.forEach(tire -> {
                        String wheelPostion = tire.getWheelPostion();
                        tyreMap.put(wheelPostion, tire);
                        initTire(wheelPostion, tire);
                    });
                // }

            }
        });*/

    }

    // 初始化轮胎信息
    private void initTire(String wheelPostion, BaseTyre baseTyre) {

        switch (wheelPostion) {
            case "左前轮":

                binding.setTire1(baseTyre);
                break;
            case "右前轮":

                binding.setTire2(baseTyre);
                break;
            case "左外轮":
                binding.setTire3(baseTyre);
                break;
            case "左内轮":
                binding.setTire4(baseTyre);
                break;

            case "右内轮":
                binding.setTire5(baseTyre);
                break;
            case "右外轮":
                binding.setTire6(baseTyre);
                break;
        }
    }

    // 查询车辆信息
    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, new 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) {
                    List<BaseCar> baseCarList = gson.fromJson(body.getJson(), new TypeToken<List<BaseCar>>() {
                    }.getType());
                    binding.setLine(baseCarList.get(0).getLine());
                }

            }
        });

    }

    // 提交处理
    public void submitWorkExecute(View view) {
        Order order = (Order) orderSubmitMap.get("order");
        order.setInputMileage(binding.workLicheng.getText().toString());
        order.setDescription(binding.workBuchong.getText().toString());

        OkGo.<MyResult>post(MyUrl.url + "/tyre/order/PDASaveMaintenanceOrder").params("json", gson.toJson(orderSubmitMap)).addFileParams("files", fileList).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);
                    return;
                }
                tipDialog.show(false, null, body.getMsg(), false);

            }
        });
    }

    // 返回照片
    @Override
    public void tekePhotoResult(String fileUrl, File file) {
        super.tekePhotoResult(fileUrl, file);
        Log.e("TAG", "拍照成功，路径是:" + fileUrl);
        tireUpdateDialog.setImage(fileUrl, file);
    }

    //    删除实时表、卸车记录表
    private void down_insert(String rfid, String carNo, String millage, String wheel, String patternDepth) {
        OkGo.<String>post(MyUrl.url + "/tyre/install/PdaUnInstallTyre").tag(this).params("tyreRfid", rfid).params("mileage", millage).params("carNo", carNo).params("wheelPostion", wheel).params("patternDepth", patternDepth).params("CreateBy", SharedPreferencesUtils.getstring("user", "admin")).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                AjaxResult ajaxResult = gson.fromJson(body, AjaxResult.class);
                handleResponse(ajaxResult);
            }
        });
    }

    // 装车
    private void up_insert(String rfid, String carNo, String millage, String wheel, String selfNo) {
        OkGo.<String>post(MyUrl.url + "/tyre/install/PdaInstallTyre").tag(this).params("tyreRfid", rfid).params("mileage", millage).params("carNo", carNo).params("wheelPostion", wheel).params("selfNo", selfNo).params("CreateBy", SharedPreferencesUtils.getstring("user", "admin")).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                AjaxResult ajaxResult = gson.fromJson(body, AjaxResult.class);
                handleResponse(ajaxResult);

            }
        });
    }

    @Override
    public void sanEpcCall(String epc) {
        super.sanEpcCall(epc);
        if (!epcTag.equals(epc)) {
            find(epc);
        }
        epcTag = epc;
    }

    //    基本信息查询
    private void find(String epc) {
        OkGo.<String>post(MyUrl.url + "/tyre/tyre/pdaQueryTyreInfo").tag(this).params("tyreEpc", epc).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                try {
                    Gson gson = new Gson();
                    BaseTyre baseTyre = gson.fromJson(body, BaseTyre.class);
                    if (baseTyre != null) {
                        epcTag = "";
                        tireUpdateDialog.setNewBaseTyre(baseTyre);
                    } else {
                        new CommonDialog(context).setMessage("系统无此轮胎！").show();

                    }
                } catch (JsonSyntaxException e) {
                    return;
                }
            }
        });
    }

    private void handleResponse(AjaxResult result) {
        switch (result.getCode()) {
            case "500":
                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
            case "0":
                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
        }
    }

    @Override
    public void onSave(BizOrderTireDetail bizOrderTireDetail, File image, boolean isupdate, BizOrderTireDetail newTireDetail) {
        // 返回轮胎信息
        bizOrderTireDetail.setOrderId(order.getOrderId());
        infoMap.put(bizOrderTireDetail.getPositionName(), bizOrderTireDetail);
        tireDetails.stream().filter(tire -> tire.getPositionName().equals(bizOrderTireDetail.getPositionName())).findFirst().ifPresent(tire -> {
            tireDetails.remove(tire);

        });
        tireDetails.add(bizOrderTireDetail);
        if (image != null) {
            fileList.add(image);
        }
        tireUpdateDialog.dismiss();
        if (isupdate) {
            // 换新胎
            tireDetails.add(newTireDetail);
            BaseTyre baseTyre = newTireDetail.getBaseTyre();
            String positionName = newTireDetail.getPositionName();
            tyreMap.put(positionName, baseTyre);
            initTire(positionName, baseTyre);// 页面信息修改
            up_insert(baseTyre.getTyreEpc(), carNo, binding.workLicheng.getText().toString(), positionName, baseTyre.getSelfNo());
        }
    }

    @Override
    public void onTakePhoto() {
        // 拍照
        try {
            teke_photo();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onChangeSave(String oldLocation, String newLocation) {
        BaseTyre baseTyreOld = tyreMap.get(oldLocation);

        BaseTyre baseTyreNew = tyreMap.get(newLocation);
        OkGo.<MyResult>post(url + "/tyre/tyre/changeTyreForOneCar")

                .params("oldTyreId", baseTyreOld.getTyreId())
                .params("newTyreId", baseTyreNew.getTyreId())
                .params("oldLocation", oldLocation)
                .params("newLocation", newLocation)
                .params("user", SharedPreferencesUtils.getstring("user", "admin"))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        if (body.getCode() == 0) {
                            tyreMap.put(newLocation, baseTyreOld);
                            initTire(newLocation, baseTyreOld);
                            tyreMap.put(oldLocation, baseTyreNew);
                            initTire(oldLocation, baseTyreNew);
                            tireDetails.forEach(tireDetail -> {
                                if (tireDetail.getPositionName().equals(oldLocation)) {
                                    tireDetail.setPositionName(newLocation);
                                } else if (tireDetail.getPositionName().equals(newLocation)) {
                                    tireDetail.setPositionName(oldLocation);
                                }
                            });



                            // BizOrderTireDetail info1 = infoMap.get(newLocation);
                            // BizOrderTireDetail info2 = infoMap.get(oldLocation);



                            return;
                        }
                        Toast.makeText(WorkExecuteActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                });
    }


}