package com.bjzc.bhzhgd.activity.yhpc;

import android.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bjzc.bhzhgd.DBModel.DataBaseYhpc;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.YhpcListAdapter;
import com.bjzc.bhzhgd.base.BaseActivity3;
import com.bjzc.bhzhgd.base.BaseCallBack;
import com.bjzc.bhzhgd.bean.ResultBean3;
import com.bjzc.bhzhgd.bean.YhpcResultBean;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.Api;
import com.bjzc.bhzhgd.utils.GsonUtils;
import com.bjzc.bhzhgd.utils.RetrofitHttpUtils;
import com.bjzc.bhzhgd.utils.SPUtils;

import org.litepal.crud.DataSupport;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class YhpcDataListActivity extends BaseActivity3 {

    ListView lv;
    TextView tvNodata;
    FrameLayout FLLL;
    Button btnSc;
    Button btnDel;
    LinearLayout xmll;


    private List<DataBaseYhpc> list;//本地数据库拿出来显示在listview上
    private List<DataBaseYhpc> removesavelist;//已上传的任务
    private List<DataBaseYhpc> Uploadlist;//要上传的集合
    private YhpcListAdapter adapter;
    private View headView;
    private View head;
    private CheckBox cb;
    private String SCR;


    @Override
    public int getLayoutId() {
        return R.layout.activity_yhpcdatalist;
    }

    @Override
    public void initView() {
        initToolbar("隐患排查上传", "新增", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startActivity(YhpcTakePhotoActivity.class);
            }
        });
        SCR = (String) SPUtils.get(context, Contans.USERID, "");

        lv = findViewById(R.id.lv);
        tvNodata = findViewById(R.id.tv_nodata);
        FLLL = findViewById(R.id.FLLL);
        btnSc = findViewById(R.id.btn_sc);
        btnDel = findViewById(R.id.btn_del);
        xmll = findViewById(R.id.xmll);




        list = new ArrayList<>();
        removesavelist = new ArrayList<>();
        Uploadlist = new ArrayList<>();

        headView = View.inflate(context, R.layout.item_yhpclist, null);
        head = headView.findViewById(R.id.head);
        lv.addHeaderView(headView, null, false);

        cb = headView.findViewById(R.id.cb);
        cb.setOnClickListener(view -> {

            if (cb.isChecked()) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setChecked(true);
                    adapter.notifyDataSetChanged();
                }
            } else {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setChecked(false);
                    adapter.notifyDataSetChanged();
                }
            }
        });

        head.setVisibility(View.VISIBLE);
        lv.setEmptyView(tvNodata);
        getDataInSQL();
        if (adapter == null) {
            setListData();
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 数据库查询获取数据
     */
    private void getDataInSQL() {

        list.clear();
        List<DataBaseYhpc> uploadaqjcsaveList = DataSupport.findAll(DataBaseYhpc.class);
        if (uploadaqjcsaveList.size() != 0) {
            list.addAll(uploadaqjcsaveList);
            FLLL.setVisibility(View.VISIBLE);
            xmll.setVisibility(View.VISIBLE);
        } else {
            FLLL.setVisibility(View.GONE);
            xmll.setVisibility(View.GONE);
        }

    }

    /**
     * 把数据库的数据显示在listview
     */
    private void setListData() {
        adapter = new YhpcListAdapter(context, list, view -> {
            CheckBox checkBox = (CheckBox) view;
            int index = (int) checkBox.getTag();
            list.get(index).setChecked(checkBox.isChecked());
            int count = 0;
            for (int a = 0; a < list.size(); a++) {
                if (list.get(a).isChecked()) {
                    count++;
                }
            }
            cb.setChecked(count == list.size());
            adapter.notifyDataSetChanged();
        });


        lv.setAdapter(adapter);
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            list.get(i - 1).setChecked(!list.get(i - 1).isChecked());
            int count = 0;
            for (int a = 0; a < list.size(); a++) {
                if (list.get(a).isChecked()) {
                    count++;
                }
            }
            cb.setChecked(count == list.size());
            adapter.notifyDataSetChanged();
        });
    }

    /**
     * 把数据库的数据上传给服务器
     */

    private void UploadData() {
        Uploadlist.clear();
        removesavelist.clear();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChecked()) {
                Uploadlist.add(list.get(i));
                removesavelist.add(list.get(i));
            }
        }
        for (DataBaseYhpc dataBaseYhpc : Uploadlist) {
            Map<String, String> map = new HashMap<>();
            map.put("Action", "DJGL_YHPC_SC");
            map.put("TJR", SCR);
            map.put("TJSJ", dataBaseYhpc.getLRSJ());
            map.put("YHWZ", dataBaseYhpc.getWTQY());
            map.put("YHMS", dataBaseYhpc.getWTMS());
            map.put("YHDJ", dataBaseYhpc.getYHDJ());

            String json = GsonUtils.GsonString(map);
            String photopatglist = dataBaseYhpc.getPhotopatglist();
            String yhwz = dataBaseYhpc.getWTQY();


            Api api = RetrofitHttpUtils.getApi(context);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
            api.upload_yhpcxx(body).enqueue(new BaseCallBack<YhpcResultBean>(context) {
                @Override
                public void onSuccess(Call<YhpcResultBean> call, Response<YhpcResultBean> response) {
                    YhpcResultBean bean = response.body();
                    if (bean.getState() == 1) {//如果成功返回 得到ID
                        String ID_Phont = bean.getData();
                        UploadData_photo(ID_Phont, photopatglist, yhwz);
                    } else {
                        showToast("数据出错" + bean.getMsg());
                    }
                }

                @Override
                public void onError(Call<YhpcResultBean> call, Throwable t) {
                }
            });
        }


    }

    public void UploadData_photo(String ID, String photopatglist, String yhwz) {
        MultipartBody.Builder builder;
        String substring = photopatglist.substring(1, photopatglist.length() - 1);
        if (substring.contains(",")) { //多张
            builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            String[] split = substring.split(",");
            for (String imagePath : split) {
                File file = new File(imagePath.trim());
                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                builder.addFormDataPart("file", file.getName(), imageBody);
            }
        } else {//单张
            builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            File file = new File(substring);
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("file", file.getName(), imageBody);
        }
        RetrofitHttpUtils.getApi(context).upload_yhpcPhoto(ID, "0", SCR, builder.build()).enqueue(new BaseCallBack<ResultBean3>(context) {
            @Override
            public void onSuccess(Call<ResultBean3> call, Response<ResultBean3> response) {
                ResultBean3 resultBean = response.body();
                if (resultBean != null) {
                    if (resultBean.getState().equals("1")) {
                        showToast(yhwz + "隐患情况上传成功...");
                        removeData();//上传成功删除本地的数据
                        Uploadlist.clear();//上传成功清除数据
                    } else {
                        showToast(resultBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Call<ResultBean3> call, Throwable t) {

            }
        });

    }

    @Override
    public void initData() {
        onclick();
    }


    private void onclick() {
        btnSc.setOnClickListener(v -> UploadData());//上传数据
        btnDel.setOnClickListener(v -> deleteData());//删除数据

    }
    @Override
    protected void onResume() {
        super.onResume();
        getDataInSQL();
        if (adapter != null) {
            cb.setChecked(false);
            adapter.notifyDataSetChanged();
        }
    }

    //移除上传成功的数据
    private void removeData() {

        for (DataBaseYhpc uploadaqjcsave : removesavelist) {
            DataSupport.deleteAll(DataBaseYhpc.class, "LRSJ = ?", uploadaqjcsave.getLRSJ());
        }

        getDataInSQL();
        if (adapter != null) {
            cb.setChecked(false);
            adapter.notifyDataSetChanged();
        }
    }

    //删除选中的数据
    public void deleteData() {
        final List<DataBaseYhpc> deletes = new ArrayList<>();
        int select = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChecked()) {
                deletes.add(list.get(i));
                select++;
            }
        }

        if (select != 0) {

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setTitle("你确定要删除？");
            builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
            builder.setPositiveButton("确定", (dialog, which) -> {
                //删除数据
                for (DataBaseYhpc uploadaqjcsave : deletes) {
                    DataSupport.deleteAll(DataBaseYhpc.class, "LRSJ = ?", uploadaqjcsave.getLRSJ());

                }
                //刷新界面
                getDataInSQL();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            });
            builder.show();
        } else {
            showToast("你还没有选择项目");
        }
    }

}
