package com.YuyeTech.HeartRate.game.food.service;

import com.YuyeTech.HeartRate.common.service.*;
import com.YuyeTech.HeartRate.enums.FoodEnum;
import com.YuyeTech.HeartRate.game.food.pojo.Food;
import com.YuyeTech.HeartRate.game.food.vo.FoodSimpleVo;
import com.YuyeTech.HeartRate.game.food.vo.FoodVo;
import com.YuyeTech.HeartRate.game.food.repository.FoodRepository;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class FoodServiceImpl extends CommonServiceImpl<FoodVo, Food, Integer> implements FoodService{

    String domain = "https://www.boohee.com";

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private FoodRepository foodRepository;

    @Override
    public Food addFood(Food food) {
        return null;
    }

    @Override
    public List<FoodSimpleVo> getListFromUrl(String url) {

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(domain+url, String.class);
        Document doc = Jsoup.parse(response);
        Element postList = doc.getElementById("main");
        Elements postItems  = postList.getElementsByClass("item clearfix");
        log.info("postList size={}", postItems.size());
        List<FoodSimpleVo>  foodVoList = new ArrayList<>();
        for (Element postItem : postItems) {
            //像jquery选择器一样，获取文章标题元素
            Elements titleEle = postItem.select(".text-box a");
            String detailUrl = domain+titleEle.attr("href");
            log.info("标题:" + titleEle.attr("title"));;
            log.info("详情地址:" + detailUrl);
            String src = postItem.select("img").attr("src");
            log.info("缩略图:" + src);
            Elements describe = postItem.select(".text-box p");
            log.info("描述:" + describe.text());
            log.info("*********************************");
            String[] hrefs = titleEle.attr("href").split("/");
            FoodSimpleVo foodVo = new FoodSimpleVo();
            foodVo.setTitle(titleEle.attr("title"));
            foodVo.setType(hrefs[1]);
            foodVo.setName(hrefs[2]);
            foodVo.setDescribe(describe.text());



            String detailUrlResponse = restTemplate.getForObject(detailUrl, String.class);
            Document detailDoc = Jsoup.parse(detailUrlResponse);

            Element detailMain = detailDoc.getElementById("main");
            Elements detailItems = detailMain.select(".basic-infor li");
            String iconUrl = detailMain.select("img").attr("src");
            foodVo.setIconUrl(iconUrl);
            for (Element _item : detailItems) {
                //像jquery选择器一样，获取文章标题元素
                //Elements titleEle = _item.select(".basic-infor li");
                log.info("b1:" + _item.text().split("：")[0]);
                log.info("b2:" + _item.text().split("：")[1]);
                Elements count =  _item.select(".stress");
                log.info("count:" + count.text() + "K");
                log.info("*********************************");
            }
            Elements infoItems = detailMain.select(".nutr-tag dl").not(".header");
            Elements ddItems = infoItems.select("dd");
            for (Element _ddItem : ddItems) {
                Elements  _name= _ddItem.select(".dt");
                Elements  _num= _ddItem.select(".dd");
                log.info(_name.text() +" = "+_num.text());
                double _value = 0;
                try {
                    _value = Double.parseDouble(_num.text());
                } catch (Exception e) {
                    _value = 0;
                }

                if(_name.text().indexOf("热量")>-1){
                    foodVo.setKcal(_value);

                }else if(_name.text().indexOf("碳水化合物")>-1){
                    foodVo.setCarbohydrate(_value);
                }else if(_name.text().indexOf("脂肪")>-1){
                    foodVo.setFat(_value);
                }else if(_name.text().indexOf("蛋白质")>-1){
                    foodVo.setProtein(_value);
                }else if(_name.text().indexOf("纤维素")>-1){
                    foodVo.setCellulose(_value);
                }
            }
            log.info("*********************************");

            foodVoList.add(foodVo);
        }

        return foodVoList;
    }


    @Override
    public List<Food> getListByIds(List<Integer> ids) {
        return foodRepository.findAllByIdIn(ids);
    }
}
