package com.example.tyre.maintenance;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;

import com.example.tyre.R;
import com.example.tyre.databinding.ActivityTireScrapBinding;
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.util.MyUrl;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class TireScrapActivity extends BaseActivity {

    private ActivityTireScrapBinding binding;
    private Order order;
    private String carNo;
    private BaseTyre selectedTire;

    // Scrap Position Data
    private String scrapCategory = "";
    private String scrapReason = "";

    // Photos
    private int currentPhotoIndex = -1;
    private List<File> fileList;

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

        fileList = new ArrayList<>();

        Intent intent = getIntent();
        carNo = intent.getStringExtra("carNo");
        String site = intent.getStringExtra("site");
        order = gson.fromJson(intent.getStringExtra("json"), Order.class);

        binding.setCarNo(carNo);
        binding.setSite(site);

        String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        binding.setCurrentDate(currentDate);

        binding.llScrapPosition.setOnClickListener(v -> showScrapReasonDialog());

        selectTire();
    }

    // 查询轮胎信息
    private void selectTire() {
        // 使用 order.getPlateNumber() 作为 tyreNo 进行查询，因为工单是根据轮胎创建的
        String tyreNo = order.getPlateNumber();
        if (tyreNo == null || tyreNo.isEmpty()) {
            Toast.makeText(context, "工单未关联轮胎信息", Toast.LENGTH_SHORT).show();
            return;
        }

        OkGo.<String>post(MyUrl.url + "/tyre/tyre/list").tag(this).params("tyreNo", tyreNo).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    org.json.JSONObject jsonObject = new org.json.JSONObject(response.body());
                    if (jsonObject.has("rows")) {
                        org.json.JSONArray rows = jsonObject.getJSONArray("rows");
                        if (rows.length() > 0) {
                            selectedTire = gson.fromJson(rows.getJSONObject(0).toString(), BaseTyre.class);
                            binding.setTire(selectedTire);
                            return;
                        }
                    }
                    Toast.makeText(context, "未查询到该轮胎信息", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, "解析轮胎数据失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void showScrapReasonDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_scrap_reason, null);
        dialog.setContentView(view);

        // Make background transparent to show custom rounded corners
        Window window = dialog.getWindow();
        if (window != null) {
            window.findViewById(com.google.android.material.R.id.design_bottom_sheet)
                    .setBackgroundColor(Color.TRANSPARENT);
        }

        ImageView ivClose = view.findViewById(R.id.iv_close_dialog);
        ivClose.setOnClickListener(v -> dialog.dismiss());

        ListView lvCategories = view.findViewById(R.id.lv_categories);
        ListView lvSubItems = view.findViewById(R.id.lv_sub_items);

        String[] categories = new String[]{"胎冠", "胎侧", "趾口T(胎号面)", "趾口D(DOT面)", "其他"};
        Map<String, String[]> subItemsMap = new HashMap<>();
        subItemsMap.put("胎冠", new String[]{"一次性刺扎(包含花纹沟夹石)", "连续刺扎(钉子或石头扎伤，橡胶受损)", "脱层", "撞击", "磨光", "不规则磨损"});
        subItemsMap.put("胎侧", new String[]{"撞击", "连续损伤(双胎夹石、机械损伤)", "一次性损伤", "过度曲挠", "开裂", "变形"});
        subItemsMap.put("趾口T(胎号面)", new String[]{"趾口开裂、脱层、变形", "拆装损伤", "老化过热", "轮辋装配"});
        subItemsMap.put("趾口D(DOT面)", new String[]{"趾口开裂、脱层、变形", "拆装损伤", "老化过热", "轮辋装配"});
        subItemsMap.put("其他", new String[]{"好的或坏的修补(厂家或授权服务商)", "不满足良性修补判定", "气密层褶皱", "串气", "化学污染", "年限到期", "其他未列出原因"});

        // Category Adapter
        ArrayAdapter<String> catAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, categories) {
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        TextView tv = (TextView) super.getView(position, convertView, parent);
                        tv.setTextSize(14f);
                        tv.setTextColor(Color.parseColor("#333333"));
                        tv.setGravity(Gravity.CENTER);
                        tv.setPadding(0, 40, 0, 40);
                        return tv;
                    }
                };
        lvCategories.setAdapter(catAdapter);

        // Sub Items Adapter (initially empty or first category)
        final ArrayAdapter<String>[] subAdapter =
                new ArrayAdapter[]{new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, subItemsMap.get(categories[0])) {
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        TextView tv = (TextView) super.getView(position, convertView, parent);
                        tv.setTextSize(14f);
                        tv.setTextColor(Color.parseColor("#666666"));
                        tv.setPadding(0, 40, 0, 40);
                        return tv;
                    }
                }};
        lvSubItems.setAdapter(subAdapter[0]);

        final String[] currentCategory = {categories[0]};

        lvCategories.setOnItemClickListener((parent, view1, position, id) -> {
            currentCategory[0] = categories[position];
            subAdapter[0] =
                    new ArrayAdapter<String>(TireScrapActivity.this, android.R.layout.simple_list_item_1, subItemsMap.get(currentCategory[0])) {
                        @Override
                        public View getView(int pos, View convertView, ViewGroup p) {
                            TextView tv = (TextView) super.getView(pos, convertView, p);
                            tv.setTextSize(14f);
                            tv.setTextColor(Color.parseColor("#666666"));
                            tv.setPadding(0, 40, 0, 40);
                            return tv;
                        }
                    };
            lvSubItems.setAdapter(subAdapter[0]);
            for (int i = 0; i < parent.getChildCount(); i++) {
                parent.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
            }
            view1.setBackgroundColor(Color.WHITE);
        });

        lvSubItems.setOnItemClickListener((parent, view12, position, id) -> {
            String selectedSubItem = subAdapter[0].getItem(position);
            scrapCategory = currentCategory[0];
            scrapReason = selectedSubItem;
            binding.tvScrapPosition.setText(scrapCategory + " - " + scrapReason);
            binding.tvScrapPosition.setTextColor(Color.parseColor("#333333"));
            dialog.dismiss();
        });

        dialog.show();
    }

    public void takePhoto1(View view) {
        currentPhotoIndex = 1;
        try {
            teke_photo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void takePhoto2(View view) {
        currentPhotoIndex = 2;
        try {
            teke_photo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void takePhoto3(View view) {
        currentPhotoIndex = 3;
        try {
            teke_photo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void takePhoto4(View view) {
        currentPhotoIndex = 4;
        try {
            teke_photo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void tekePhotoResult(String fileUrl, File file) {
        super.tekePhotoResult(fileUrl, file);
        if (file != null) {
            fileList.add(file);
            if (currentPhotoIndex == 1) {
                binding.ivPhoto1.setImageResource(R.mipmap.ic_duihao);
            } else if (currentPhotoIndex == 2) {
                binding.ivPhoto2.setImageResource(R.mipmap.ic_duihao);
            } else if (currentPhotoIndex == 3) {
                binding.ivPhoto3.setImageResource(R.mipmap.ic_duihao);
            } else if (currentPhotoIndex == 4) {
                binding.ivPhoto4.setImageResource(R.mipmap.ic_duihao);
            }
        }
    }

    public void saveScrapOrder(View view) {
        if (selectedTire == null) {
            Toast.makeText(context, "未找到关联的轮胎信息，无法报废", Toast.LENGTH_SHORT).show();
            return;
        }

        if (scrapReason.isEmpty()) {
            Toast.makeText(context, "请选择报废位置", Toast.LENGTH_SHORT).show();
            return;
        }

        if (fileList.isEmpty()) {
            Toast.makeText(context, "请至少拍摄一张报废照片", Toast.LENGTH_SHORT).show();
            return;
        }

        String remark = binding.dialogTireRemark1.getText().toString().trim();

        BizOrderTireDetail scrapDetail = new BizOrderTireDetail();
        scrapDetail.setOrderId(order.getOrderId());
        scrapDetail.setTireId(selectedTire.getTyreId());
        scrapDetail.setTireCode(selectedTire.getTyreNo());
        scrapDetail.setPositionName(selectedTire.getWheelPostion());
        String wheelPostion = selectedTire.getWheelPostion();
        if (wheelPostion != null && !wheelPostion.isEmpty()) {
            if (wheelPostion.equals("右内轮")) {
                scrapDetail.setPositionId(119L);
            } else if (wheelPostion.equals("右外轮")) {
                scrapDetail.setPositionId(118L);
            } else if (wheelPostion.equals("左内轮")) {
                scrapDetail.setPositionId(120L);
            } else if (wheelPostion.equals("左外轮")) {
                scrapDetail.setPositionId(121L);
            } else if (wheelPostion.equals("右前轮")) {
                scrapDetail.setPositionId(122L);
            } else if (wheelPostion.equals("左前轮")) {
                scrapDetail.setPositionId(123L);
            }

        }


        scrapDetail.setDataType("报废");

        // 暂不将两级原因结果存入数据库中，轮胎状态默认报废
        scrapDetail.setTireStatus("报废");
        scrapDetail.setRemark(remark);

        List<BizOrderTireDetail> tireDetails = new ArrayList<>();
        tireDetails.add(scrapDetail);

        Map<String, Object> orderSubmitMap = new HashMap<>();
        orderSubmitMap.put("order", order);
        orderSubmitMap.put("tireDetails", tireDetails);

        OkGo.<MyResult>post(url + "/tyre/order/PDASaveMaintenanceOrder")
                .tag(this)
                .isMultipart(true)
                .params("json", gson.toJson(orderSubmitMap))
                .addFileParams("files", fileList)
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        if (body.getCode() == 0) {
                            Toast.makeText(context, "报废工单提交成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(context, body.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}