package yangtz.cs.liu.campus.controller.schoolAtt;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAtt;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAttEa;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAttMon;
import yangtz.cs.liu.campus.service.schoolAtt.ISchoolAttEaService;
import yangtz.cs.liu.campus.service.schoolAtt.ISchoolAttMonService;

import java.util.List;

@RestController
@RequestMapping("/schoolAttEa")
public class SchoolAttEaController extends BaseController {
    @Autowired
    private ISchoolAttEaService eaService;

    @Autowired
    private ISchoolAttMonService monService;

    /**
     * 获取考勤明细-请假详细信息
     */
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(eaService.getById(id));
    }

    /**
     * 新增考勤明细-请假
     */
    @PostMapping("/add/{attMonId}")
    public AjaxResult add(@RequestBody SchoolAttEa schoolAttEa,@PathVariable Long attMonId)
    {
        schoolAttEa.setAttMonId(attMonId);
        eaService.save(schoolAttEa);
        SchoolAttMon mon = monService.getById(attMonId);
        Double t = mon.getAttEa() + schoolAttEa.getTotalTime();
        mon.setAttEa(t);
        return toAjax(monService.updateById(mon));
    }

    /**
     * 修改考勤明细-请假
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolAttEa schoolAttEa)
    {
        if(StringUtils.isNull(schoolAttEa.getId())){
            throw new ServiceException("id不能为空");
        }
        SchoolAttEa ea = eaService.getById(schoolAttEa.getId());
        eaService.updateById(schoolAttEa);
        SchoolAttMon mon = monService.getById(schoolAttEa.getAttMonId());
        Double t = mon.getAttEa() - ea.getTotalTime() + schoolAttEa.getTotalTime();
        mon.setAttEa(t);
        return toAjax(monService.updateById(mon));
    }

    /**
     * 删除考勤明细-请假
     */
    @DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        List<SchoolAttEa> eas = eaService.listByIds(ids);
        SchoolAttMon mon = monService.getById(eas.get(0).getAttMonId());
        Double t = mon.getAttEa();
        for(SchoolAttEa ea : eas){
            t = t - ea.getTotalTime();
        }
        mon.setAttEa(t);
        monService.updateById(mon);
        return toAjax(eaService.removeByIds(ids));
    }
}
