package com.zhongshu.card.server.core.service.attendance;

import com.github.microservice.auth.security.helper.AuthHelper;
import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.components.data.mongo.mongo.domain.SuperEntity;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.model.attendance.*;
import com.zhongshu.card.client.model.org.UserCountModel;
import com.zhongshu.card.client.model.org.role.RoleModel;
import com.zhongshu.card.client.service.org.UserAccountService;
import com.zhongshu.card.client.type.LeaveQueryType;
import com.zhongshu.card.client.type.LeaveStatus;
import com.zhongshu.card.client.utils.DateUtils;
import com.zhongshu.card.server.core.dao.attendance.LeaveApprovalDao;
import com.zhongshu.card.server.core.dao.attendance.LeaveSettingDao;
import com.zhongshu.card.server.core.dao.dictionary.DictionaryDao;
import com.zhongshu.card.server.core.dao.dictionary.DictionaryItemDao;
import com.zhongshu.card.server.core.dao.org.RoleDao;
import com.zhongshu.card.server.core.dao.org.UserCountDao;
import com.zhongshu.card.server.core.domain.attendance.LeaveApproval;
import com.zhongshu.card.server.core.domain.attendance.LeaveSetting;
import com.zhongshu.card.server.core.domain.dictionary.Dictionary;
import com.zhongshu.card.server.core.domain.dictionary.DictionaryItem;
import com.zhongshu.card.server.core.domain.org.Role;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.server.core.service.base.SuperService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LeaveService extends SuperService {

    @Autowired
    LeaveSettingDao leaveSettingDao;

    @Autowired
    LeaveApprovalDao leaveApprovalDao;

    @Autowired
    RoleDao roleDao;

    @Autowired
    UserCountDao userCountDao;

    @Autowired
    AuthHelper authHelper;

    @Autowired
    DictionaryItemDao dictionaryItemDao;

    @Autowired
    DictionaryDao dictionaryDao;


    public ResultContent setting(LeaveSettingParam param) {
        LeaveSetting leaveSetting = null;
        if (StringUtils.isNotBlank(param.getId())){
            leaveSetting = leaveSettingDao.findTopBySceneId(param.getSceneId());
            if (leaveSetting == null){
                return ResultContent.buildFail("数据不存在");
            }
        }else {
            leaveSetting = new LeaveSetting();
        }
        BeanUtils.copyProperties(param, leaveSetting, "approvalRoles");
        List<Role> roles = new ArrayList<>();
        if (param.getApprovalRoles()!=null && !param.getApprovalRoles().isEmpty()){
            roles = roleDao.findByIdIn(param.getApprovalRoles());
        }
        leaveSetting.setApprovalRoles(roles);
        leaveSettingDao.save(leaveSetting);
        return ResultContent.buildSuccess();
    }

    public ResultContent getSetting(String sceneId) {
        LeaveSetting leaveSetting = leaveSettingDao.findTopBySceneId(sceneId);
        LeaveSettingModel model = new LeaveSettingModel();
        if (leaveSetting != null){
            BeanUtils.copyProperties(leaveSetting, model, "approvalRoles");
            if (leaveSetting.getApprovalRoles()!=null && !leaveSetting.getApprovalRoles().isEmpty()){
                List<String> roleIdList = leaveSetting.getApprovalRoles().stream().map(SuperEntity::getId).toList();
                List<Role> roles = roleDao.findByIdIn(roleIdList);
                List<RoleModel> roleModels = roles.stream().map(role -> {
                    RoleModel roleModel = new RoleModel();
                    if (ObjectUtils.isNotEmpty(role)) {
                        com.zhongshu.card.server.core.util.BeanUtils.copyProperties(role, roleModel);
                    }
                    return roleModel;
                }).toList();
                model.setApprovalRoles(roleModels);
            }
        }
        return ResultContent.buildSuccess(model);
    }

    public ResultContent apply(ApplyLeaveParam param) {

        String projectId = param.getProjectId();
        if (StringUtils.isBlank(projectId)){
            projectId = getCurrentProjectOid();
        }

        LeaveApproval leaveApproval = new LeaveApproval();
        BeanUtils.copyProperties(param, leaveApproval);
        leaveApproval.setProjectId(projectId);

        String approvalUser = param.getApprovalUser();
        if (StringUtils.isBlank(approvalUser)){
            return ResultContent.buildFail("审批人不存在");
        }
        UserAccount approvalUserAccount = userCountDao.findTopByUserId(approvalUser);
        if (approvalUserAccount == null){
            return ResultContent.buildFail("审批人不存在");
        }
        leaveApproval.setApprovalUser(approvalUser);
        leaveApproval.setApprovalUserName(approvalUserAccount.getName());

        String currentUserId = authHelper.getCurrentUser().getUserId();
        UserAccount leaveUserAccount = userCountDao.findTopByUserId(currentUserId);
        if (leaveUserAccount == null){
            return ResultContent.buildFail("申请人不存在");
        }
        leaveApproval.setLeaveUser(currentUserId);
        leaveApproval.setLeaveUserName(leaveUserAccount.getName());
        leaveApproval.setLeaveUserPhone(leaveUserAccount.getPhone());

        leaveApproval.setLeaveStatus(LeaveStatus.Wait);
        leaveApprovalDao.save(leaveApproval);
        return ResultContent.buildSuccess();
    }

    public ResultContent approval(ApprovalLeaveParam param) {
        LeaveApproval leaveApproval = leaveApprovalDao.findTopById(param.getId());
        if (leaveApproval == null){
            return ResultContent.buildFail("请假申请不存在");
        }

        if (!leaveApproval.getLeaveStatus().equals(LeaveStatus.Wait)){
            return ResultContent.buildFail("已审核，请勿重复操作");
        }

        String currentUserId = authHelper.getCurrentUser().getUserId();
        if (!currentUserId.equals(leaveApproval.getApprovalUser())){
            return ResultContent.buildFail("当前登录用户不是审批人");
        }

        if (!param.getLeaveStatus().equals(LeaveStatus.Pass) && !param.getLeaveStatus().equals(LeaveStatus.Refuse)){
            return ResultContent.buildFail("审批状态错误");
        }
        leaveApproval.setLeaveStatus(param.getLeaveStatus());
        leaveApproval.setApprovalRemark(param.getRemark());
        leaveApproval.setApprovalTime(System.currentTimeMillis());
        leaveApprovalDao.save(leaveApproval);
        return ResultContent.buildSuccess();
    }


    /**
     *
     * @return
     */
    public ResultContent page(Pageable pageable, LeaveQueryParam param) {

        String projectId = param.getProjectId();
        if (StringUtils.isBlank(projectId)){
            projectId = getCurrentProjectOid();
        }

        Long startTime = param.getStartTime();
        if (startTime == null || startTime == 0){
            startTime = DateUtils.getSixMonthsAgo();
        }

        if (StringUtils.isBlank(param.getSceneId())){
            return ResultContent.buildFail("sceneId不能为空");
        }
        String userId = authHelper.getCurrentUser().getUserId();
        Page<LeaveApproval> page = leaveApprovalDao.page(pageable, param.getLeaveQueryType(), projectId, param.getSceneId(), userId, startTime, param.getEndTime(), param.getLeaveType(), param.getLeaveStatus(), param.getApprovalUserName(), param.getLeaveUserName(), param.getLeaveUserPhone(), param.getApprovalStartTime(), param.getApprovalEndTime());
        return ResultContent.buildContent(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    public ResultContent pageLeave(Pageable pageable, LeaveQueryParam param) {

        String projectId = param.getProjectId();
        if (StringUtils.isBlank(projectId)){
            projectId = getCurrentProjectOid();
        }

        String userId = authHelper.getCurrentUser().getUserId();
        Page<LeaveApproval> page = leaveApprovalDao.page(pageable, param.getLeaveQueryType(), projectId, param.getSceneId(), userId, param.getStartTime(), param.getEndTime(), param.getLeaveType(), param.getLeaveStatus(), param.getApprovalUserName(), param.getLeaveUserName(), param.getLeaveUserPhone(), param.getApprovalStartTime(), param.getApprovalEndTime());
        return ResultContent.buildContent(PageEntityUtil.concurrent2PageModel(page, this::toModel));
    }

    public LeaveApprovalModel toModel(LeaveApproval leaveApproval) {
        LeaveApprovalModel model = new LeaveApprovalModel();
        if (leaveApproval != null){
            BeanUtils.copyProperties(leaveApproval, model, "approvalUser","leaveUser");

            if (StringUtils.isNotBlank(leaveApproval.getApprovalUser())){
                UserAccount approvalUser = userCountDao.findTopByUserId(leaveApproval.getApprovalUser());
                model.setApprovalUser(toUserCountModel(approvalUser));
            }

            if (StringUtils.isNotBlank(leaveApproval.getLeaveUser())){
                UserAccount leaveUser = userCountDao.findTopByUserId(leaveApproval.getLeaveUser());
                model.setLeaveUser(toUserCountModel(leaveUser));
            }

            if (StringUtils.isNotBlank(leaveApproval.getLeaveType())){
                Dictionary dictionary = dictionaryDao.findTopByProjectIdAndKey(leaveApproval.getProjectId(), "sys_leave_type");
                if (dictionary != null){
                    DictionaryItem item = dictionaryItemDao.findTopByDictionary_IdAndKey(dictionary.getId(), leaveApproval.getLeaveType());
                    if (item != null){
                        model.setLeaveName(item.getName());
                    }
                }

            }
        }
        return model;
    }

    /**
     * 所有数据字段
     *
     * @param entity
     * @return
     */
    public UserCountModel toUserCountModel(UserAccount entity) {
        UserCountModel model = null;
        if (ObjectUtils.isNotEmpty(entity)) {
            model = new UserCountModel();
            com.zhongshu.card.server.core.util.BeanUtils.copyProperties(entity, model);
        }
        return model;
    }

}
