package com.navinfo.outdoor.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.adapter.CapacityMeasureAdapter;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseFragment;
import com.navinfo.outdoor.bean.BolBean;
import com.navinfo.outdoor.bean.ExamBean;
import com.navinfo.outdoor.bean.ExamSubmitBean;
import com.navinfo.outdoor.bean.MeasureBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.DialogCallback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;

import org.json.JSONException;

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

import okhttp3.MediaType;

/**
 * 发现-能力测评条目点击进入测试页面
 */
public class CapacityMeasurementFragment extends BaseFragment implements View.OnClickListener {
    private ImageView ivMeasurementFinish;
    private RecyclerView capacityMeasurementRel;
    private CapacityMeasureAdapter capacityMeasureAdapter;
    private ArrayList<BolBean> bolbean;
    private Button btn;
    private ArrayList<ExamBean> examBeans;

    private String examId;
    private Gson gson;

    public static CapacityMeasurementFragment newInstance(Bundle bundle) {
        CapacityMeasurementFragment fragment = new CapacityMeasurementFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_capacity_eva_web;
    }

    @Override
    protected void initView() {
        super.initView();
        ivMeasurementFinish = (ImageView) findViewById(R.id.iv_measurement_finish);
        capacityMeasurementRel = (RecyclerView) findViewById(R.id.capacity_measurementRel);
        ivMeasurementFinish.setOnClickListener(this::onClick);
        capacityMeasurementRel.setLayoutManager(new LinearLayoutManager(getActivity()));
        capacityMeasureAdapter = new CapacityMeasureAdapter(getActivity());
        capacityMeasurementRel.setAdapter(capacityMeasureAdapter);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(this::onClick);
        gson = new Gson();
    }

    @Override
    protected void initData() {
        super.initData();
        bolbean = new ArrayList<>();
        examBeans = new ArrayList<>();

        initNetWorks(true);
    }

    private void initNetWorks(boolean b) {
        showLoadingDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("id", "11");
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.EXAM_CONTENT)
                .cls(MeasureBean.class)
                .params(httpParams)
                .token(Constant.ACCESS_TOKEN)
                .getRequest(new Callback<MeasureBean>() {
                    @Override
                    public void onSuccess(MeasureBean response, int id) {
                        dismissLoadingDialog();

                        //单选
                        List<MeasureBean.BodyBean.MultiChoiceBean> multiChoice = response.getBody().getMultiChoice();
                        //多选
                        List<MeasureBean.BodyBean.SingleChoiceBean> singleChoice1 = response.getBody().getSingleChoice();

                        if (multiChoice != null) {
                            for (int i = 0; i < multiChoice.size(); i++) {
                                bolbean.add(new BolBean(multiChoice.get(i).getId(), multiChoice.get(i).getQuestion(), multiChoice.get(i).getOption(), true));
                                examId = multiChoice.get(i).getExamId();
                            }
                        }

                        if (singleChoice1 != null) {
                            for (int i = 0; i < singleChoice1.size(); i++) {
                                bolbean.add(new BolBean(singleChoice1.get(i).getId(), singleChoice1.get(i).getQuestion(), singleChoice1.get(i).getOption(), false));
                                examId = singleChoice1.get(i).getExamId();
                            }
                        }

                        if (bolbean != null) {
                            capacityMeasureAdapter.setMeasureList(bolbean);
                        }

                        Log.d("TAG", "onSuccess: " + response.toString() + "sssssssssssss");

                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + e.getMessage());
                    }
                });
        dismissDialog();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_measurement_finish:
                getActivity().finish();
                break;
            case R.id.btn:
                try {
                    if (bolbean != null) {
                        Map<String, String> checkedMap = capacityMeasureAdapter.getCheckedMap();
                        for (int i = 0; i < bolbean.size(); i++) {
                            final String id = bolbean.get(i).getId();
                            if (!checkedMap.containsKey(id) || checkedMap.get(id) == null || ("").equals(checkedMap.get(id))) {
                                Toast.makeText(getActivity(), "有题目未填写答案，请仔细检查！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        for (Map.Entry<String, String> entry : checkedMap.entrySet()) {
                            ExamBean examBean = new ExamBean();
                            examBean.setId(entry.getKey());
                            String value = entry.getValue();
                            String[] valus = value.split(",");
                            List<String> answerList = new ArrayList<>();
                            if (valus!=null) {
                                for (int i = 0; i < valus.length; i++) {
                                    if (valus[i]!=null&&!valus[i].equals("")) {
                                        answerList.add(valus[i]);
                                    }
                                }
                            }

                            examBean.setAnswer(answerList);
                            examBeans.add(examBean);
                        }
                        initExamSubmit();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void initExamSubmit() throws JSONException {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("examId",examId);
        map.put("answerList",examBeans);

        String json = gson.toJson(map);
        examBeans.clear();
        // Log.d("TAG", "initExamSubmit: " + jsonArray.toString());
        OkGo
                // 请求方式和请求url
                .<ExamSubmitBean>post(HttpInterface.EXAM_SUBMIT)
                .upString(json, MediaType.parse("application/json"))
                // 请求的 tag, 主要用于取消对应的请求
                .tag(this)
                .execute(new DialogCallback<ExamSubmitBean>(ExamSubmitBean.class) {
                    @Override
                    public void onSuccess(Response<ExamSubmitBean> response) {
                        dismissLoadingDialog();
                        if (response.code()==200){
                            if (response.body().equals("0")) {
                                MessageDialog.show((AppCompatActivity) getActivity(), "提示", "不通过", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                    @Override
                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                        // Toast.makeText(getContext(), "点击了确定", Toast.LENGTH_SHORT).show();
                                        return false;
                                    }
                                });
                            } else {
                                MessageDialog.show((AppCompatActivity) getActivity(), "提示", "通过", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                    @Override
                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                        // Toast.makeText(getContext(), "点击了确定", Toast.LENGTH_SHORT).show();
                                        return false;
                                    }
                                });
                            }
                        }else {
                            Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                        }
                        Log.d("TAG", "onSuccess: " + response.toString() + "sssssssssssss");

                    }

                    @Override
                    public void onError(Response<ExamSubmitBean> response) {
                        super.onError(response);
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + response.message());
                    }
                });
        dismissDialog();
    }
}