package com.zhongshu.card.server.core.dao.attendance.impl;

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.type.LeaveQueryType;
import com.zhongshu.card.client.type.LeaveStatus;
import com.zhongshu.card.server.core.dao.attendance.LeaveApprovalDao;
import com.zhongshu.card.server.core.dao.attendance.extend.LeaveApprovalDaoExtend;
import com.zhongshu.card.server.core.domain.attendance.LeaveApproval;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

public class LeaveApprovalDaoImpl implements LeaveApprovalDaoExtend {

    @Autowired
    DBHelper dbHelper;

    @Override
    public Page<LeaveApproval> page(Pageable pageable, LeaveQueryType queryType, String projectId, String sceneId, String userId, Long startTime, Long endTime, List<String> leaveType, List<LeaveStatus> leaveStatus) {
        Criteria criteria = new Criteria();

        if (StringUtils.isNotBlank(projectId)){
            criteria.and("projectId").is(projectId);
        }

        if (StringUtils.isNotBlank(sceneId)){
            criteria.and("sceneId").is(sceneId);
        }

        if (leaveType!=null && !leaveType.isEmpty()){
            criteria.and("leaveType").in(leaveType);
        }

//        if (leaveStatus != null && !leaveStatus.isEmpty()){
//            criteria.and("leaveStatus").in(leaveStatus);
//        }

        if (startTime != null && endTime != null){
            criteria.and("createTime").gte(startTime).lte(endTime);
        }

//        if (endTime != null){
//            criteria.and("createTime").lte(endTime);
//        }

        if (LeaveQueryType.Wait.equals(queryType)){
            criteria.and("leaveStatus").is(LeaveStatus.Wait);
            criteria.and("approvalUser").is(userId);
        }else if (LeaveQueryType.Approval.equals(queryType)){
            if (leaveStatus!=null && !leaveStatus.isEmpty()){
                criteria.and("leaveStatus").in(leaveStatus);
            }else {
                criteria.and("leaveStatus").ne(LeaveStatus.Wait);
            }
            criteria.and("approvalUser").is(userId);
        }else if (LeaveQueryType.Apply.equals(queryType)){
            if (leaveStatus!=null && !leaveStatus.isEmpty()){
                criteria.and("leaveStatus").in(leaveStatus);
            }
            criteria.and("leaveUser").is(userId);
        }

        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));

        return dbHelper.pages(query, pageable, LeaveApproval.class);
    }
}
