package com.emr.service.ipml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emr.dao.Emr_LogMapper;
import com.emr.entity.Emr_Log;
import com.emr.entity.Emr_Log_Vo;
import com.emr.entity.OffsetLimitPage;
import com.emr.service.LogService;
import com.emr.service.PowerUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class LogServiceImpl implements LogService {
    @Autowired
    private Emr_LogMapper logMapper;

    @Autowired
    private PowerUserService powerUserService;

    @Override
    public int insert(Emr_Log log) {
        return logMapper.insert(log);
    }

    @Override
    public int insertSelective(Emr_Log log) {
        return logMapper.insertSelective(log);
    }

    @Override
    public void deleteLogById(Integer logId) {
        logMapper.deleteByPrimaryKey(logId);
    }

    @Override
    public OffsetLimitPage selectByCol(Emr_Log_Vo emr_log_vo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Emr_Log_Vo> newsInfoList = logMapper.selectByCol(emr_log_vo);

        JSONArray powerUsers = powerUserService.getPowerUserList("1");
        List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
        if (powerUserList != null){
            Map<String,JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject,String>() {
                @Override
                public String apply(JSONObject temp) {
                    return temp.getString("userName");
                }});

            for (Emr_Log_Vo emrLogVo : newsInfoList) {
                JSONObject userInfo = mappedMovies.get(emrLogVo.getCreater());
                if (userInfo==null){
                    emrLogVo.setCreater(emrLogVo.getCreater());
                }else {
                    emrLogVo.setCreater(userInfo.getString("name"));
                }
            }

        }

        return new OffsetLimitPage((Page) newsInfoList);
    }

    @Override
    public List<Emr_Log_Vo> selectByCol(Emr_Log_Vo emr_log_vo) {
        return logMapper.selectByCol(emr_log_vo);
    }

    @Override
    public Emr_Log lastBylogTitle(String logTitle) {
        return logMapper.lastBylogTitle(logTitle);
    }


}
