package com.example.administrator.zhapp.activity.ajhxcgl;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.zhapp.BaseListViewAdapter.CommonAdapter;
import com.example.administrator.zhapp.BaseListViewAdapter.ViewHolder;
import com.example.administrator.zhapp.DBModel.Qy;
import com.example.administrator.zhapp.DBModel.YhpcInfo;
import com.example.administrator.zhapp.DBModel.Yhpctp;
import com.example.administrator.zhapp.R;
import com.example.administrator.zhapp.activity.BaseActivity;
import com.example.administrator.zhapp.contans.Contans;
import com.example.administrator.zhapp.entity.StatusInfo;
import com.example.administrator.zhapp.utils.GsonUtils;
import com.example.administrator.zhapp.utils.HttpListener;
import com.example.administrator.zhapp.utils.NohttpUtils;
import com.example.administrator.zhapp.utils.UiUtlis;
import com.example.administrator.zhapp.weight.WaitDialog;
import com.orhanobut.logger.Logger;
import com.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import org.litepal.crud.DataSupport;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class YhpclrListActivity extends BaseActivity {

    TextView tvInput;
    ListView lv;
    TextView tvNodata;
    Button btnSc;

    private int requestCount;
    private int successCount;

    private WaitDialog dialog;

    private CommonAdapter<YhpcInfo> adapter;
    private List<YhpcInfo> datas;

    @Override
    public int getContentViewID() {
        return R.layout.activity_yhpclr_list;
    }

    @Override
    protected void initView() {
        lv = findViewById(R.id.lv);
        tvInput = findViewById(R.id.tv_input);
        btnSc = findViewById(R.id.btn_sc);
        tvNodata = findViewById(R.id.tv_nodata);
        tvInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, YhpclrActivity.class);
                intent.putExtra("isUpdate", false);
                startActivityForResult(intent, 200);
            }
        });

        btnSc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scData();
            }
        });

        setBack();
        setTitle("隐患排查");
        datas = new ArrayList<>();

        getSqlData();

        dialog = new WaitDialog(context, "上传中...");

    }

    @Override
    protected void initData() {

    }

    //读取数据库数据
    private void getSqlData() {

        datas.clear();
        datas.addAll(DataSupport.findAll(YhpcInfo.class));

        if (datas.size() == 0) {
            btnSc.setVisibility(View.GONE);
        } else {
            btnSc.setVisibility(View.VISIBLE);
        }

        for (YhpcInfo yhpc : datas) {
            String code = yhpc.getAREACODE();
            List<Qy> qys = DataSupport.where("areacode = ?", code).find(Qy.class);
            if (qys.size() != 0) {
                yhpc.setAREACODE(qys.get(0).getAREANAME());
            }
        }

        setLvAdapter();
    }

    private void setLvAdapter() {

        if (adapter == null) {

            adapter = new CommonAdapter<YhpcInfo>(context, R.layout.item_yhpc, datas) {
                @Override
                protected void convert(ViewHolder viewHolder, YhpcInfo item, int position) {

                    viewHolder.setText(R.id.tv_inputname, "录入人(" + item.getFXR() + ")");
                    viewHolder.setText(R.id.tv_gzqy, item.getAREACODE());
                    viewHolder.setText(R.id.tv_nr, item.getNR());
                    viewHolder.setText(R.id.tv_wt, item.getWT());
                }
            };

            lv.setAdapter(adapter);
            lv.setEmptyView(tvNodata);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Intent intent = new Intent(YhpclrListActivity.this, YhpclrActivity.class);
                    intent.putExtra("guid", datas.get(position).getGUID());
                    intent.putExtra("isUpdate", true);
                    startActivityForResult(intent, 200);
                }
            });
        } else {
            adapter.notifyDataSetChanged();
        }

    }

    private void scData() {

        requestCount = 0;
        successCount = 0;

        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.YHPC, RequestMethod.POST);
        List<YhpcInfo> infos = DataSupport.findAll(YhpcInfo.class);
        if (infos.size() != 0) {
            dialog.show();
            requestCount++;
            String json = "{\"Rows\":" + GsonUtils.GsonString(infos) + ",\"Total\": " + infos.size() + "}";
            System.out.println("json" + json);
            json = new String(json.getBytes(), StandardCharsets.UTF_8);
            request.setDefineRequestBodyForJson(UiUtlis.encoder(json));
            NohttpUtils.getInstance().add(this, 0, request, callback, false, false, "上传中...");


            List<Yhpctp> tps = DataSupport.findAll(Yhpctp.class);

            if (tps.size() != 0) {
                for (Yhpctp tp : tps) {
                    requestCount++;
                    Request<String> request1 = NoHttp.createStringRequest(Contans.IP + Contans.YHPCTP + "?guid=" + tp.getGuid(), RequestMethod.POST);
                    request1.add(Contans.FILEPS, new FileBinary(new File(tp.getPath())));
                    NohttpUtils.getInstance().add(this, 1, request1, callback, false, false, "上传中...");
                }
            }
        } else {
            showToast("没有数据");
        }
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            System.out.println("json" + response.get());
            Logger.json(response.get());
            try {
                StatusInfo info = GsonUtils.GsonToBean(response.get(), StatusInfo.class);
                if (info != null) {
                    if (info.getRows().get(0).getStatus().equals("1")) {
//                        showToast("上传成功");
                        successCount++;
                    } else {
                        showToast("上传失败");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                showToast("数据异常");
                dialog.dismiss();
            }

            if (requestCount == successCount) {
                showToast("上传成功");
                removeData();
                dialog.dismiss();
            }

        }

        @Override
        public void onFailed(int what, Response<String> response) {
            dialog.dismiss();
        }
    };

    private void removeData() {

        DataSupport.deleteAll(YhpcInfo.class);
        List<Yhpctp> tps = DataSupport.findAll(Yhpctp.class);
        for (Yhpctp tp : tps) {
            File file = new File(tp.getPath());
            if (file.isFile()) {
                file.delete();
            }
        }
        DataSupport.deleteAll(Yhpctp.class);

        getSqlData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getSqlData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 200) {
            switch (resultCode) {
                //录入返回
                case 100:
                    getSqlData();
                    break;
                //修改返回
                case 200:
                    getSqlData();
                    break;
            }
        }
    }
}
