package com.baoshi.swms.activity.item;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.baoshi.swms.App;
import com.baoshi.swms.R;
import com.baoshi.swms.bean.Waybill;
import com.baoshi.swms.net.callback.WasHandlerCallback;
import com.baoshi.swms.net.subscribe.WasSubscribe;
import com.baoshi.swms.util.Hint;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 调配详情操作 ACTIVITY
 *
 * @author Zhendong Zhou
 * @date 2021/12/6 11:48
 */
public class WaybillDispatchItemActivity extends AppCompatActivity {
    private Waybill waybill;
    private EditText carrierBill;
    private EditText inquireTel;
    private EditText weight;
    private EditText volume;
    private EditText amount;
    private EditText subjoinFee;
    private RadioGroup amountUnitName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dispatch_item_waybill_show);

        registerLocalVar();
        initData();
        registerEvent();
    }

    /**
     * 注册局部变量
     * */
    private void registerLocalVar() {
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        waybill= (Waybill)bundle.getSerializable("waybill");
        carrierBill = findViewById(R.id.carrier_bill);
        inquireTel = findViewById(R.id.inquire_tel);
        weight = findViewById(R.id.weight);
        volume = findViewById(R.id.volume);
        amount = findViewById(R.id.amount);
        subjoinFee = findViewById(R.id.subjoin_fee);
        amountUnitName = findViewById(R.id.amount_unit_name);
    }

    /**
     * 注册事件
     * */
    private void registerEvent() {
        Button btn = findViewById(R.id.submit);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkData())submitUpdate();
            }
        });
        ImageView img = findViewById(R.id.waybill_show_back);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    /**
     * 格式化参数
     * */
    private Map<String,String> formatParam(){
        RadioButton rb = findViewById(amountUnitName.getCheckedRadioButtonId());
        waybill.setCarrierBill(carrierBill.getText().toString());
        waybill.setInquireTel(inquireTel.getText().toString());
        waybill.setAmount(amount.getText().toString().equals("") ? null : Integer.parseInt(amount.getText().toString()));
        waybill.setAmountUnitName(rb.getText().toString());
        waybill.setWeight(weight.getText().toString().equals("") ? null : Double.parseDouble(weight.getText().toString()));
        waybill.setVolume(volume.getText().toString().equals("") ? null : Double.parseDouble(volume.getText().toString()));
        waybill.setSubjoinFee(subjoinFee.getText().toString());
        return new HashMap<String,String>() {{
            put("id",String.valueOf(waybill.getId()));
            put("carrier_bill",waybill.getCarrierBill());
            put("inquire_tel",waybill.getInquireTel());
            put("amount",String.valueOf(waybill.getAmount()));
            put("amount_unit_name",waybill.getAmountUnitName());
            put("carrier_weight_other",waybill.getWeight()==null ? "" : String.valueOf(waybill.getWeight()));
            put("carrier_weight",waybill.getVolume()==null ? "" : String.valueOf(waybill.getVolume()));
            put("subjoin_fee",waybill.getSubjoinFee());
        }};
    }
    private void submitUpdate() {
        WasSubscribe.dispatch(formatParam(), new WasHandlerCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean result) {
                if (result) {
                    back();
                }else{
                    Hint.toastShort(WaybillDispatchItemActivity.this, "服务器拒绝,修改失败", Hint.ERROR);
                }
            }
            @Override
            public void onFault(int code, String errorMsg){
                if (code==0){
                    Hint.toastShort(App.getAppContext(), errorMsg, Hint.COMMON);
                }else {
                    Gson gson = new Gson();
                    LinkedTreeMap<String, ArrayList<String>> err = gson.fromJson(errorMsg, LinkedTreeMap.class);
                    if (err.get("carrier_bill")!=null)carrierBill.setError(err.get("carrier_bill").get(0));
                    if (err.get("inquire_tel")!=null)inquireTel.setError(err.get("inquire_tel").get(0));
                    if (err.get("amount")!=null)amount.setError(err.get("amount").get(0));
                    if (err.get("amount_unit_name")!=null) Hint.toastShort(WaybillDispatchItemActivity.this,"必须选择数量单位",Hint.COMMON);
                    if (err.get("carrier_weight_other")!=null)weight.setError(err.get("carrier_weight_other").get(0));
                    if (err.get("carrier_weight")!=null)volume.setError(err.get("carrier_weight").get(0));
                    if (err.get("subjoin_fee")!=null)subjoinFee.setError(err.get("subjoin_fee").get(0));
                }
            }
        });
    }

    /**
     * 回到主列表
     * */
    private void back()
    {
        Intent intent = new Intent();
        intent.putExtra("waybill", waybill);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 参数检查
     * */
    private boolean checkData() {
        boolean sign = true;
        if (carrierBill.getText()==null || carrierBill.getText().toString().equals("")){
            carrierBill.setError("必填");
            sign = false;
        }
        if (inquireTel.getText()==null || inquireTel.getText().toString().equals("")){
            inquireTel.setError("必填");
            sign = false;
        }
        if ((weight.getText()==null || weight.getText().toString().equals("")) &&
                (volume.getText()==null || volume.getText().toString().equals(""))){
            weight.setError("重量与体积至少填写一项");
            sign = false;
        }
        if ((amount.getText()==null || amount.getText().toString().equals(""))){
            amount.setError("必填");
            sign = false;
        }
        if (amountUnitName.getCheckedRadioButtonId()==0){
            Hint.toastShort(this,"必须选择数量单位",Hint.COMMON);
            sign = false;
        }
        return sign;
    }

    /**
     * 初始化参数
     * */
    private void initData() {
        TextView waybillNumber = findViewById(R.id.waybill_number);
        TextView deliverAt = findViewById(R.id.deliver_at);
        TextView carrierName = findViewById(R.id.carrier_name);
        TextView destination = findViewById(R.id.destination);
        TextView recipient = findViewById(R.id.recipient);
        TextView origination = findViewById(R.id.origination);
        TextView warehouseWeightOther = findViewById(R.id.warehouse_weight_other);
        TextView warehouseWeight = findViewById(R.id.warehouse_weight);

        waybillNumber.setText(waybill.getWaybillNumber());
        deliverAt.setText(waybill.getDeliverAt());
        carrierName.setText(waybill.getCarrierName());
        destination.setText(waybill.getDestination());
        recipient.setText(waybill.getRecipient());
        origination.setText(waybill.getOrigination());
        warehouseWeightOther.setText(waybill.getWarehouseWeightOther()==null ? "" : String.valueOf(waybill.getWarehouseWeightOther()));
        warehouseWeight.setText(waybill.getWarehouseWeight()==null ? "" : String.valueOf(waybill.getWarehouseWeight()));
        carrierBill.setText(waybill.getCarrierBill());
        inquireTel.setText(waybill.getInquireTel());
        weight.setText(waybill.getWeight()==null ? "" : String.valueOf(waybill.getWeight()));
        volume.setText(waybill.getVolume()==null ? "" : String.valueOf(waybill.getVolume()));
        amount.setText(waybill.getAmount()==null ? "" : String.valueOf(waybill.getAmount()));
        subjoinFee.setText(waybill.getSubjoinFee());
        amountUnitName.check(waybill.getAmountUnitName().equals("托") ? R.id.radio_2 : R.id.radio_1);
    }
}
