package com.srs.dormitory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.common.utils.SecurityUtils;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.dormitory.domain.DmsApprovalProcess;
import com.srs.dormitory.domain.DmsCheckoutApplication;
import com.srs.dormitory.domain.Dto.AddDmsOffcampusApplicationDto;
import com.srs.dormitory.domain.Dto.ApplicationListDto;
import com.srs.dormitory.domain.SrsDormitoryStudent;
import com.srs.dormitory.mapper.DmsApprovalProcessMapper;
import com.srs.dormitory.mapper.DmsCheckoutApplicationMapper;
import com.srs.dormitory.service.IDmsApprovalProcessService;
import com.srs.dormitory.service.IDmsCheckoutApplicationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.dormitory.service.ISrsDormitoryStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 退宿申请表 服务实现类
 * </p>
 *
 * @author szz
 * @since 2023年07月26日
 */
@Service
public class IDmsCheckoutApplicationServiceImpl extends ServiceImpl<DmsCheckoutApplicationMapper, DmsCheckoutApplication> implements IDmsCheckoutApplicationService {
    @Autowired
    private ISrsDormitoryStudentService srsDormitoryStudentService;
    @Autowired
    private DmsApprovalProcessMapper dmsApprovalProcessMapper;
    @Autowired
    private SrsStudentMapper srsStudentMapper;
    /**
     * 学生提交退宿申请
     * @param dto 请求参数
     * @return
     */
    @Override
    @Transactional
    public AjaxResult addDormitoryCheckoutApplication(AddDmsOffcampusApplicationDto dto) {
        String username = SecurityUtils.getUsername();
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(2);
        //校验该学生是否有待审核的退宿申请或审核未完成的申请
        Long count = lambdaQuery().eq(DmsCheckoutApplication::getStuNo, username)
                .in(DmsCheckoutApplication::getStatus, status)
                .count();
        if (count>0){
            return AjaxResult.error("您已经提交申请，无法重复提交");
        }
        //校验该学生是否有床位
        SrsDormitoryStudent checkHas = srsDormitoryStudentService.lambdaQuery()
                .eq(SrsDormitoryStudent::getStuNo, username)
                .one();
        if (checkHas==null) return AjaxResult.error("您并不在本校住宿");
        DmsCheckoutApplication application = new DmsCheckoutApplication();
        application.setOutTime(dto.getOutTime());
        application.setReason(dto.getReason());
        application.setStuNo(username);
        application.setCreateBy(SecurityUtils.getUsername());
        application.setStatus(0);
        application.setCurrentDormId(checkHas.getDormitoryId());
        int insert = baseMapper.insert(application);
        if (insert<=0){
            return AjaxResult.error("添加申请表失败");
        }
        DmsApprovalProcess approvalProcess = new DmsApprovalProcess();
        approvalProcess.setApplyId(application.getId());
        int insert1 = dmsApprovalProcessMapper.insert(approvalProcess);
        if (insert1 <= 0 ) return AjaxResult.error("添加审核数据失败");
        return AjaxResult.success();
    }
    /**
     * 查看退宿申请列表
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> getApplicationList(ApplicationListDto params) {
        String username = SecurityUtils.getUsername();
        params.setStudentNo(username);
        SecurityUtils.getLoginUser().getUser().getRoles().forEach(item -> {
            if (item.isAdmin()){
                params.setStudentNo(null);
            }
        });
        return baseMapper.getApplicationList(params);
    }

    /**
     * 查看退宿申请表详情
     * @param id 退宿申请表ID
     * @return
     */
    @Override
    public AjaxResult getInfo(Long id) {
        Map<String, Object> map = baseMapper.selectInfo(id);
        if (map.get("createTime") != null){
            map.put("createTime",map.get("createTime").toString().replace('T',' '));
        }
        return AjaxResult.success(map);
    }

    /**
     * 批量删除退宿申请
     * @param ids 退宿申请id列表
     * @return
     */
    @Transactional
    @Override
    public AjaxResult batchDelete(List<Long> ids) {
//        boolean removeApproval = dmsApprovalProcessService.lambdaUpdate()
//                .eq(DmsApprovalProcess::getApplicationType, 1)
//                .in(DmsApprovalProcess::getApplicationId, ids)
//                .remove();
//        if (!removeApproval) throw new RuntimeException("删除审核流程失败");
//        boolean removeApplication = removeBatchByIds(ids);
//        if (!removeApplication) throw new RuntimeException("删除申请表失败");
        return AjaxResult.success();
    }

    /**
     * 学生取消提交申请
     * @param id 申请表id
     * @return
     */
    @Override
    public AjaxResult cancel(Long id) {
        String username = SecurityUtils.getUsername();
        DmsCheckoutApplication application = getById(id);
        if (application == null) return AjaxResult.error("id错误");
        if (application.getStatus() != 0) return AjaxResult.error("该申请表无法取消");
        if (!application.getStuNo().equals(username)) return AjaxResult.error("您无法取消该申请表");
        application.setStatus(7);
        boolean update = updateById(application);
        if (!update) return AjaxResult.error("取消失败");
        return AjaxResult.success();
    }
}
