package com.srs.dormitory.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.srs.common.core.domain.AjaxResult;
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.DmsTransferApplication;
import com.srs.dormitory.domain.Dto.AddTransferApplicationDto;
import com.srs.dormitory.domain.Dto.ApplicationListDto;
import com.srs.dormitory.domain.SrsDormitoryStudent;
import com.srs.dormitory.mapper.DmsApprovalProcessMapper;
import com.srs.dormitory.mapper.DmsTransferApplicationMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.dormitory.mapper.SrsDormitoryStudentMapper;
import com.srs.dormitory.service.IDmsApprovalProcessService;
import com.srs.dormitory.service.IDmsTransferApplicationService;
import com.srs.dormitory.service.ISrsDormitoryStudentService;
import com.srs.stureg.domain.SrsStuReg;
import com.srs.stureg.mapper.SrsStuRegMapper;
import org.springframework.beans.BeanUtils;
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 IDmsTransferApplicationServiceImpl extends ServiceImpl<DmsTransferApplicationMapper, DmsTransferApplication> implements IDmsTransferApplicationService {
    @Autowired
    private SrsDormitoryStudentMapper dormitoryStudentMapper;
    @Autowired
    private DmsApprovalProcessMapper approvalProcessMapper;
    @Autowired
    private SrsStuRegMapper srsStuRegMapper;
    @Autowired
    private SrsStudentMapper srsStudentMapper;
    /**
     * 提交调宿申请表
     * @param applicationDto 请求参数
     * @return
     */
    @Override
    public AjaxResult addTransferApplication(AddTransferApplicationDto applicationDto) {
        String stuNo = SecurityUtils.getUsername();
        //校验该学生是否在本校居住
        SrsDormitoryStudent check = new LambdaQueryChainWrapper<>(dormitoryStudentMapper)
                .eq(SrsDormitoryStudent::getStuNo, stuNo)
                .one();
        if (check==null){
            return AjaxResult.error("您并不在本校居住");
        }
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(2);
        //校验该学生是否已有一个待审批的申请
        Long count = lambdaQuery()
                .eq(DmsTransferApplication::getStuNo, stuNo)
                .in(DmsTransferApplication::getStatus, status)
                .count();
        if (count>0) return AjaxResult.error("您已经提交申请，无法重复提交");
        //插入申请表数据
        DmsTransferApplication application = new DmsTransferApplication();
        application.setReason(applicationDto.getReason());
        application.setStuNo(stuNo);
        application.setCreateBy(stuNo);
        application.setCurrentDormId(check.getDormitoryId());
        application.setCurrentBedId(check.getBedId());
        int insert = baseMapper.insert(application);
        if (insert<=0){
            return AjaxResult.error("添加申请表数据失败");
        }
        //插入审核表数据
        DmsApprovalProcess approvalProcess = new DmsApprovalProcess();
        approvalProcess.setApplyId(application.getId());
        int insertApproval = approvalProcessMapper.insert(approvalProcess);
        if (insertApproval<=0) return AjaxResult.error("添加审核表数据失败");
        return AjaxResult.success();
    }


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

    /**
     * 查看调宿申请列表
     * @param dto
     * @return
     */
    @Override
    public List<Map<String, Object>> getTransferApplicationList(ApplicationListDto dto) {
        String username = SecurityUtils.getUsername();
        dto.setStudentNo(username);
        SecurityUtils.getLoginUser().getUser().getRoles().forEach(item -> {
            if (item.isAdmin()){
                dto.setStudentNo(null);
            }
        });
        return baseMapper.selectTransferApplicationList(dto);
    }

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

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