package com.example.tyre.maintenance;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
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.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 okhttp3.RequestBody;

public class TireScrapActivity extends BaseActivity {

    private ActivityTireScrapBinding binding;
    private Order order;
    private String carNo;
    private Map<String, BaseTyre> tyreMap;
    private List<BaseTyre> baseTyreList;
    private List<String> positionList;
    private ArrayAdapter<String> positionAdapter;

    // 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);

        tyreMap = new HashMap<>();
        positionList = new ArrayList<>();
        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);

        positionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, positionList);
        positionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinnerScrapPosition.setAdapter(positionAdapter);

        selectTire(carNo);
    }

    // 查询轮胎信息
    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) {
                baseTyreList = gson.fromJson(response.body(), new TypeToken<List<BaseTyre>>() {
                }.getType());
                if (baseTyreList == null || baseTyreList.isEmpty()) {
                    Toast.makeText(context, "该车无绑定轮胎", Toast.LENGTH_SHORT).show();
                    return;
                }
                positionList.clear();
                tyreMap.clear();
                for (BaseTyre tire : baseTyreList) {
                    String wheelPostion = tire.getWheelPostion();
                    if (wheelPostion != null && !wheelPostion.isEmpty()) {
                        positionList.add(wheelPostion);
                        tyreMap.put(wheelPostion, tire);
                    }
                }
                positionAdapter.notifyDataSetChanged();
            }
        });
    }

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

    @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);
            }
        }
    }

    public void saveScrapOrder(View view) {
        if (positionList.isEmpty()) {
            Toast.makeText(context, "无可报废的轮胎", Toast.LENGTH_SHORT).show();
            return;
        }

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

        String selectedPosition = (String) binding.spinnerScrapPosition.getSelectedItem();
        BaseTyre selectedTire = tyreMap.get(selectedPosition);
        if (selectedTire == null) {
            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());
        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();
                        }
                    }
                });
    }
}