package com.sipai.jspatrol.Equ;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

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

import com.example.zhouwei.library.CustomPopWindow;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.InfoSel;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.Fault.SingleChoiceActivity;
import com.sipai.jspatrol.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class EquInsertActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_company,tv_processSection;//厂区，工艺段
    private String pSectionId = "";
    private CustomPopWindow mCustomPopWindow;
    private EditText edt_equno,edt_equname;//设备编号，设备名称
    private TextView tv_asset,tv_equtypenum,tv_equclass,tv_equspecification,tv_equlevel,tv_pertain_to_equ;//资产类型,设备型号，设备类型，设备规格，设备级别，所属设备
    private String st_asset,st_equtypenum,st_equclass,st_equspecification,st_equlevel,st_status,st_pertain_to_equ;
    private EditText edt_assetnumber,edt_assetvalue,edt_ratedpower;//资产编号，资产原值/元，额定功率/KW
    private EditText edt_cost_of_labor,edt_residual_rate,edt_installation_date,edt_pro_charge;//人工费/元，残值率，安装日期，采购费/元
    private Button btn_save;//保存
    private Spinner sp_status;
    private List<EditText> edts;
    private EquList sel_equ;
    private ProcessSection sel_ps;
    private static final int ASSETCLASS = 101;
    private static final int EQUTYPENUM = 102;
    private static final int EQUCLASS = 103;
    private static final int EQUSPECIFICATION = 104;
    private static final int EQULEVEL = 105;
    private static final int PERTAINTOEQU = 106;
    private static final int SELPS = 8;//选择工艺段

    public static void actionStart(Context context){
        Intent intent = new Intent(context, EquInsertActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equ_insert);
        init();
        initView();
    }

    private void initView() {
        TextView tv_title = findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("新增设备");
        ImageView btn_back = findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        edts = new ArrayList<>();
        tv_company = findViewById(R.id.moudle_equ_insert_tv_company);
        tv_company.setText(mBizName);
        tv_processSection = findViewById(R.id.moudle_equ_insert_tv_processsection);
        tv_processSection.setOnClickListener(this);
        edt_equno = findViewById(R.id.moudle_equ_insert_edt_equno);
        edt_equname = findViewById(R.id.moudle_equ_insert_edt_equname);
        tv_asset = findViewById(R.id.moudle_equ_insert_tv_asset);
        tv_asset.setOnClickListener(this);
        tv_equtypenum = findViewById(R.id.moudle_equ_insert_tv_equtypenum);
        tv_equtypenum.setOnClickListener(this);
        tv_equclass = findViewById(R.id.moudle_equ_insert_tv_equclass);
        tv_equclass.setOnClickListener(this);
        tv_equspecification = findViewById(R.id.moudle_equ_insert_tv_equspecification);
        tv_equspecification.setOnClickListener(this);
        tv_equlevel = findViewById(R.id.moudle_equ_insert_tv_equlevel);
        tv_equlevel.setOnClickListener(this);
        tv_pertain_to_equ = findViewById(R.id.moudle_equ_insert_tv_pertain_to_equ);
        tv_pertain_to_equ.setOnClickListener(this);
        edt_assetnumber = findViewById(R.id.moudle_equ_insert_edt_assetnumber);
        edt_assetvalue = findViewById(R.id.moudle_equ_insert_edt_assetvalue);
        edt_ratedpower = findViewById(R.id.moudle_equ_insert_edt_ratedpower);
        edt_pro_charge = findViewById(R.id.moudle_equ_insert_edt_pro_charge);
        edt_cost_of_labor = findViewById(R.id.moudle_equ_insert_edt_cost_of_labor);
        edt_residual_rate = findViewById(R.id.moudle_equ_insert_edt_residual_rate);
        edt_installation_date = findViewById(R.id.moudle_equ_insert_edt_installation_date);
        btn_save = findViewById(R.id.moudle_equ_insert_btn_save);
        btn_save.setOnClickListener(this);
        sp_status = findViewById(R.id.moudle_equ_insert_sp_status);
        edts.add(edt_equno);
        edts.add(edt_equname);
        final String[] status = getResources().getStringArray(R.array.equ_status);
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.item_normal_little_spin, R.id.moudle_normal_little_spin_tv_title,status);
        sp_status.setAdapter(arrayAdapter);
        sp_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                st_status = String.valueOf(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case ASSETCLASS:
                if (resultCode==RESULT_OK){
                    InfoSel item = (InfoSel) data.getSerializableExtra("sel");
                    st_asset = item.getId();
                    UpdateTv(tv_asset,item.getText());
                }
                break;
            case EQUTYPENUM:
                if (resultCode==RESULT_OK){
                    InfoSel item = (InfoSel) data.getSerializableExtra("sel");
                    st_equtypenum = item.getId();
                    UpdateTv(tv_equtypenum,item.getText());
                }
                break;
            case EQUCLASS:
                if (resultCode==RESULT_OK){
                    InfoSel item = (InfoSel) data.getSerializableExtra("sel");
                    st_equclass = item.getId();
                    UpdateTv(tv_equclass,item.getText());
                }
                break;
            case EQUSPECIFICATION:
                if (resultCode==RESULT_OK){
                    InfoSel item = (InfoSel) data.getSerializableExtra("sel");
                    st_equspecification = item.getId();
                    UpdateTv(tv_equspecification,item.getText());
                }
                break;
            case EQULEVEL:
                if (resultCode==RESULT_OK){
                    InfoSel item = (InfoSel) data.getSerializableExtra("sel");
                    st_equlevel = item.getId();
                    UpdateTv(tv_equlevel,item.getText());
                }
                break;
            case PERTAINTOEQU:
                if (resultCode==RESULT_OK){
                    EquList sel_equ = (EquList) data.getSerializableExtra("sel");
                    st_pertain_to_equ = sel_equ.getId();
                    UpdateTv(tv_pertain_to_equ,sel_equ.getEquipmentname());
                }
                break;
            case SELPS:
                if (resultCode == RESULT_OK) {
                    sel_ps = (ProcessSection) data.getSerializableExtra("ps");
                    UpdateTv(tv_processSection, sel_ps.getName());
                    pSectionId = sel_ps.getSid();
                }
                break;
        }
    }

    private void UpdateTv(final TextView tv, final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText(text);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_equ_insert_tv_asset:
                Intent intent = new Intent(EquInsertActivity.this, SelActivity.class);
                intent.putExtra("type","assetclass");
                startActivityForResult(intent,ASSETCLASS);
                break;
            case R.id.moudle_equ_insert_tv_equtypenum:
                Intent intent_equtypenum = new Intent(EquInsertActivity.this, SelActivity.class);
                intent_equtypenum.putExtra("type","equtypenum");
                startActivityForResult(intent_equtypenum,EQUTYPENUM);
                break;
            case R.id.moudle_equ_insert_tv_equclass:
                Intent intent_equclass = new Intent(EquInsertActivity.this, SelActivity.class);
                intent_equclass.putExtra("type","equclass");
                startActivityForResult(intent_equclass,EQUCLASS);
                break;
            case R.id.moudle_equ_insert_tv_equspecification:
                Intent intent_equspecification = new Intent(EquInsertActivity.this, SelActivity.class);
                intent_equspecification.putExtra("type","equspecification");
                startActivityForResult(intent_equspecification,EQUSPECIFICATION);
                break;
            case R.id.moudle_equ_insert_tv_equlevel:
                Intent intent_equlevel = new Intent(EquInsertActivity.this, SelActivity.class);
                intent_equlevel.putExtra("type","equlevel");
                startActivityForResult(intent_equlevel,EQULEVEL);
                break;
            case R.id.moudle_equ_insert_tv_pertain_to_equ:
                Intent intent_pertain = new Intent(EquInsertActivity.this, PertainToEquSelActivity.class);
                intent_pertain.putExtra("psectionId",pSectionId);
                startActivityForResult(intent_pertain,PERTAINTOEQU);
                break;
            case R.id.moudle_equ_insert_tv_processsection:
                Intent intent_sel_ps = new Intent(EquInsertActivity.this, SingleChoiceActivity.class);
                intent_sel_ps.putExtra("mark","ps");
                startActivityForResult(intent_sel_ps,SELPS);
                break;
            case R.id.moudle_equ_insert_btn_save:
                if (!isEdtEmpty()) {
                    isRepeated();
//                    subEquInfo();
                }
                break;
        }
    }

    private void isRepeated() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        params.put("equipmentcardid",edt_equno.getText().toString());
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/checkExist.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optBoolean("valid")){
                        subEquInfo();
                    }else {
                        idRepeated();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                if(!EquInsertActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(EquInsertActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("连接失败请重试！")
                                    .setConfirmText("确认")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            isRepeated();
                                        }
                                    }).setCancelText("取消")
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            finish();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    private void idRepeated() {
        if (!EquInsertActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(EquInsertActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("设备编号重复，请修改后提交")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private boolean isEdtEmpty() {
        for (int i=0;i<edts.size();i++){
            if (edts.get(i).getText()==null||edts.get(i).getText().toString().isEmpty()){
                final int finalI = i;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        edts.get(finalI).setError("不能为空");
                    }
                });
                return true;
            }
        }
        return false;
    }

    private void subEquInfo() {
        String st_assetnumber = "";
        if (edt_assetnumber.getText()!=null&&!edt_assetnumber.getText().toString().isEmpty()){
            st_assetnumber = edt_assetnumber.getText().toString();
        }
        String st_assetvalue = "";
        if (edt_assetvalue.getText()!=null&&!edt_assetvalue.getText().toString().isEmpty()){
            st_assetvalue = edt_assetvalue.getText().toString();
        }
        String st_ratedpower = "";
        if (edt_ratedpower.getText()!=null&&!edt_ratedpower.getText().toString().isEmpty()){
            st_ratedpower = edt_ratedpower.getText().toString();
        }
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        params.put("bizid",mBizid);
        params.put("processsectionid",pSectionId);//工艺段id
        params.put("equipmentcardid",edt_equno.getText().toString());//设备编号
        params.put("assetclassid",st_asset);//资产类型id
        params.put("equipmentname",edt_equname.getText().toString());//设备名称 （必填
        params.put("equipmentmodel",st_equtypenum);//设备型号id
        params.put("equipmentclassid",st_equclass);//设备类型id
        params.put("specification",st_equspecification);//设备规格id
        params.put("equipmentlevelid",st_equlevel);//设备级别id
        params.put("equipmentstatus",st_status);//设备状态
        params.put("assetnumber",st_assetnumber);//资产编号
        params.put("pid",mBizid);// 所属设备id
        params.put("equipmentvalue",st_assetvalue);//资产原值
        params.put("ratedpower",st_ratedpower);//额定功率
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/dosave.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                String res = response;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.get("id")!=null){
                        String id = jsonObject.opt("id").toString();
                        subEquInfoProp(id);
                    }else {
                        ErrorDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                ErrorDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    /**
     * 添加附属表信息
     */
    private void subEquInfoProp(final String id) {
        String st_pro_charge = "";
        if (edt_pro_charge.getText()!=null&&!edt_pro_charge.getText().toString().isEmpty()){
            st_pro_charge = edt_pro_charge.getText().toString();
        }
        String st_cost_of_labor = "";
        if (edt_cost_of_labor.getText()!=null&&!edt_cost_of_labor.getText().toString().isEmpty()){
            st_cost_of_labor  = edt_cost_of_labor.getText().toString();
        }
        String st_residual_rate = "";
        if (edt_residual_rate.getText()!=null&&!edt_residual_rate.getText().toString().isEmpty()){
            st_residual_rate = edt_residual_rate.getText().toString();
        }
        String st_installation_date = "";
        if (edt_installation_date.getText()!=null&&!edt_installation_date.getText().toString().isEmpty()){
            st_installation_date = edt_installation_date.getText().toString();
        }
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        RequestParams params = new RequestParams();
        params.put("equipmentId",id);//采购费
        params.put("purchaseMoney",st_pro_charge);//采购费
        params.put("laborMoney ",st_cost_of_labor);//人工费
        params.put("residualValueRate",st_residual_rate);//残值率
        params.put("installDate",edt_installation_date.getText().toString());//安装日期
        AsyncHttpClient client = new AsyncHttpClient();
        client.setCookieStore(myCookieStore);
        client.post(mServer + "equipment/dosaveEquipmentProp.do?", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                String res = response;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.get("id")!=null){
                        String id = jsonObject.opt("id").toString();
                        ShowSuccessDialog();
                    }else {
                        ErrorDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                String a = error.toString();
                ErrorDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

        });
    }

    private void ErrorDialog() {
        if (!EquInsertActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(EquInsertActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("设备录入失败，请重试")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }

    private void ShowSuccessDialog() {
        if (!EquInsertActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(EquInsertActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("成功")
                            .setContentText("设备录入成功")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).show();
                }
            });
        }
    }


    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;
    private String mBizName;

    public void init(){
        SharedPreferences sharedPre=getSharedPreferences("config", MODE_PRIVATE);
        mServer=sharedPre.getString("server", "");
        mUsername=sharedPre.getString("username", "");
        mPassword=sharedPre.getString("password", "");
        mUserid=sharedPre.getString("userid", "");
        mCaption=sharedPre.getString("caption", "");
        mBizid=sharedPre.getString("bizid", "");
        mBizName=sharedPre.getString("bizname", "");
    }

    private void showText(final String st, final TextView tv) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText(st);
            }
        });
    }
}
