package com.mobvista.apptag.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.mobvista.apptag.entity.ECStorage;
import com.mobvista.apptag.entity.ECTag;
import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.ECStorageDao;
import com.mobvista.apptag.mapper.ECTagDao;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.ECStorageService;
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;

/**
 * @package: com.mobvista.apptag.service.impl
 * @author: wangjf
 * @date: 2019-08-13
 * @time: 11:05
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
@Service("ecStorageService")
public class ECStorageServiceImpl implements ECStorageService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private ECTagDao ecTagDao;
    @Autowired
    private ECStorageDao ecStorageDao;

    @Override
    public boolean update(String urlMd5, String userName, String json) {
        ECTag tag = ecTagDao.find(urlMd5);
        User user = userDao.find(userName);
        ECStorage storage = new ECStorage();
        storage.setUrlMd5(urlMd5);
        storage.setPreviewUrl(tag.getPreviewUrl());
        storage.setTag(json);
        storage.setUpdateTime(new Date());
        storage.setUserId(user.getUserId());
        return this.ecStorageDao.save(storage);
    }

    @Override
    public ECStorage find(String urlMd5) {
        return ecStorageDao.find(urlMd5);
    }

    @Override
    public List<ECStorage> list(Query query) {
        List<ECStorage> results;
        PageHelper.startPage(query.getOffset() / query.getLimit() + 1, query.getLimit());
        results = ecStorageDao.list(query.getSearch().toLowerCase());

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

    @Override
    public int count(String search) {
        return ecStorageDao.count(search);
    }
}
