package com.example.leudaemialikeme.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.leudaemialikeme.Adapter.CommentAdapter;
import com.example.leudaemialikeme.Model.Blog;
import com.example.leudaemialikeme.Model.Comment;
import com.example.leudaemialikeme.Model.User;
import com.example.leudaemialikeme.R;
import com.example.leudaemialikeme.Utils.OkHttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class BlogDetailActivity extends BaseActivity {
    TextView bTitleView;
    TextView bAuthorNameView;
    TextView bContentView;
    TextView bViewNumView;
    TextView bColNumView;
    TextView bComNumView;
    EditText comEditView;
    TextView comComView;
    ImageView detail_to;
    ImageView search;
    ImageView bColImage;
    Blog blog=new Blog();
    User author;
    List<Comment> commentList=new ArrayList<>();
    CommentAdapter commentAdapter=new CommentAdapter();
    RecyclerView recyclerView;
    LinearLayout detailColView;

    private static ViewPager viewPager; //内导航的碎片的容器
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blogdetail);
        Intent intent=getIntent();//新增bid

        blog.setBid(Integer.parseInt(intent.getStringExtra("bid")));//新增bid
        blog.setBcontent(intent.getStringExtra("bContent"));
        blog.setBtittle(intent.getStringExtra("bTitle"));
        Log.e("传输后的bid",String.valueOf(blog.getBid()));
        blog.setBcollectNum(Integer.parseInt(intent.getStringExtra("bColNum")));
        blog.setBbrowse((Integer.parseInt(intent.getStringExtra("bViewNum"))));
        blog.setUid(Integer.parseInt(intent.getStringExtra("uid")));


        initView();
        setData();
        initClick();
        recyclerView=(RecyclerView)findViewById(R.id.comment_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        commentAdapter=new CommentAdapter();
        initComments();
        Log.e("commentList",String.valueOf(commentList));
        commentAdapter.setMCommentList(commentList);
        recyclerView.setAdapter(commentAdapter);

    }



    private void initComments() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url=BaseActivity.SERVER_URL+"/comment-servlet?action=getCommentByBid";
                Map<String,String> paramMap=new HashMap<String,String>();
                paramMap.put("bid",String.valueOf(blog.getBid()));
                OkHttpUtil.asyPost(url, paramMap, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String jsonStr=response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Gson gson=new Gson();
                                Log.e("comment",jsonStr);
                                Type listType=new TypeToken<List<Comment>>(){}.getType();
                                commentList = gson.fromJson(jsonStr,listType);
                                Log.e("onResponse:commentList",String.valueOf(commentList));
                                bComNumView.setText("("+String.valueOf(commentList.size())+")");
                                commentAdapter.setMCommentList(commentList);
                                recyclerView.setAdapter(commentAdapter);
                            }
                        });
                    }
                });

            }
        }).start();
    }

    private void setBlogAuthorName(String uid){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url = BaseActivity.SERVER_URL + "/main-servlet?action=getUserById";
                    Map<String,String> paramMap = new HashMap<String,String>();
                    paramMap.put("uid", String.valueOf(blog.getUid()));
                    Log.e("设置帖子的作者uid",uid);
                    OkHttpUtil.asyPost(url, paramMap, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String jsonStr = response.body().string();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Gson gson = new Gson(); // 使用 gson 库解析 JSON 数据
//                 创建一个 TypeToken 的匿名子类对象，并调用对象的 getType()方法
//                                    Log.e("Blog's Str",jsonStr);
                                    Type listType = new TypeToken<User>() {}.getType();
                                    author = gson.fromJson(jsonStr, listType);
//                                    bAuthorNameView=findViewById(R.id.author);
                                    bAuthorNameView.setText(author.getUsername());
                                }
                            });
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initView(){
        bTitleView=findViewById(R.id.detail_theme);
        bAuthorNameView=findViewById(R.id.author);
        bContentView=findViewById(R.id.bContent);
        bViewNumView=findViewById(R.id.detail_view_num);
        bColNumView=findViewById(R.id.detail_col_num);
        bComNumView=findViewById(R.id.comment_num);
        comEditView=findViewById(R.id.comment_edit);
        comComView=findViewById(R.id.comment_commit);
        detail_to=findViewById(R.id.detail_to);
        search=findViewById(R.id.detail_to_search);
        detailColView=findViewById(R.id.detail_like);
        detailColView=findViewById(R.id.detail_col);
        bColImage=findViewById(R.id.imageView15);
    }

    private void setData(){
        setBlogAuthorName(String.valueOf(blog.getUid()));
//        setBColNumViewImage(blog.getBid(),BaseActivity.owner.getNetId()); 需要传入登录用户的id
        setBColNumViewImage(blog.getBid(),BaseActivity.owner.getNetId(),2);
        bViewNumView.setText(String.valueOf(blog.getBbrowse()));
        bTitleView.setText(blog.getBtittle());
        bContentView.setText(blog.getBcontent());
        bColNumView.setText(String.valueOf(blog.getBcollectNum()));
    }

    private void setBColNumViewImage(int bid,int uid,int type){
        Map<String,Integer> paramMap=new HashMap<String, Integer>();
        paramMap.put("bid",bid);
        paramMap.put("uid", uid);
        paramMap.put("type",type);
        String url_collect=BaseActivity.SERVER_URL+"/collect-servlet?action=JudgeCollect";
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonStr=OkHttpUtil.synPost(url_collect,paramMap);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("ColNumViewImage-jsonStr",jsonStr);
                        if(!jsonStr.contains("not")){
                            bColImage.setImageResource(R.drawable.collect_pick);
                            bColImage.setTag(R.drawable.collect_pick);
                        }else{
                            bColImage.setImageResource(R.drawable.collect);
                            bColImage.setTag(R.drawable.collect);
                        }
                    }
                });
                System.out.println("更新collect表成功");
            }
        }).start();
    }

    private void initClick(){
        detail_to.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(BlogDetailActivity.this,BlogSearchActivity.class);
                startActivity(intent);
            }
        });

        comComView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String cont = comEditView.getText().toString();

                User user=new User();
                user.setIduser(BaseActivity.owner.getNetId());
                user.setUsername(BaseActivity.owner.getUsername());

                long timeCurrent = System.currentTimeMillis();
                SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Timestamp time = Timestamp.valueOf(sdf.format(timeCurrent));
                Comment comment=new Comment(blog.getBid(),user.getUsername(),time,user.getIduser(),
                        cont,2);
                Map<String,Comment> paramMap=new HashMap<String,Comment>();
                paramMap.put("comment",comment);
                String url=BaseActivity.SERVER_URL+"/comment-servlet?action=insertComment";
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpUtil.asyPost(url, paramMap, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                String jsonStr = response.body().string();
//                               Log.e("提交评论",jsonStr);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        commentList.add(comment);
                                        commentAdapter.setMCommentList(commentList);
                                        recyclerView.setAdapter(commentAdapter);
                                        comEditView.setText("");
                                        bComNumView.setText("("+String.valueOf(commentList.size())+")");
                                    }
                                });
                            }
                        });
                    }
                }).start();


            }
        });

        detailColView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Map<String,Integer> paramMap=new HashMap<String, Integer>();
                paramMap.put("bid",blog.getBid());
                paramMap.put("uid", BaseActivity.owner.getNetId());
                paramMap.put("type",2);
                String url_collect=BaseActivity.SERVER_URL+"/collect-servlet?action=InsertCollect";

                int imageId=getDrawableId(bColImage);
                if(imageId==R.drawable.collect) {
                    bColImage.setImageResource(R.drawable.collect_pick);
                    bColImage.setTag(R.drawable.collect_pick);
                }else {
                    bColImage.setImageResource(R.drawable.collect);
                    bColImage.setTag(R.drawable.collect);
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String jsonStr=OkHttpUtil.synPost(url_collect,paramMap);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(jsonStr.contains("insert")){
                                        bColNumView.setText(String.valueOf(Integer.parseInt(bColNumView.getText().toString())+1));
                                        Toast.makeText(BlogDetailActivity.this,
                                                "已收藏",Toast.LENGTH_SHORT).show();
                                    }else{
                                        bColNumView.setText(String.valueOf(Integer.parseInt(bColNumView.getText().toString())-1));
                                        Toast.makeText(BlogDetailActivity.this,
                                                "取消收藏",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                        System.out.println("更新collect表成功");
                    }
                }).start();
            }
        });
    }

    private int getDrawableId(ImageView iv) {
        return (Integer) iv.getTag();
    }


}
