package cn.exploring.engine.server.wx.web;

import cn.exploring.engine.server.core.util.ResponseUtil;
import cn.exploring.engine.server.core.validator.Order;
import cn.exploring.engine.server.core.validator.Sort;
import cn.exploring.engine.server.db.domain.WxKeyword;
import cn.exploring.engine.server.db.domain.WxSearchHistory;
import cn.exploring.engine.server.db.service.WxKeywordService;
import cn.exploring.engine.server.db.service.WxSearchHistoryService;
import cn.exploring.engine.server.wx.annotation.LoginUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品搜索服务
 * <p>
 * 注意：目前搜索功能非常简单，只是基于关键字匹配。
 */
@RestController
@RequestMapping("/wx/search")
@Validated
public class WxSearchController {
    private final Log logger = LogFactory.getLog(WxSearchController.class);

    @Autowired
    private WxKeywordService keywordsService;
    @Autowired
    private WxSearchHistoryService searchHistoryService;

    /**
     * 搜索页面信息
     * <p>
     * 如果用户已登录，则给出用户历史搜索记录；
     * 如果没有登录，则给出空历史搜索记录。
     *
     * @param userId 用户ID，可选
     * @return 搜索页面信息
     */
    @GetMapping("index")
    public Object index(@LoginUser Integer userId) {
        //取出输入框默认的关键词
        WxKeyword defaultKeyword = keywordsService.queryDefault();
        //取出热闹关键词
        List<WxKeyword> hotKeywordList = keywordsService.queryHots();

        List<WxSearchHistory> historyList = null;
        if (userId != null) {
            //取出用户历史关键字
            historyList = searchHistoryService.queryByUid(userId);
        } else {
            historyList = new ArrayList<>(0);
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("defaultKeyword", defaultKeyword);
        data.put("historyKeywordList", historyList);
        data.put("hotKeywordList", hotKeywordList);
        return ResponseUtil.ok(data);
    }

    /**
     * 关键字提醒
     * <p>
     * 当用户输入关键字一部分时，可以推荐系统中合适的关键字。
     *
     * @param keyword 关键字
     * @return 合适的关键字
     */
    @GetMapping("helper")
    public Object helper(@NotEmpty String keyword,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        List<WxKeyword> keywordsList = keywordsService.queryByKeyword(keyword, page, size);
        String[] keys = new String[keywordsList.size()];
        int index = 0;
        for (WxKeyword key : keywordsList) {
            keys[index++] = key.getKeyword();
        }
        return ResponseUtil.ok(keys);
    }

    /**
     * 清除用户搜索历史
     *
     * @param userId 用户ID
     * @return 清理是否成功
     */
    @PostMapping("clearhistory")
    public Object clearhistory(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        searchHistoryService.deleteByUid(userId);
        return ResponseUtil.ok();
    }

    /**
     * 搜索
     * @param keyword 关键字
     */
    @GetMapping("search")
    public Object search(@LoginUser Integer userId, @NotEmpty String keyword, @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer limit,
                         @Sort @RequestParam(defaultValue = "add_time") String sort,
                         @Order @RequestParam(defaultValue = "desc") String order) {

        // 如果userid不为空，则存入搜索库
        if (userId != null) {
            WxSearchHistory history = new WxSearchHistory();
            history.setFrom("小程序");
            history.setKeyword(keyword);
            history.setUserId(userId);
            LocalDateTime now = LocalDateTime.now();
            history.setAddTime(now);
            history.setUpdateTime(now);
            history.setDeleted(false);
            searchHistoryService.save(history);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("activities", null);
        data.put("oplogs", null);
        data.put("members", null);
        return ResponseUtil.ok(data);
    }
}
