package com.wx.application.adapter.controller;

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

import com.alibaba.fastjson.JSONObject;
import com.wx.application.gorse4j.GorsePage;
import com.wx.application.gorse4j.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.wx.application.adapter.dto.qo.GorseQ;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.core.service.EntrysService;
import com.wx.application.core.service.RiskUserService;
import com.wx.application.gorse4j.GorseService;
import com.wx.application.gorse4j.Item;
import com.wx.application.nebula.graph.query.NebulaModel;
import com.wx.application.nebula.graph.query.NebulaNode;
import com.wx.application.nebula.graph.service.ImportGraphService;
import com.wx.application.nebula.graph.service.NebulaOperateService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RequestMapping("/gorse")
@RestController("gorseController")
public class GorseController extends BaseController {

    @Autowired
    GorseService gorseService;

    @Autowired
    RiskUserService riskUserService;

    @Autowired
    EntrysService entrysService;

    @Autowired
    NebulaOperateService nebulaOperateService;

    @Autowired
    ImportGraphService importGraphService;

    /**
     * 推荐根据userId
     *
     * @param gQo
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/recommend_by_userid")
    public ResponseData recommendByUserId(@RequestBody GorseQ gQo) throws Exception {
        List<String> res = gorseService.getRecommend(gQo.getUserId());
        if (res == null || res.size() == 0) {
            return success();
        }
        Map mQ = new HashMap<>();
        mQ.put("INS_fid", StringUtils.join(res, ","));
        return success(entrysService.queryList(mQ));
    }

    /**
     * 根据列表推荐
     *
     * @param gQo
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/popular_by_category")
    public ResponseData popularByCategory(@RequestBody GorseQ gQo) throws Exception {
        List<Item> res = gorseService.getPopular(gQo.getCategory());
        return success(res);
    }

    @PostMapping(value = "/ipt")
    public ResponseData ipt() throws Exception {
        importGraphService.iptUser();
        importGraphService.iptentrys();
        return success();
    }

    /**
     * 推荐根据知识图谱
     *
     * @param gQo
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/recommend_by_userid_with_graph")
    public ResponseData recommendByUserIdWithGraph(@RequestBody GorseQ gQo) throws Exception {

        NebulaModel nebulaModel = nebulaOperateService.findOnePathById("", gQo.getUserId());
        List<NebulaNode> nodes = nebulaModel.getNodes();

        if (nodes != null && nodes.size() > 0) {
            nodes.get(0).getVid();
        }

        List<String> res = gorseService.getRecommend(gQo.getUserId());
        if (res == null || res.size() == 0) {
            return success();
        }
        Map mQ = new HashMap<>();
        mQ.put("INS_fid", StringUtils.join(res, ","));
        return success(entrysService.queryList(mQ));
    }

    @PostMapping(value = "/get_similar_user")
    public ResponseData getSimilarUser(@RequestBody GorseQ gQo) throws Exception {
        return success(gorseService.getSimilarUser(gQo.getUserId()));
    }

    @PostMapping(value = "/get_recommend_by_user")
    public ResponseData getRecommendByUser(@RequestBody GorseQ gQo) throws Exception {
        return success(gorseService.getRecommendByUser(gQo.getUserId(), gQo.getRecommendation(), gQo.getCategory(), gQo.getN()));
    }

    @PutMapping(value = "/bulk/{type}")
    public ResponseData bulkUserOrItem(@RequestParam Map<String, String> data, @RequestParam("file") MultipartFile file, @PathVariable("type") String type) throws Exception {
        return success(gorseService.bulkUserOrItem(data, file, type));
    }

    @GetMapping(value = "/get_bulk/{type}")
    public String getBulkUserOrItem(@PathVariable("type") String type) {
        return gorseService.getBulkUserOrItem(type);
    }

    @GetMapping(value = "/query_users")
    public ResponseData queryUsers(@RequestParam("cursor") String cursor) throws Exception {
        GorsePage page = gorseService.getUserPageByCursor(cursor);
        if (page.getUsers() == null || page.getUsers().size() == 0) {
            return success(page);
        }
        List<String> ids = new ArrayList<>();
        for (User user : page.getUsers()) {
            ids.add(user.getUserId());
        }
        Map mQ = new HashMap<>();
        mQ.put("INS_fid", StringUtils.join(ids, ","));

        JSONObject obj = new JSONObject();
        obj.put("cursor", page.getCursor());
        obj.put("users", riskUserService.queryList(mQ));
        return success(obj);
    }

    @GetMapping(value = "/query_user/{id}")
    public ResponseData queryUser(@PathVariable("id") String id) {
        User user = null;
        try {
            user = gorseService.getUserById(id);
        } catch (Exception e) {

        }

        if (user == null) {
            return success();
        }
        Map mQ = new HashMap<>();
        mQ.put("EQS_fid", user.getUserId());
        return success(riskUserService.queryUnique(mQ));
    }

    @GetMapping(value = "/query_items")
    public ResponseData queryItems(@RequestParam("cursor") String cursor) throws Exception {
        GorsePage page = gorseService.getItemPageByCursor(cursor);
        if (page.getItems() == null || page.getItems().size() == 0) {
            return success(page);
        }
        List<String> ids = new ArrayList<>();
        for (Item item : page.getItems()) {
            ids.add(item.getItemId());
        }
        Map mQ = new HashMap<>();
        mQ.put("INS_fid", StringUtils.join(ids, ","));

        JSONObject obj = new JSONObject();
        obj.put("cursor", page.getCursor());
        obj.put("items", entrysService.queryList(mQ));
        return success(obj);
    }

    @GetMapping(value = "/query_item/{id}")
    public ResponseData queryItem(@PathVariable("id") String id) {
        Item item = null;
        try {
            item = gorseService.getItemById(id);
        } catch (Exception e) {

        }

        if (item == null) {
            return success();
        }
        Map mQ = new HashMap<>();
        mQ.put("EQS_fid", item.getItemId());
        return success(entrysService.queryUnique(mQ));
    }


}
