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

import java.text.ParseException;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.schoolDuty.SchoolDuty;
import yangtz.cs.liu.campus.domain.schoolDuty.SchoolDutyDetails;
import yangtz.cs.liu.campus.service.schoolDuty.ISchoolDutyDetailsService;
import yangtz.cs.liu.campus.service.schoolDuty.ISchoolDutyService;
import yangtz.cs.liu.campus.util.TemplateExcelUtils;
import yangtz.cs.liu.campus.vo.schoolDuty.*;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static yangtz.cs.liu.campus.constant.DutyType.DORMITORYNUM;
import static yangtz.cs.liu.campus.constant.DutyType.GUARDNUM;


/**
 * 值班管理明细Controller
 */
@RestController
@RequestMapping("/dutyDetails")
public class SchoolDutyDetailsController extends BaseController {
    @Autowired
    private ISchoolDutyDetailsService schoolDutyDetailsService;

    @Autowired
    private ISchoolDutyService schoolDutyService;

    /**
     * 查询值班管理明细列表
     */
    @GetMapping("/list/{dutyId}")
    public TableDataInfo list(@PathVariable("dutyId") Long dutyId, SchoolDutyDetails schoolDutyDetails) {
//        startPage();
        try {
            schoolDutyDetails.setDutyId(dutyId);
            List<SchoolDutyDetails> list = schoolDutyDetailsService.selectSchoolDutyDetailsList(schoolDutyDetails);
            return getDataTable(list);
        } catch (Exception e) {
            throw new SecurityException("查询值班管理明细出现异常");
        }
    }

    /**
     * 选择日期时触发
     * */
    @GetMapping("/getWeek/{dutyDeDate}")
    public AjaxResult getWeek(@PathVariable String dutyDeDate){
        String dutyDeWeek = DateUtils.dateToWeek(dutyDeDate);
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("dutyDeWeek",dutyDeWeek);
        return ajaxResult;
    }

    /**
     * 导出值班管理明细列表
     */
    @Log(title = "值班管理明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolDutyDetails schoolDutyDetails) {
        List<SchoolDutyDetails> list = schoolDutyDetailsService.selectSchoolDutyDetailsList(schoolDutyDetails);
        ExcelUtil<SchoolDutyDetails> util = new ExcelUtil<SchoolDutyDetails>(SchoolDutyDetails.class);
        util.exportExcel(response, list, "值班管理明细数据");
    }

    /**
     * 获取值班管理明细详细信息
     */
    @GetMapping(value = "/queryById/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolDutyDetailsService.getById(id));
    }

    /**
     * 新增值班管理明细
     */

    @Log(title = "值班管理明细", businessType = BusinessType.INSERT)
    @PostMapping("/add/{dutyId}")
    public AjaxResult add(@PathVariable("dutyId") Long dutyId, @RequestBody SchoolDutyDetails schoolDutyDetails) {
        schoolDutyDetails.setDutyId(dutyId);
        judgePerson(schoolDutyDetails);
        schoolDutyDetails.insert();
        return toAjax(schoolDutyDetailsService.save(schoolDutyDetails));
    }

    /**
     * 修改值班管理明细
     */

    @Log(title = "值班管理明细", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolDutyDetails schoolDutyDetails) {
        if (StringUtils.isNull(schoolDutyDetails.getId())) {
            throw new ServiceException("id为空");
        }
        judgePerson(schoolDutyDetails);
        return toAjax(schoolDutyDetailsService.updateById(schoolDutyDetails));
    }

    /**
     * 判断日期是否合法，改天该值班类型是否已有人
     * */
    public void judgePerson(SchoolDutyDetails details){
        SchoolDuty duty = schoolDutyService.getById(details.getDutyId());
        //判断日期是否在该值班日期范围内
        if(StringUtils.isNotNull(details.getDutyDeDate())){
            boolean flag = DateUtils.isEffectiveDate(details.getDutyDeDate(),duty.getStartDate(),duty.getEndDate());
            if(!flag){
                throw new ServiceException("日期不在范围内");
            }
        }

        //改天值班类型是否已存在
        LambdaQueryWrapper<SchoolDutyDetails> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolDutyDetails::getDutyId,details.getDutyId())
                .eq(isNotNull(details.getDutyDeDate()),SchoolDutyDetails::getDutyDeDate,details.getDutyDeDate())
                .eq(SchoolDutyDetails::getDutyDeType,details.getDutyDeType());
        List<SchoolDutyDetails> list = schoolDutyDetailsService.list(lqw);
        if (isNotNull(list) || list.size() > 0) {
            //门卫，宿舍
            if(details.getDutyDeType().equals(GUARDNUM) || details.getDutyDeType().equals(DORMITORYNUM)){
                if(StringUtils.isNull(details.getId()) || !details.getId().equals(list.get(0).getId())){
                    throw new ServiceException("本寒暑假该值班类型已存在");
                }
            }

            if(StringUtils.isNull(details.getId()) || !details.getId().equals(list.get(0).getId())){
                throw new ServiceException("本日期该值班类型已存在");
            }

        }
    }

    /**
     * 删除值班管理明细
     */

    @Log(title = "值班管理明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable("ids") List<Long> ids) {
//        return toAjax(schoolDutyDetailsService.deleteSchoolDutyDetailsByIds(ids));
        return toAjax(schoolDutyDetailsService.removeByIds(ids));
    }


    /**
     * 下载模板
     *
     * @param response
     * @param dutyId   值班主id
     */
    @PostMapping("/importTemplate/{dutyId}")
    public void importTemplate(HttpServletResponse response, @PathVariable("dutyId") Long dutyId) throws ParseException {
        ExcelUtil<SchoolDutyDetails> util = new ExcelUtil<SchoolDutyDetails>(SchoolDutyDetails.class);
        SchoolDuty schoolDuty = schoolDutyService.getById(dutyId);
        List<SchoolDutyDetails> list = schoolDutyDetailsService.getDuty(schoolDuty.getStartDate(), schoolDuty.getEndDate());
        util.exportExcel(response, list, "值班模板表");
    }

    /**
     * 下载模板节日
     *
     * @param response
     * @param dutyId   值班主id
     */
    @PostMapping("/importHolidayTemplate/{dutyId}")
    public void importHolidayTemplate(HttpServletResponse response, @PathVariable("dutyId") Long dutyId) throws ParseException {
        ExcelUtil<SchoolDutyDetails> util = new ExcelUtil<SchoolDutyDetails>(SchoolDutyDetails.class);
        SchoolDuty schoolDuty = schoolDutyService.getById(dutyId);
        List<SchoolDutyDetails> list = schoolDutyDetailsService.getHoildayDuty(schoolDuty.getStartDate(), schoolDuty.getEndDate());
        util.exportExcel(response, list, "节日值班模板表");
    }

    /**
     * 导入
     */
    @PostMapping("/importData/{dutyId}")
    public AjaxResult importData(MultipartFile file, @PathVariable("dutyId") Long dutyId) throws Exception {
        ExcelUtil<SchoolDutyDetails> util = new ExcelUtil<SchoolDutyDetails>(SchoolDutyDetails.class);
        List<SchoolDutyDetails> list = util.importExcel(file.getInputStream());
        schoolDutyDetailsService.checkData(list, dutyId);
        String message = schoolDutyDetailsService.importDutyDetails(list, dutyId);
        return AjaxResult.success(message);
    }

    /**节日值班表查看*/
    @GetMapping("/queryHoilday/{id}")
    public AjaxResult queryHoilday( @PathVariable Long id){
        DutyHoildayVo vo = schoolDutyDetailsService.selectHoliday(id);
        return AjaxResult.success(vo);
    }

    /**节日值班表下载*/
    @PostMapping("/downloadHoilday/{id}")
    public void downloadHoilday(@PathVariable Long id,  HttpServletResponse response) throws Exception {
        ExcelUtil<DownHoilday> util = new ExcelUtil<DownHoilday>(DownHoilday.class);
        List<DownHoilday> list = new ArrayList<>();
        DownHoilday d = new DownHoilday();
        DutyHoildayVo vo = schoolDutyDetailsService.selectHoliday(id);
        d.setHolidayName(vo.getHolidayName());
        d.setList(vo.getList());
        list.add(d);
        util.exportExcel(response, list,"节日值班表",vo.getDutyName());
    }

    /**寒暑假值班表查看*/
    @GetMapping("/queryVacation/{id}")
    public AjaxResult queryVacation( @PathVariable Long id){
        DutyVacationVo vo = schoolDutyDetailsService.selectVacation(id);
        return AjaxResult.success(vo);
    }

    /**寒暑假值班表下载*/
    @PostMapping("/downloadVacation/{id}")
    public void downloadVacation2( @PathVariable Long id, HttpServletResponse response) throws Exception {
        DutyVacationVo vo = schoolDutyDetailsService.selectVacation(id);
        DownVacation vacation = new DownVacation();
        BeanUtils.copyProperties(vo,vacation);
        VacationDetailsVo detailsVo = vacation.getList().get(0);
        vacation.setGuardPerson(detailsVo.getGuardPerson());
        vacation.setGuardTel(detailsVo.getGuardTel());
        vacation.setGuardPhone(detailsVo.getGuardPhone());
        vacation.setDormPerson(detailsVo.getDormPerson());
        vacation.setDormPhone(detailsVo.getDormPhone());

        try {

            Resource classPathResource = new ClassPathResource("template/template1.xlsx");
            //获取模板文件绝对路径
            //String absolutePath = classPathResource.getAbsolutePath();
            TemplateExportParams params = new TemplateExportParams(TemplateExcelUtils.convertTemplatePath("template/template1.xlsx"));

            Map<String, Object> finalMap = new HashMap<String, Object>();
            List<DownVacation> list = new ArrayList<>();
            list.add(vacation);
            finalMap.put("downVacationList",list);
            finalMap.put("remarks",vacation.getRemarks());
            finalMap.put("guardTel",vacation.getGuardTel());
            finalMap.put("dutyName",vacation.getDutyName());

            Workbook workbook = ExcelExportUtil.exportExcel(params, finalMap);

            workbook.write(response.getOutputStream());

        } catch (Exception e) {
            throw new ServiceException("下载出错");
        }


    }

}
