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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.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.domain.time.SchoolTime;
import yangtz.cs.liu.campus.domain.time.SchoolTimeDetail;
import yangtz.cs.liu.campus.domain.time.SchoolTimeRule;
import yangtz.cs.liu.campus.service.time.ISchoolTimeDetailService;
import yangtz.cs.liu.campus.service.time.ISchoolTimeService;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static yangtz.cs.liu.campus.constant.TimeUseConstant.UN_USE;
import static yangtz.cs.liu.campus.constant.TimeUseConstant.USE;

@RestController
@RequestMapping("/schoolTime")
public class SchoolTimeController extends BaseController {

    @Autowired
    private ISchoolTimeService schoolTimeService;

    @Autowired
    private ISchoolTimeDetailService schoolTimeDetailService;

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

    /**
     * 查询学校时刻列表
     * @param schoolTime
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolTime schoolTime) {
        try {
            startPage();
            List<SchoolTime> list = schoolTimeService.selectSchoolTimeList(schoolTime);
            return getDataTable(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("查询学校时刻列表异常");
        }
    }

    /**
     * 查询排课规则
     * @return
     */
    @GetMapping("/selectRules")
    public TableDataInfo selectRules() {
        try {
            startPage();
            List<SchoolTimeRule> list = schoolTimeService.selectRules();
            return getDataTable(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("查询排课规则异常");
        }
    }

    /**
     * 新增学校时刻
     * @param schoolTime
     * @return
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated SchoolTime schoolTime) {
        return toAjax(schoolTimeService.save(schoolTime));
    }

    /**
     * 修改学校时刻
     * @param schoolTime
     * @return
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated SchoolTime schoolTime) {
        if (StringUtils.isNull(schoolTime.getId())) {
            throw new ServiceException("主键为空");
        }
        return toAjax(schoolTimeService.updateById(schoolTime));
    }

    /**
     * 删除学校时刻
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@PathVariable("ids") List<Long> ids) {
        try {
            LambdaQueryWrapper<SchoolTimeDetail> lqw = new LambdaQueryWrapper<>();
            lqw.in(SchoolTimeDetail::getSchoolTimeId,ids);
            schoolTimeDetailService.remove(lqw);
            return toAjax(schoolTimeService.removeByIds(ids));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new ServiceException("删除数据异常");
        }
    }

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

    /**
     * 修改是否启用
     * @param id
     * @param state
     * @return
     */
    @PutMapping("/changeIsUsed/{id}")
    public AjaxResult changeIsUsed(@PathVariable("id") Long id,String state) {
        /** 将其他启用全部关闭 */
        if (USE.equals(state)) {
            //判断时令是否有内容，如果没有明细数据则不允许启用
            LambdaQueryWrapper<SchoolTimeDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SchoolTimeDetail::getSchoolTimeId,id);
            List<SchoolTimeDetail> details = schoolTimeDetailService.list(lqw);
            if(StringUtils.isNull(details) || details.size() == 0){
                throw new ServiceException("该时刻没有明细数据不允许使用");
            }
            LambdaUpdateWrapper<SchoolTime> luw = new LambdaUpdateWrapper<>();
            luw.eq(SchoolTime::getIsUsed, USE).set(SchoolTime::getIsUsed,UN_USE);
            schoolTimeService.update(luw);
        }
        //判断是否所有时令都关闭，不允许都关闭
        if(UN_USE.equals(state)){
            int noNum = 0;
            List<SchoolTime> times = schoolTimeService.list();
            for(SchoolTime t : times){
                if(!id.equals(t.getId())){
                    if(UN_USE.equals(t.getIsUsed())){
                        noNum++;
                    }
                }
            }
            if(noNum == times.size()-1){
                throw new ServiceException("不允许所有时刻都停用");
            }
        }
        SchoolTime schoolTime = new SchoolTime();
        schoolTime.setIsUsed(state);
        schoolTime.setId(id);
        return toAjax(schoolTimeService.updateById(schoolTime));
    }

    /**
     * 学校时刻导出
     * @param response
     * @param ids
     */
    @PostMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") List<Long> ids) {
        List<SchoolTime> list = schoolTimeService.listByIds(ids);
        ExcelUtil<SchoolTime> util = new ExcelUtil<>(SchoolTime.class);
        util.exportExcel(response, list, "学校时刻");
    }

    /**
     * 学校时刻导出全部
     * @param response
     * @param schoolTime
     */
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response, SchoolTime schoolTime) {
        List<SchoolTime> list = schoolTimeService.selectSchoolTimeList(schoolTime);
        ExcelUtil<SchoolTime> util = new ExcelUtil<>(SchoolTime.class);
        util.exportExcel(response, list, "学校时刻");
    }
}
