package com.propertyManagement.web.controller.business;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.propertyManagement.business.domain.WxClock;
import com.propertyManagement.business.domain.bo.WxClockBo;
import com.propertyManagement.business.domain.vo.WxClockVo;
import com.propertyManagement.business.domain.vo.WxClockVo2;
import com.propertyManagement.business.mapper.WxClockMapper;
import com.propertyManagement.business.service.IWxClockService;
import com.propertyManagement.business.support.util.AuthUtil;
import com.propertyManagement.common.annotation.Log;
import com.propertyManagement.common.annotation.RepeatSubmit;
import com.propertyManagement.common.core.controller.BaseController;
import com.propertyManagement.common.core.domain.PageQuery;
import com.propertyManagement.common.core.domain.R;
import com.propertyManagement.common.core.page.TableDataInfo;
import com.propertyManagement.common.core.validate.AddGroup;
import com.propertyManagement.common.core.validate.EditGroup;
import com.propertyManagement.common.enums.BusinessType;
import com.propertyManagement.common.utils.poi.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 打卡
 *
 * @author liushuai
 * @date 2025-05-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/clock")
public class WxClockController extends BaseController {

    private final IWxClockService iWxClockService;

    private final WxClockMapper wxClockMapper;

    /**
     * 查询打卡列表
     */
    @SaCheckPermission("business:clock:list")
    @GetMapping("/list")
    public TableDataInfo<WxClockVo> list(WxClockBo bo, PageQuery pageQuery) {
        return iWxClockService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询打卡列表
     */
    @GetMapping("/info")
    public R<WxClockVo2> info(@NotNull Long accountId ,@NotNull(message = "日期不能为空") String date) {
        WxClockVo2 wxClockVo2 = new WxClockVo2();
        // 解析传入的日期参数
        DateTime inputDate = DateUtil.parse(date, "yyyy-MM");
        // 获取本月第一天和最后一天
        DateTime beginOfMonth = DateUtil.beginOfMonth(inputDate);
        DateTime endOfMonth = DateUtil.endOfMonth(inputDate);
        // 生成本月所有日期列表
        List<DateTime> dateTimes = DateUtil.rangeToList(beginOfMonth, endOfMonth, DateField.DAY_OF_MONTH);
        // 并行处理提高效率
        List<WxClockVo2.ClockRecord> clockRecordList = dateTimes.parallelStream()
            .map(item -> {
                String dateStr = DateUtil.format(item, "yyyy-MM-dd");
                int count = Math.toIntExact(wxClockMapper.selectCount(Wrappers.<WxClock>lambdaQuery()
                    .apply("DATE(clock_time) = {0}", dateStr)
                    .eq(WxClock::getAccountId, accountId)));
                return new WxClockVo2.ClockRecord(dateStr, count > 0 ? 1 : 0);
            })
            .collect(Collectors.toList());
        // 计算打卡和缺卡天数
        long clockDays = clockRecordList.stream().filter(r -> r.getClockState() == 1).count();
        wxClockVo2.setClockDay((int) clockDays);
        wxClockVo2.setNoRecordDay(clockRecordList.size() - (int) clockDays);
        wxClockVo2.setClockRecordList(clockRecordList);
        return R.ok(wxClockVo2);
    }

    /**
     * 导出打卡列表
     */
    @SaCheckPermission("business:clock:export")
    @Log(title = "打卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(WxClockBo bo, HttpServletResponse response) {
        List<WxClockVo> list = iWxClockService.queryList(bo);
        ExcelUtil.exportExcel(list, "打卡", WxClockVo.class, response);
    }

    /**
     * 获取打卡详细信息
     *
     * @param clockId 主键
     */
    @SaCheckPermission("business:clock:query")
    @GetMapping("/{clockId}")
    public R<WxClockVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long clockId) {
        return R.ok(iWxClockService.queryById(clockId));
    }

    /**
     * 新增打卡
     */
    @SaCheckPermission("business:clock:add")
    @Log(title = "打卡", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody WxClockBo bo) {
        return toAjax(iWxClockService.insertByBo(bo));
    }

    /**
     * 修改打卡
     */
    @SaCheckPermission("business:clock:edit")
    @Log(title = "打卡", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody WxClockBo bo) {
        return toAjax(iWxClockService.updateByBo(bo));
    }

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