package modules.news;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import common.interceptor.LoginInterceptor;
import common.interceptor.empty.EmptyInterface;
import common.interceptor.role.RequiredRoleInterface;
import common.model.News;
import common.utils.http.MyController;
import common.utils.http.MyRet;
import modules.user.UserController;

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

public class NewsController extends MyController {
    @Inject
    NewsService service;

    public void hello() {
        renderJson(MyRet.ok(service.hello()));
    }

    @Before(LoginInterceptor.class)
    @RequiredRoleInterface({UserController.ROLE_CHECK_ADMIN, UserController.ROLE_SUPER_ADMIN})
    @EmptyInterface({"type", "image_list", "title", "content"})
    public void create() {
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);
        News news = new News();

        // 基础属性设置
        String currentUserIdStr = getSessionAttr("user_id");
        if (StrKit.isBlank(currentUserIdStr)) {
            renderJson(MyRet.fail("创建失败: 未获取到用户信息，请重新登录"));
            return;
        }
        news.setOperatorId(new Integer(currentUserIdStr));

        // 类型
        Integer type = requestBodyJson.getInteger("type");
        if (type == null) {
            // 虽然 EmptyInterface 确保了不为空字符串，但可能为 null
            renderJson(MyRet.fail("类型(type)不能为空或格式不正确"));
            return;
        }
        if (type != 1 && type != 2) {
            renderJson(MyRet.fail("类型(type) 只能为 1(公告) 2(资讯)"));
            return;
        }
        news.setType(type);

        // 标题
        String title = requestBodyJson.getString("title");
        news.setTitle(title);
        
        // 内容
        String content = requestBodyJson.getString("content");
        news.setContent(content);

        // 图片数组
        JSONArray imageList = requestBodyJson.getJSONArray("image_list");
        if (imageList == null || imageList.isEmpty()) {
            // EmptyInterface 应该已经保证了 non-null，但可能为空数组
            // 如果图片列表不能为空，这里可以返回错误
            renderJson(MyRet.fail("介绍图URL列表(image_list)不能为空"));
            return;
        }
        news.setImageList(imageList.toJSONString());
        
        // 老三样初始值设置
        news.setCreateTime(System.currentTimeMillis());
        news.setUpdateTime(System.currentTimeMillis());
        news.setIsDeleted(0);

        if (service.save(news)) {
            renderJson(MyRet.ok("资讯创建成功").setData(news));
        } else {
            renderJson(MyRet.fail("资讯创建失败，原因未知，请将此日志提供给开发者" + news).setData(news));
        }
    }

    @Before(LoginInterceptor.class)
    @RequiredRoleInterface({UserController.ROLE_CHECK_ADMIN, UserController.ROLE_SUPER_ADMIN})
    @EmptyInterface({"id"})
    public void update() {
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);
        String id = requestBodyJson.getString("id");

        News news = service.findNewsById(id);

        if (news == null) {
            renderJson(MyRet.fail("news模板获取不合法，该id对应的news不存在：" + id));
            return;
        }
        
        // 基础属性设置
        String currentUserIdStr = getSessionAttr("user_id");
        if (StrKit.notBlank(currentUserIdStr)) {
            news.setOperatorId(new Integer(currentUserIdStr));
        }

        // 类型
        Integer type = requestBodyJson.getInteger("type");
        if (type != null) {
            if (type != 1 && type != 2) {
                renderJson(MyRet.fail("类型(type) 只能为 1(公告) 2(资讯)"));
                return;
            } else {
                news.setType(type);
            }
        }

        // 标题
        String title = requestBodyJson.getString("title");
        if (StrKit.notBlank(title)) {
            news.setTitle(title);
        }

        // 内容
        String content = requestBodyJson.getString("content");
        if (StrKit.notBlank(content)) {
            news.setContent(content);
        }

        // 图片数组
        JSONArray imageList = requestBodyJson.getJSONArray("image_list");
        if (imageList != null && !imageList.isEmpty()) {
            news.setImageList(imageList.toJSONString());
        }
        
        // 更新时间
        news.setUpdateTime(System.currentTimeMillis());

        // 最后执行更新
        if (news.update()) {
            renderJson(MyRet.ok("更新成功").setData(news));
        } else {
            renderJson(MyRet.fail("更新失败，请将此日志复制给开发者" + news).setData(news));
        }
    }

    @EmptyInterface({"id"})
    public void findById() {
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);

        String id = requestBodyJson.getString("id");
        News news = service.findNewsById(id);

        if (news != null) {
            renderJson(MyRet.ok("获取成功").setData(news));
        } else {
            renderJson(MyRet.fail("获取失败，非法请求可能会导致ip封禁！" + id));
        }
    }

    @EmptyInterface({"type"})
    public void homeList() {
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);
        String type = requestBodyJson.getString("type");
        
        renderJson(MyRet.ok("查询成功").setData(service.homeList(type)));
    }
    
    @Before(LoginInterceptor.class)
    @RequiredRoleInterface({UserController.ROLE_CHECK_ADMIN, UserController.ROLE_SUPER_ADMIN})
    @EmptyInterface({"page_size", "page_number"})
    public void newsList() {
        JSONObject requestBodyJson = MyController.getJsonModelByRequestAndType(getRequest(), JSONObject.class);

        // 页面大小
        String pageSizeStr = requestBodyJson.getString("page_size");
        int pageSizeInt;
        try {
            pageSizeInt = Integer.parseInt(pageSizeStr);

            if (pageSizeInt <= 0) {
                renderJson(MyRet.fail("页面大小(page_size)期待是正整数，你传的是: " + pageSizeStr));
                return;
            }
        } catch (Exception e) {
            renderJson(MyRet.fail("页面大小(page_size)格式不正确: " + e.getMessage()));
            return;
        }

        // 页码
        String pageNumberStr = requestBodyJson.getString("page_number");
        int pageNumberInt;
        try {
            pageNumberInt = Integer.parseInt(pageNumberStr);

            if (pageNumberInt <= 0) {
                renderJson(MyRet.fail("页码(page_number)期待是正整数，你传的是: " + pageNumberStr));
                return;
            }
        } catch (Exception e) {
            renderJson(MyRet.fail("页码(page_number)格式不正确: " + e.getMessage()));
            return;
        }

        String keywords = requestBodyJson.getString("keywords");

        // 最终结果封装
        List<News> newsList = service.newsList(pageNumberInt, pageSizeInt, keywords);
        long newsCount = service.count(keywords);

        Map<String, Object> response = new HashMap<>();
        response.put("list", newsList);
        response.put("total_row", newsList.toArray().length);
        response.put("total_page", 1 + (newsList.toArray().length / pageSizeInt));
        response.put("page_size", pageSizeInt);
        response.put("page_number", pageNumberInt);
        response.put("total_user_count", newsCount);

        renderJson(MyRet.ok("查询成功").setData(response));
    }
}
