package com.yihu.figure.controller.health;

import com.yihu.figure.controller.BaseController;
import com.yihu.figure.model.health.HealthEduArticle;
import com.yihu.figure.service.health.HealthEduArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by chenweida on 2017/3/15.
 */

@Controller
@RequestMapping(value = "/health/article")
@Api(description = "健康教育文章")
public class HealthEduArticleController extends BaseController {
    @Autowired
    private HealthEduArticleService healthEduArticleService;

    @RequestMapping(value = "/findByKeyword", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据keyword查找文章")
    public String findByKeyword(@ApiParam(name = "keyword", value = "关键字",required = false)
                                @RequestParam(value = "keyword", required = false) String keyword) {
        try {
            if(StringUtils.isEmpty(keyword)){
                keyword="";
            }
            List<HealthEduArticle> healthEduArticle= healthEduArticleService.findByKeyword(keyword);
            JSONArray ja=new JSONArray();
            if(healthEduArticle!=null&&healthEduArticle.size()>0){
                healthEduArticle.stream().forEach( h->{
                    JSONObject jo=new JSONObject();
                    jo.put("title",h.getTitle());
                    jo.put("content",h.getContent());
                    ja.put(jo);
                });
            }
            return write(200, "成功","data",ja);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "生成失败");
        }
    }
}
