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

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.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.controller.exam.ExamDetailController;
import yangtz.cs.liu.campus.domain.time.SchoolTime;
import yangtz.cs.liu.campus.domain.time.SchoolTimeDetail;
import yangtz.cs.liu.campus.service.time.ISchoolTimeDetailService;
import yangtz.cs.liu.campus.vo.time.SchoolTimeDetailVO;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/schoolTimeDetail")
public class SchoolTimeDetailController extends BaseController {

    @Autowired
    private ISchoolTimeDetailService schoolTimeDetailService;

    private Logger log = LoggerFactory.getLogger(SchoolTimeDetailController.class);

    /**
     * 查询学校时刻明细
     * @param schoolTimeId
     * @param schoolTimeDetail
     * @return
     */
    @GetMapping("/list/{schoolTimeId}")
    public TableDataInfo list(@PathVariable("schoolTimeId") Long schoolTimeId, SchoolTimeDetail schoolTimeDetail)
    {
        try {
            schoolTimeDetail.setSchoolTimeId(schoolTimeId);
            //startPage();
            List<SchoolTimeDetailVO> list = schoolTimeDetailService.selectSchoolTimeDetailList(schoolTimeDetail);
            return getDataTable(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("查询学校时刻明细出现异常");
        }
    }

    /**
     * 查询学校时刻明细列表中, 一天总课时数，上下午课时数
     * @param schoolTimeId
     * @return
     */
    @GetMapping("/queryByTimeId/{schoolTimeId}")
    public Map<String, Integer> queryByTimeId(@PathVariable("schoolTimeId") Long schoolTimeId)
    {
        if (StringUtils.isNull(schoolTimeId)){
            throw new BaseException("季节表id不能为空");
        }
        Map<String,Integer> map = new HashMap<String,Integer>();
        Integer totalNum = schoolTimeDetailService.selectTotalCount(schoolTimeId);
        Integer amNum = schoolTimeDetailService.selectAmCount(schoolTimeId);
        Integer pmNum = schoolTimeDetailService.selectPmCount(schoolTimeId);;
        if(pmNum<0 || StringUtils.isNull(pmNum)){
            throw new ServiceException("下午课程数错误");
        }
        map.put("totalNum",totalNum);
        map.put("amNum",amNum);
        map.put("pmNum",pmNum-amNum);
        return map;
    }

    /**
     * 新增学校时刻明细
     * @param schoolTimeId
     * @param schoolTimeDetail
     * @return
     */
    @PostMapping("/add/{schoolTimeId}")
    public AjaxResult addSave(@PathVariable("schoolTimeId") Long schoolTimeId, @RequestBody @Validated SchoolTimeDetail schoolTimeDetail)
    {
        schoolTimeDetail.setSchoolTimeId(schoolTimeId);
        judge(schoolTimeDetail);
        return toAjax(schoolTimeDetailService.save(schoolTimeDetail));
    }

    /**
     * 查询详情学校时刻明细
     * @param id
     * @return
     */
    @GetMapping("/queryOne/{id}")
    public AjaxResult queryOne(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolTimeDetailService.getById(id));
    }

    /**
     * 修改保存学校时刻明细
     * @param schoolTimeDetail
     * @return
     */
    @PutMapping("/edit")
    public AjaxResult editSave(@RequestBody @Validated SchoolTimeDetail schoolTimeDetail) {
        if (StringUtils.isNull(schoolTimeDetail.getId())){
            throw new BaseException("修改主键id不能为空");
        }
        judge(schoolTimeDetail);
        return toAjax(schoolTimeDetailService.updateById(schoolTimeDetail));
    }

    /**判断当前节次是否已存在*/
    public void judge(SchoolTimeDetail schoolTimeDetail){
        Long id = StringUtils.isNull(schoolTimeDetail.getId()) ? -1L : schoolTimeDetail.getId();
        LambdaQueryWrapper<SchoolTimeDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolTimeDetail::getSchoolTimeId,schoolTimeDetail.getSchoolTimeId());
        List<SchoolTimeDetail> list = schoolTimeDetailService.list(lqw);

        if(StringUtils.isNotNull(list) && list.size() > 0){
            //存在数据
            for(SchoolTimeDetail detail : list){
                //排序号一致且id不一样则不允许新增或修改
                if(detail.getSortId().equals(schoolTimeDetail.getSortId()) && detail.getId().longValue() != id.longValue()){
                    throw new ServiceException("该节次已存在");
                }
            }
        }
    }

    /**
     * 删除学校时刻明细
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@PathVariable("ids") List<Long> ids) {
        return toAjax(schoolTimeDetailService.removeByIds(ids));
    }

    /**
     * 导出
     * @param response
     * @param ids
     */
    @PostMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") List<Long> ids) {
        LambdaQueryWrapper<SchoolTimeDetail> lqw = new LambdaQueryWrapper<>();
        lqw.in(SchoolTimeDetail::getId,ids).orderByAsc(SchoolTimeDetail::getSortId);
        //List<SchoolTimeDetail> list = schoolTimeDetailService.listByIds(ids);
        List<SchoolTimeDetail> list = schoolTimeDetailService.list(lqw);
        ExcelUtil<SchoolTimeDetail> util = new ExcelUtil<>(SchoolTimeDetail.class);
        util.exportExcel(response, list, "学校时刻明细");
    }

    /**
     * 导出全部
     * @param response
     * @param schoolTimeDetail
     */
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response, SchoolTimeDetail schoolTimeDetail) {
        List<SchoolTimeDetailVO> list = schoolTimeDetailService.selectSchoolTimeDetailList(schoolTimeDetail);
        ExcelUtil<SchoolTimeDetailVO> util = new ExcelUtil<>(SchoolTimeDetailVO.class);
        util.exportExcel(response, list, "学校时刻明细");
    }

}
