package com.xjrsoft.module.teacher.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.UserDeptRelation;
import com.xjrsoft.module.teacher.dto.*;
import com.xjrsoft.module.teacher.entity.AttendanceRecord;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.teacher.service.IAttendanceRecordService;
import com.xjrsoft.module.teacher.vo.AttendanceRecordPageVo;
import com.xjrsoft.module.teacher.vo.AttendanceRecordVo;
import com.xjrsoft.module.teacher.vo.PresentUserCheckInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
* @title: 考勤-记录
* @Author szs
* @Date: 2023-12-18
* @Version 1.0
*/
@RestController
@RequestMapping("/teacher" + "/attendanceRecord")
@Api(value = "/teacher"  + "/attendanceRecord",tags = "考勤-记录代码")
@AllArgsConstructor
public class AttendanceRecordController {


    private final IAttendanceRecordService attendanceRecordService;

    @GetMapping(value = "/page")
    @ApiOperation(value="考勤-记录列表(分页)")
    @SaCheckPermission("attendancerecord:detail")
    public RT<PageOutput<AttendanceRecordPageVo>> page(@Valid AttendanceRecordPageDto dto){

        MPJLambdaWrapper<AttendanceRecord> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper
                .disableSubLogicDel()
                .select(AttendanceRecord::getId)
                .selectAs(XjrUser::getName, AttendanceRecordPageVo::getUserName)
                .selectAs(XjrUser::getUserName, AttendanceRecordPageVo::getOA)
                .selectAs(Department::getName, AttendanceRecordPageVo::getDeptName)
                .select(AttendanceRecord.class, x -> VoToColumnUtil.fieldsToColumns(AttendanceRecordPageVo.class).contains(x.getProperty()))
                .leftJoin(XjrUser.class, XjrUser::getId, AttendanceRecord::getUserId)
                .leftJoin(UserDeptRelation.class, UserDeptRelation::getUserId,AttendanceRecord::getUserId)
                .leftJoin(Department.class, Department::getId,UserDeptRelation::getDeptId)
                .like(ObjectUtil.isNotNull(dto.getUserName()) && !(dto.getUserName().equals("")),XjrUser::getName,dto.getUserName())
                .between(ObjectUtil.isNotNull(dto.getCheckTimeStart()) && ObjectUtil.isNotNull(dto.getCheckTimeEnd()) && !dto.getCheckTimeStart().equals("") && !dto.getCheckTimeEnd().equals(""),
                        AttendanceRecord::getCheckTime,dto.getCheckTimeStart(),dto.getCheckTimeEnd())
                .orderByDesc(AttendanceRecord::getId);
        IPage<AttendanceRecordPageVo> page = attendanceRecordService.selectJoinListPage(ConventPage.getPage(dto),AttendanceRecordPageVo.class, queryWrapper);
        PageOutput<AttendanceRecordPageVo> pageOutput = ConventPage.getPageOutput(page, AttendanceRecordPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/getCheckInDay")
    @ApiOperation(value="获取当月打卡的天")
    @SaCheckPermission("attendancerecord:detail")
    public RT<List<String>> getCheckInDay(@Valid GetCheckInDayDto dto){
        List<String> dayList = attendanceRecordService.getCheckInDay(dto);
        return RT.ok(dayList);
    }

    @GetMapping(value = "/getPresentUserCheckInfo")
    @ApiOperation(value="获取当前用户当天上班打卡数据")
    @SaCheckPermission("attendancerecord:detail")
    public RT<PresentUserCheckInfoVo> getPresentUserCheckInfo(){
        PresentUserCheckInfoVo presentUserCheckInfo = attendanceRecordService.getPresentUserCheckInfo();
        return RT.ok(presentUserCheckInfo);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询考勤-记录信息")
    @SaCheckPermission("attendancerecord:detail")
    public RT<AttendanceRecordVo> info(@RequestParam Long id){
        AttendanceRecord attendanceRecord = attendanceRecordService.getById(id);
        if (attendanceRecord == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(BeanUtil.toBean(attendanceRecord, AttendanceRecordVo.class));
    }

    @PostMapping
    @ApiOperation(value = "新增考勤-记录")
    @SaCheckPermission("attendancerecord:add")
    public RT<Boolean> add(@Valid @RequestBody AddAttendanceRecordDto dto){
        AttendanceRecord attendanceRecord = BeanUtil.toBean(dto, AttendanceRecord.class);
        boolean isSuccess = attendanceRecordService.save(attendanceRecord);
        return RT.ok(isSuccess);
    }

    @PostMapping(value = "/clock-in")
    @ApiOperation(value = "新增考勤-记录(打卡)")
    @SaCheckPermission("attendancerecord:add")
    public RT<Boolean> clockIn(@Valid @RequestBody ClockInDto dto){
        AttendanceRecord AttendanceRecord = BeanUtil.toBean(dto, AttendanceRecord.class);
        boolean isSuccess = attendanceRecordService.addAttendanceRecordOfClockIn(AttendanceRecord);
        return  RT.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改考勤-记录")
    @SaCheckPermission("attendancerecord:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateAttendanceRecordDto dto){

        AttendanceRecord attendanceRecord = BeanUtil.toBean(dto, AttendanceRecord.class);
        return RT.ok(attendanceRecordService.updateById(attendanceRecord));

    }

    @DeleteMapping
    @ApiOperation(value = "删除考勤-记录")
    @SaCheckPermission("attendancerecord:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        return RT.ok(attendanceRecordService.removeBatchByIds(ids));

    }

    @GetMapping("/export")
    @ApiOperation(value = "导出")
    public ResponseEntity<byte[]> exportData(@Valid AttendanceRecordPageDto dto, @RequestParam(defaultValue = "false") Boolean isTemplate) {
        List<AttendanceRecordPageVo> customerList = isTemplate != null && isTemplate ? new ArrayList<>() : ((PageOutput<AttendanceRecordPageVo>) page(dto).getData()).getList();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, AttendanceRecordPageVo.class).automaticMergeHead(false).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(customerList);

        return RT.fileStream(bot.toByteArray(), "AttendanceRecord" + ExcelTypeEnum.XLSX.getValue());
    }
}