package org.linlinjava.jz.db.service;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.util.CollectionUtils;
import org.linlinjava.jz.db.dao.JzTicketMapper;
import org.linlinjava.jz.db.dao.SysUserMapper;
import org.linlinjava.jz.db.domain.*;
import org.linlinjava.jz.db.util.TicketStatusConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

/**
 * 工单处理类 主表
 */
@Service
public class JzTicketService {

    @Resource
    private JzTicketMapper ticketMapper;
    @Resource
    private JzSysUserService sysUserService;

    @Resource
    private CustomerClientService customerClientService;

    @Resource
    private JzTicketActionService actionService;
    
    @Autowired
    private JzTicketRelationService jzTicketRelationService;

    private final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public List<JzTicket> querySelective(Integer userId, String mobile, Integer tab, String sno, Integer orderId, Integer ticketType, Integer status, Integer subStatus, String startTime, String endTime, String updateUser, Integer page, Integer limit, String sort, String order) {
        JzTicketExample example = new JzTicketExample();
        JzTicketExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(mobile)) {
            CustomerClient customerClient = customerClientService.findUserByMobile(mobile);
            int customerId = 0;
            if (customerClient != null) {
                customerId = customerClient.getId().intValue();
            }
            criteria.andCustomerIdEqualTo(customerId);
        }
        if (tab == 2)//超过24小时未完结的工单
        {
            criteria.andCreateTimeLessThan(LocalDateTime.now().plusHours(-24));
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
        } else if (tab == 3)//超过48小时
        {
            criteria.andCreateTimeLessThan(LocalDateTime.now().plusHours(-48));
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
        } else if (tab == 4)//已完成
        {
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_COMPLETED);
        } else if (tab == 5)//我的待处理工单
        {
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
        }


        if (!StringUtils.isEmpty(sno)) {
            criteria.andTicketSnEqualTo(sno);
        }

        if (null != orderId) {
            criteria.andOrderIdEqualTo(orderId);
        }

        if (ticketType != null && ticketType >= 0) {
            criteria.andTicketTypeEqualTo(ticketType);
        }
        if (status != null && status >= 0) {
            criteria.andStatusEqualTo(status.shortValue());
        }

        if (subStatus != null) {
            criteria.andSubstatusEqualTo(subStatus.shortValue());
        }

        if (StringUtils.isNotBlank(startTime)) {
            criteria.andCreateTimeGreaterThanOrEqualTo(LocalDateTime.parse(startTime, df));
        }

        if (StringUtils.isNotBlank(endTime)) {
            criteria.andCreateTimeLessThanOrEqualTo(LocalDateTime.parse(endTime, df));
        }

        if (StringUtils.isNotBlank(updateUser)) {
            List<SysUser> sysUsers = sysUserService.findAdmin(updateUser);
            List<Integer> lists = Lists.newArrayList();
            List<Integer> finalLists = lists;
            sysUsers.forEach(item -> {
                finalLists.add(item.getId().intValue());
            });

            if (CollectionUtils.isEmpty(lists)) {
                lists = Lists.newArrayList(-1);
            }

            criteria.andUpdateUserIn(lists);
        }

        //添加限制条件，当前用户参与过的工单 此处需要优化
        if (null != userId) {
            List<Integer> integers = actionService.queryTicketByUser(userId);

            if (CollectionUtils.isEmpty(integers)) {
                integers = Lists.newArrayList(-1);
            }
            criteria.andIdIn(integers);
        }

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return ticketMapper.selectByExample(example);
    }

    public int add(JzTicket ticket) {
        ticket.setCreateTime(LocalDateTime.now());
        ticket.setUpdateTime(LocalDateTime.now());
        ticketMapper.insertSelective(ticket);
        return ticket.getId();
    }

    public int deleteById(JzTicket ticket) {
        ticket.setUpdateTime(LocalDateTime.now());
        return ticketMapper.updateByPrimaryKeySelective(ticket);
    }

    public int updateById(JzTicket ticket) {
        ticket.setUpdateTime(LocalDateTime.now());
        return ticketMapper.updateByPrimaryKeySelective(ticket);
    }

    public int updateByExample(JzTicket ticket, JzTicketExample example) {
        return ticketMapper.updateByExampleSelective(ticket, example);
    }

    public JzTicket findBySn(String sno) {
        JzTicketExample example = new JzTicketExample();
        example.or().andTicketSnEqualTo(sno);
        return ticketMapper.selectOneByExample(example);
    }


    public JzTicket findById(Integer id) {
        return ticketMapper.selectByPrimaryKey(id);
    }

    public List<JzTicket> selectTicketByMobile(String mobile) {
        JzTicketExample example = new JzTicketExample();
        JzTicketExample.Criteria criteria = example.createCriteria();

        CustomerClient customerClient = customerClientService.findUserByMobile(mobile);
        int customerId = 0;
        if (customerClient != null) {
            customerId = customerClient.getId().intValue();
        }
        criteria.andCustomerIdEqualTo(customerId);


        return ticketMapper.selectByExample(example);
    }

    public List<JzTicket> selectTicketByCustomerId(Integer customerId) {
        JzTicketExample example = new JzTicketExample();
        example.or().andCustomerIdEqualTo(customerId);

        return ticketMapper.selectByExample(example);
    }


    public long count(Integer tab, Integer userId) {
        JzTicketExample example = new JzTicketExample();
        JzTicketExample.Criteria criteria = example.createCriteria();

        if (tab == 2)//超过24小时未完结的工单
        {
            criteria.andCreateTimeLessThan(LocalDateTime.now().plusHours(-24));
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
        } else if (tab == 3)//超过48小时
        {
            criteria.andCreateTimeLessThan(LocalDateTime.now().plusHours(-48));
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
        } else if (tab == 4)//已完成
        {
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_COMPLETED);
        } else if (tab == 5) {//处理中
            criteria.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
        }

        //添加限制条件，当前用户参与过的工单 此处需要优化
        if (null != userId) {
            List<Integer> integers = actionService.queryTicketByUser(userId);

            if (CollectionUtils.isEmpty(integers)) {
                integers = Lists.newArrayList(-1);
            }
            criteria.andIdIn(integers);
        }

        return ticketMapper.countByExample(example);
    }
    
    /**
     	*  我的任务，今日需完成的
     * @param userId
     * @param start
     * @param end
     * @return
     */
    public Long countCurrentDayTicket(Integer userId,LocalDateTime start,LocalDateTime end) {
    	//查ticket_type为2，且handler为user.getSysUserid()，和status是TicketStatusConstant.STATUS_PROCESSING
    	JzTicketExample tickep = new JzTicketExample();
		tickep.or().andTicketTypeEqualTo(2).andHandlerEqualTo(userId)
		.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING)
		.andExpirationTimeBetween(start, end);
		return ticketMapper.countByExample(tickep);
    }
    
    /**
     * 我的任务大于24小时的 
     * @param userId
     * @param time
     * @return
     */
    public Long countTwentyFourTicket(Integer userId,LocalDateTime time) {
    	//查ticket_type为2，且handler为user.getSysUserid()， 大于24
    	JzTicketExample tickep = new JzTicketExample();
		tickep.or().andTicketTypeEqualTo(2).andHandlerEqualTo(userId)
		.andExpirationTimeGreaterThan(time);//大于24
//		.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING)
		return ticketMapper.countByExample(tickep);
    }
    
    /**
     * 超时的任务
     * @param userId
     * @param time
     * @return
     */
    public Long countTaskTimeOut(Integer userId,LocalDateTime time) {
    	//查ticket_type为2，且handler为user.getSysUserid()， 大于24
    	JzTicketExample tickep = new JzTicketExample();
		tickep.or().andTicketTypeEqualTo(2).andHandlerEqualTo(userId)
		.andExpirationTimeLessThan(time)
		.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
		return ticketMapper.countByExample(tickep);
    }
    
    /**
     * 未完成的任务
     * @param userId
     * @return
     */
    public Long countNoComplete(Integer userId) {
    	//查ticket_type为2，且handler为user.getSysUserid()， 大于24
    	JzTicketExample tickep = new JzTicketExample();
		tickep.or().andTicketTypeEqualTo(2).andHandlerEqualTo(userId)
		.andStatusEqualTo(TicketStatusConstant.STATUS_PROCESSING);
		return ticketMapper.countByExample(tickep);
    }
    
    
    public JzTicket getTicketByNoticeId(Integer noticeId) {
    	int ticketId = jzTicketRelationService.findTicketIdByHmAppNoticeId(noticeId);
    	return  findById(ticketId);
    }
}
