package com.example.tyre.maintenance;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListPopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableBoolean;

import com.example.tyre.R;
import com.example.tyre.databinding.ActivityWorkOrderBinding;
import com.example.tyre.maintenance.adapter.OrderAdapter;
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.Order;
import com.example.tyre.util.SharedPreferencesUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.RequestBody;

public class WorkOrderActivity extends BaseActivity implements OrderAdapter.SelectTagAdapterListener {
    private ActivityWorkOrderBinding binding;
    private ObservableBoolean status;
    private DatePickerDialog datePickerDialogStart;
    private DatePickerDialog datePickerDialogEnd;
    private ListPopupWindow listPopupWindow;
    private List<Order> list;
    private OrderAdapter adapter;
    private String typeCode;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_work_order);
        status = new ObservableBoolean(false);
        binding.setStatus(status);
        Intent intent = getIntent();
        title = intent.getStringExtra("title");

        typeCode = intent.getStringExtra("typeCode");
        binding.setTitle(title);
        // 获取当前日期
        initDataSelect();

        // 初始化选择框
        listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAnchorView(binding.workOrderSite);
        String[] stringArray = getResources().getStringArray(R.array.zxzd);
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, stringArray));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            String text = stringArray[position];
            binding.workOrderSite.setText(text);
            SharedPreferencesUtils.putstring("workOrderSite", text);
            listPopupWindow.dismiss();
            selectWorkOrder(binding.workOrderDateStart.getText().toString(), binding.workOrderDateEnd.getText().toString(), getDeptId(text), status.get() ? "COMPLETED" : "PROCESSING");
        });
        adapter = new OrderAdapter(this, this);
        binding.setAdapter(adapter);

    }

    private void initDataSelect() {
        // 开始日期
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.add(Calendar.DAY_OF_MONTH, -7);
        binding.workOrderDateStart.setText(dateFormat.format(calendarStart.getTime()));
        datePickerDialogStart = new DatePickerDialog(this, (view1, year, monthOfYear, dayOfMonth) -> {
            @SuppressLint("DefaultLocale")
            String selectedDate =
                    year + "-" + String.format("%02d", (monthOfYear + 1)) + "-" + String.format("%02d", dayOfMonth);
            binding.workOrderDateStart.setText(selectedDate);
            // 查询
            selectWorkOrder(selectedDate,
                    binding.workOrderDateEnd.getText().toString(),
                    getDeptId(binding.workOrderSite.getText().toString()),
                    status.get() ? "COMPLETED" : "PROCESSING");

        }, calendarStart.get(Calendar.YEAR), calendarStart.get(Calendar.MONTH), calendarStart.get(Calendar.DAY_OF_MONTH));

        // 结束日期
        Calendar calendarEnd = Calendar.getInstance();
        binding.workOrderDateEnd.setText(dateFormat.format(calendarEnd.getTime()));
        datePickerDialogEnd = new DatePickerDialog(this, (view1, year, monthOfYear, dayOfMonth) -> {
            @SuppressLint("DefaultLocale")
            String selectedDate =
                    year + "-" + String.format("%02d", (monthOfYear + 1)) + "-" + String.format("%02d", dayOfMonth);
            binding.workOrderDateEnd.setText(selectedDate);
            selectWorkOrder(binding.workOrderDateStart.getText().toString(),
                    selectedDate,
                    getDeptId(binding.workOrderSite.getText().toString()),
                    status.get() ? "COMPLETED" : "PROCESSING");
        }, calendarEnd.get(Calendar.YEAR), calendarEnd.get(Calendar.MONTH), calendarEnd.get(Calendar.DAY_OF_MONTH));


    }

    // 查询工单
    private void selectWorkOrder(String selectedDate1, String selectedDate2, int deptId, String state) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", state);
        // params.put("maintainDateStart", selectedDate1);
        params.put("maintainDate", selectedDate2);
        params.put("factoryId", deptId);
        if (typeCode != null && !typeCode.isEmpty()) {
            params.put("typeCode", typeCode);
        }

        OkGo.<MyResult>post(url + "/tyre/order/PDAGetMaintenanceOrder").upRequestBody(RequestBody.create(JSON, gson.toJson(params))).execute(new MyRecultCall(dialog, this) {
            @Override
            public void onSuccess(Response<MyResult> response) {
                super.onSuccess(response);
                var body = response.body();
                if (body.getCode() == 0) {
                    list = gson.fromJson(body.getJson(), new TypeToken<List<Order>>() {
                    }.getType());
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    // 选日期
    public void selectDate1(View view) {
        datePickerDialogStart.show();
    }

    public void selectDate2(View view) {
        datePickerDialogEnd.show();
    }

    // 选站点
    public void selectOrderSite(View view) {
        listPopupWindow.show();
    }

    // 创建
    public void goCreateWorkOrder(View view) {
        Intent intent = new Intent(this, CreateWorkOrderActivity.class);
        intent.putExtra("title", title);
        startActivity(intent);
    }

    public void switchStatus(View view) {
        status.set(!status.get());
        selectWorkOrder(binding.workOrderDateStart.getText().toString(),
                binding.workOrderDateEnd.getText().toString(),
                getDeptId(binding.workOrderSite.getText().toString()),
                status.get() ? "COMPLETED" : "PROCESSING");
    }

    // 执行工单
    @Override
    public void onTagClick(int position) {
        Order order = list.get(position);
        Intent intent = null;
        String typeCode1 = order.getTypeCode();
        if (typeCode1.equals("6")) {
            intent = new Intent(this, TireRepairActivity.class);
        } else if (typeCode1.equals("7")) {
            intent = new Intent(this, TireScrapActivity.class);
        } else {
            intent = new Intent(this, WorkExecuteActivity.class);
        }

        intent.putExtra("site", binding.workOrderSite.getText().toString());
        intent.putExtra("carNo", order.getPlateNumber());
        intent.putExtra("maintainDate", order.getMaintainDate());
        intent.putExtra("orderState", status.get());
        intent.putExtra("json", gson.toJson(order));
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.workOrderSite.setText(SharedPreferencesUtils.getstring("workOrderSite", "光明修理厂"));
        selectWorkOrder(binding.workOrderDateStart.getText().toString(), binding.workOrderDateEnd.getText().toString(), getDeptId(binding.workOrderSite.getText().toString()),   status.get() ? "COMPLETED" : "PROCESSING");
    }
}