package com.ruoyi.pay.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pay.util.AttendanceExcelUtil;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pay.domain.vo.PayAttendanceVo;
import com.ruoyi.pay.domain.bo.PayAttendanceBo;
import com.ruoyi.pay.service.IPayAttendanceService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 考勤
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/pay/attendance")
public class PayAttendanceController extends BaseController {

    private final IPayAttendanceService iPayAttendanceService;

    /**
     * 查询考勤列表
     */
    @SaCheckPermission("pay:attendance:list")
    @GetMapping("/list")
    public TableDataInfo<PayAttendanceVo> list(PayAttendanceBo bo, PageQuery pageQuery) {
        return iPayAttendanceService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出考勤列表
     */
    @SaCheckPermission("pay:attendance:export")
    @Log(title = "考勤", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(PayAttendanceBo bo, HttpServletResponse response) {
        List<PayAttendanceVo> list = iPayAttendanceService.queryList(bo);
        ExcelUtil.exportExcel(list, "考勤", PayAttendanceVo.class, response);
    }
    /**
     * 导入考勤列表
     */
    @SaCheckPermission("pay:attendance:import")
    @Log(title = "考勤", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public  R<Void> importData(MultipartFile file, boolean updateSupport,String date,String kaoqinType,Long tenantId) throws Exception {
        PayAttendanceBo attendance = new PayAttendanceBo();
        attendance.setKaoqinjiNum(kaoqinType);
        attendance.setKaoqinYearMonth(date);
        List<PayAttendanceVo>  occupaAttendance= iPayAttendanceService.queryList(attendance);
        if(occupaAttendance!=null&&occupaAttendance.size()>0){
            if(!updateSupport){ //判断是否为更新
                return R.fail("已有当月考勤信息,如需更新请勾选更新考勤");
            }else{   //选择是更新数据时根据年月和考勤机删除原来记录的当月数据
                List<Long> ids = new ArrayList<>();
                for(PayAttendanceVo attendance1:occupaAttendance){
                    ids.add(attendance1.getId()) ;
                }
                iPayAttendanceService.deleteWithValidByIds(ids,true);
            }
        }

        List<PayAttendanceBo> attendanceList;
        //判断考勤机（综合办与网机用一个模板，围栏一个模板）
        if(!kaoqinType.equals("2")){
            attendanceList = new AttendanceExcelUtil().importKaoQinExcel(StringUtils.EMPTY,file.getInputStream(),3,date,kaoqinType,tenantId);
        }else{
            attendanceList = new AttendanceExcelUtil().importKaoQinExcel2(StringUtils.EMPTY,file.getInputStream(),2,date,kaoqinType,tenantId);
        }
        String message = iPayAttendanceService.importAttendance(attendanceList, updateSupport, date);
        return R.ok(message);
    }

    /**
     * 获取考勤详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("pay:attendance:query")
    @GetMapping("/{id}")
    public R<PayAttendanceVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iPayAttendanceService.queryById(id));
    }

    /**
     * 新增考勤
     */
    @SaCheckPermission("pay:attendance:add")
    @Log(title = "考勤", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody PayAttendanceBo bo) {
        // 验证本人当日的考勤是否存在
        PayAttendanceBo query = new PayAttendanceBo();
        query.setEmpName(bo.getEmpName());
        query.setKaoqinDate(bo.getKaoqinDate());
        List<PayAttendanceVo> attendances=iPayAttendanceService.queryList(query);
        if (attendances==null||attendances.size()==0){
            return toAjax(iPayAttendanceService.insertByBo(bo));
        }
        return R.fail("已存在"+bo.getEmpName()+"的考勤");
    }

    /**
     * 修改考勤
     */
    @SaCheckPermission("pay:attendance:edit")
    @Log(title = "考勤", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PayAttendanceBo bo) {
        return toAjax(iPayAttendanceService.updateByBo(bo));
    }

    /**
     * 删除考勤
     *
     * @param ids 主键串
     */
    @SaCheckPermission("pay:attendance:remove")
    @Log(title = "考勤", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iPayAttendanceService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
