var System=require("../../system");
const http=require("http");
const querystring = require('querystring');
const md5=require("MD5");
const uuidv4 = require('uuid/v4');
var settings=require("../../../config/settings");
const ApiBase =require("../api.base");

/**
 * tmk收藏api
 */
class tmkApi extends ApiBase{
    constructor(){
        super();
        this.cacheManager = System.getObject("db.cacheManager");
        this.service=System.getObject("service.tmkSve");
    };

    //检查appkey
    // async checkKey(obj){
    //     let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(obj.appKey);
    //     if(key==null){
    //         return System.getResult2(null,null,"ok","请检查您的授权KEY");
    //     }
    // };

    //新增收藏
    async addCollect(obj){
        var data = await this.checkKey(obj.appKey);
        if(data && data.status && data.status===-1){
            return data;
        }
        //判断数据是否存在
        var select = await this.service.selectCollect(obj);
        if (select.length ===0) {
            var result = await this.service.insertCollect(obj);
            if (result == null) {
                return {code: -1, msg: "收藏失败！"}
            }
            return {code: 1, msg: "OK"}
        }else {
            return {code: 0, msg: "该数据已存在"}
        }
    }

    //删除收藏
    async delCollect(obj){
        //验证appKey
        var data = await this.checkKey(obj.appKey);
        if(data && data.status && data.status===-1){
            return data;
        }
        //判断数据是否存在
        var select = await this.service.selectCollect(obj);
        if (select.length !==0) {
            var result = await this.service.delCollect(obj);
            if (result == null) {
                return {code: -1, msg: "取消收藏失败！"}
            }
            // return {code: 1, msg: "取消收藏成功！"}
            var collect = await this.service.selectAllCollect(obj);
            if (collect.data.length ===0) {
                return {code: 0, msg: "没有收藏记录"}

            }else {
                return collect;
            }
        }else {
            return {code: 0, msg: "该数据未在收藏队列"}
        }

    }

    //查询所有收藏
    async seleCollect(obj){
        var data = await this.checkKey(obj.appKey);
        if(data && data.status && data.status===-1){
            return data;
        }
        var select = await this.service.selectAllCollect(obj);
        if (select.data.length ===0) {
            return {code: 0, msg: "没有收藏记录"}

        }else {
            return select;
        }
    }
}

module.exports =tmkApi;