package com.mobvista.apptag.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.entity.ECTag;
import com.mobvista.apptag.entity.ECTagResult;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.ECResultDao;
import com.mobvista.apptag.mapper.ECTagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.ECResultService;
import com.mobvista.apptag.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangjf
 */
@Service("ecResultService")
public class ECResultServiceImpl implements ECResultService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private ECTagDao ecTagDao;
    @Autowired
    private ECResultDao ecResultDao;

    @Override
    public boolean save(String urlMd5, String userName, String json) {
        ECTag tag = ecTagDao.find(urlMd5);
        User user = userDao.find(userName);
        ECTagResult tagResult = new ECTagResult();
        tagResult.setPreviewUrl(tag.getPreviewUrl());
        tagResult.setUrlMd5(urlMd5);
        tagResult.setFeatId(json);
        tagResult.setComment("comment");
        tagResult.setUserId(user.getUserId());
        tagResult.setUpdateTime(new Date());
        if (user.getRole() == 1) {
            ecResultDao.delete(urlMd5);
        }
        return this.ecResultDao.save(tagResult);
    }

    @Override
    public ECTagResult find(String urlMd5, String userId) {
        return ecResultDao.find(urlMd5, userId);
    }

    @Override
    public List<ECTagResult> list(String userId, Query query) {
        User user = userDao.find(userId);
        List<ECTagResult> results;
        PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        if (user.getRole() == 0) {
            results = ecResultDao.list(userId, query.getSearch().toLowerCase());
        } else {
            results = ecResultDao.listAll(query.getSearch().toLowerCase());
        }

        List<ECTagResult> results2 = new ArrayList<>();
        for (ECTagResult result : results) {
            JSONObject jsonObject = JSONObject.parseObject(result.getFeatId());
            result.setFeatId(jsonObject.values().toString());
            results2.add(result);
        }
        return results2;
    }

    @Override
    public int count(String userId, String search) {
        User user = userDao.find(userId);
        if (user.getRole() == 0) {
            return ecResultDao.count(userId, search);
        } else {
            return ecResultDao.countAll(search);
        }
    }
}