package io.renren.modules.app.controller;

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

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.apache.commons.lang.StringUtils;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.admin.entity.DataBaseEntity;
import io.renren.modules.admin.entity.DataCorrosionEntity;
import io.renren.modules.admin.entity.DataCraftEntity;
import io.renren.modules.admin.entity.DataMechanicsEntity;
import io.renren.modules.admin.entity.DataPhysicalEntity;
import io.renren.modules.admin.entity.DataStructureEntity;
import io.renren.modules.admin.entity.MemberFavoriteEntity;
import io.renren.modules.admin.service.DataBaseService;
import io.renren.modules.admin.service.DataCorrosionService;
import io.renren.modules.admin.service.DataCraftService;
import io.renren.modules.admin.service.DataMechanicsService;
import io.renren.modules.admin.service.DataPhysicalService;
import io.renren.modules.admin.service.DataStructureService;
import io.renren.modules.admin.service.MemberFavoriteService;
import io.renren.modules.app.form.FavoriteForm;
import io.renren.modules.app.utils.JwtUtils;
import io.jsonwebtoken.Claims;

/**
 * 
 *
 * @author huwhois
 * @email huwhois@gmail.com
 * @date 2020-07-22 15:28:24
 */
@RestController
@RequestMapping("/app/data")
public class AppDataController {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private DataBaseService dataBaseService;
    @Autowired
    private DataPhysicalService dataPhysicalService;
    @Autowired
    private DataMechanicsService dataMechanicsService;
    @Autowired
    private DataCraftService dataCraftService;
    @Autowired
    private DataStructureService dataStructureService;
    @Autowired
    private DataCorrosionService dataCorrosionService;
    @Autowired
    private MemberFavoriteService memberFavoriteService;

    /**
     * base列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = dataBaseService.queryAppPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		DataBaseEntity dataBase = dataBaseService.getById(id);
        DataPhysicalEntity dataPhysical = dataPhysicalService.getById(id);
        DataMechanicsEntity dataMechanics = dataMechanicsService.getById(id);
        DataCraftEntity dataCraft = dataCraftService.getById(id);
        DataStructureEntity dataStructure = dataStructureService.getById(id);
        DataCorrosionEntity dataCorrosion = dataCorrosionService.getById(id);
        Map<String, Object> data = new HashMap<>();

        dataBase.setLanmuName("合金介绍");
        data.put("dataBase", dataBase);
        data.put("dataPhysical", dataPhysical);
        data.put("dataMechanics", dataMechanics);
        data.put("dataCraft", dataCraft);
        data.put("dataStructure", dataStructure);
        data.put("dataCorrosion", dataCorrosion);

        // 点击量加 1
        dataBase.setClicks(dataBase.getClicks() + 1L);
        dataBaseService.updateById(dataBase);

        // 会员保存最近访问记录
        saveReCent(dataBase);
        return R.ok().put("data", data);
    }

    /**
     * 热门词
     */
    @GetMapping("/hotword")
    public R hotWord(){
        List<String> list =  memberFavoriteService.getHotWord();
        return R.ok().put("hotword", list);
    }

    /**
     * 同类牌号
     */
    @GetMapping("/similarity/{cid}")
    public R similarity(@PathVariable("cid") Long cid) {
        List<DataBaseEntity> list = dataBaseService.getSimilarityList(cid);
        return R.ok().put("list", list);
    }
 
    /**
     * 
     */
    public void saveReCent(DataBaseEntity dataBase) {
        //获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		
		//获取用户凭证
		String token = request.getHeader("token");
		if(StringUtils.isBlank(token)){
			token = request.getParameter("token");
        }
        // 有登陆token则记录日志, 无则不记录
		if (StringUtils.isNotBlank(token)) {
            Claims claims = jwtUtils.getClaimByToken(token);
			// System.out.println(Long.parseLong(claims.getSubject()));
            Long userId = Long.parseLong(claims.getSubject());
            
            Long did = dataBase.getId();
            MemberFavoriteEntity memberFavoriteEntity = memberFavoriteService.getOneRecent(did, userId);

            if (memberFavoriteEntity !=null ) {
                System.out.println("member_id:" + userId +"-did:"+did+ "-已保存最近浏览记录");
            } else {
                FavoriteForm favorite = new FavoriteForm();
                favorite.setId(dataBase.getId());
                favorite.setCode(dataBase.getCode());
                favorite.setImage(dataBase.getImage());
                favorite.setKeyword(dataBase.getKeyword());
                favorite.setSummary(dataBase.getOverview());
                favorite.setCreateTime(dataBase.getCreateTime());
    
                String content = JSON.toJSONString(favorite);
    
                MemberFavoriteEntity memberFavorite= new MemberFavoriteEntity();
                memberFavorite.setContent(content);
                memberFavorite.setMemberId(userId.longValue());
                memberFavorite.setDid(favorite.getId());
                memberFavorite.setType(2);
        
                memberFavoriteService.save(memberFavorite);
            }

        }
    }
}
