package org.linlinjava.jz.db.service;

import com.google.common.collect.Lists;

import org.linlinjava.jz.db.dao.JzTicketActionMapper;
import org.linlinjava.jz.db.domain.JzTicketAction;
import org.linlinjava.jz.db.domain.JzTicketActionExample;
import org.linlinjava.jz.db.dto.JzTicketActionDto;
import org.linlinjava.jz.db.util.JsonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 工单处理过程
 */
@Service
public class JzTicketActionService {
    @Resource
    private JzTicketActionMapper handleMapper;

    public List<JzTicketAction> queryByTocketId(Integer id) {
        JzTicketActionExample example = new JzTicketActionExample();
        example.or().andTicketIdEqualTo(id);
        return handleMapper.selectByExample(example);
    }

    public int add(JzTicketAction handle) {
        handle.setCreateTime(LocalDateTime.now());
        return handleMapper.insertSelective(handle);
    }

    public int updateById(JzTicketAction handle) {
        return handleMapper.updateByPrimaryKeySelective(handle);
    }

    public JzTicketAction findById(Integer id) {
        return handleMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取工单处理历史的最后一个处理人
     * 用于驳回
     *
     * @param ticketId
     * @return
     */
    public Integer queryLastHandler(Integer ticketId) {
        JzTicketActionExample example = new JzTicketActionExample();
        example.or().andTicketIdEqualTo(ticketId);
        example.setOrderByClause(" id desc ");
        JzTicketAction handle = handleMapper.selectOneByExample(example);

        if (handle != null) {
            return handle.getCreateUser();
        }
        return 0;
    }

    public List<Integer> queryTicketByUser(int userId) {
        JzTicketActionExample example = new JzTicketActionExample();
        example.or().andCreateUserEqualTo(userId);
        List<JzTicketAction> handles = handleMapper.selectByExample(example);

        List<Integer> lists = Lists.newArrayList();
        handles.forEach(item -> {
            lists.add(item.getTicketId());
        });

        return lists;
    }
    
    public List<JzTicketActionDto> selectByTicketId(Integer id) {
    	List<Map<String, Object>> selectByTicketId = handleMapper.selectByTicketId(id);
		List<JzTicketActionDto> entity = JsonUtil.jsonToListT(selectByTicketId, JzTicketActionDto.class);
        return entity;
    }
}
