package com.reyun.service.impl;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.reyun.model.UserViewColumn;
import com.reyun.model.ViewColumn;
import com.reyun.repository.UserViewColumnRepository;
import com.reyun.repository.ViewColumnRepository;
import com.reyun.service.IViewColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by nolan on 28/12/2016.
 * description:
 */
@Service
public class ViewColumnServiceImpl implements IViewColumnService {
    @Autowired
    private ViewColumnRepository viewColumnRepository;
    @Autowired
    private UserViewColumnRepository userViewColumnRepository;

    public List<ViewColumn> findUserViewColumns(Long accountid) {
        List<ViewColumn> itemlist = viewColumnRepository.findAll();
        UserViewColumn userViewColumn = userViewColumnRepository.findByAccount(accountid);
        if (userViewColumn != null && !Strings.isNullOrEmpty(userViewColumn.getViewcolumn())) {
            Iterable<String> viewcolumnList = Splitter.on(",").omitEmptyStrings().trimResults().split(userViewColumn.getViewcolumn());
            List<String> fieldCodeList = Lists.newArrayList(viewcolumnList);

            for (int i = 0; i < itemlist.size(); i++) {
                ViewColumn viewColumn = itemlist.get(i);
                if (fieldCodeList.contains(viewColumn.getFieldcode())) {
                    viewColumn.setIscheck(true);
                }
            }
        }
        return itemlist;
    }

    public void saveUserViewColumn(Long accountid, String viewcolumn) {
        UserViewColumn userViewColumn = this.userViewColumnRepository.findByAccount(accountid);
        if (userViewColumn == null) {
            userViewColumn = new UserViewColumn();
            userViewColumn.setAccount(accountid);
            userViewColumn.setViewcolumn(viewcolumn);
            this.userViewColumnRepository.saveAndFlush(userViewColumn);
        } else {
            userViewColumn.setViewcolumn(viewcolumn);
            this.userViewColumnRepository.saveAndFlush(userViewColumn);
        }
    }
}
