package top.continew.admin.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.continew.admin.business.mapper.SignInMapper;
import top.continew.admin.business.model.entity.SignInDO;
import top.continew.admin.business.model.query.SignInQuery;
import top.continew.admin.business.model.req.SignInAddReq;
import top.continew.admin.business.model.req.SignInEditReq;
import top.continew.admin.business.model.resp.SignInExportResp;
import top.continew.admin.business.model.resp.SignInResp;
import top.continew.admin.business.model.resp.TodayNosignInExportResp;
import top.continew.admin.business.service.SignInService;
import top.continew.starter.data.mp.service.impl.ServiceImpl;
import top.continew.starter.data.mp.util.QueryWrapperHelper;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.query.SortQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.file.excel.util.ExcelUtils;

import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * business业务实现
 *
 * @author jiay
 * @since 2025/06/26 10:24
 */
@Service
@RequiredArgsConstructor
public class SignInServiceImpl extends ServiceImpl<SignInMapper, SignInDO> implements SignInService {

    private final SignInMapper signInMapper;

    @Override
    public List<SignInResp> getSignInList(SignInQuery query) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        List list = this.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(list)) {
            return BeanUtil.copyToList(list, SignInResp.class);
        }
        return Collections.emptyList();
    }

    @Override
    public boolean addSignIn(SignInAddReq req) {
        //插入记录到数据库
        SignInDO entity = BeanUtil.copyProperties(req, SignInDO.class);
        return signInMapper.insert(entity) > 0;

    }

    @Override
    public boolean editSignIn(SignInEditReq req) {
        SignInDO signInDO = BeanUtil.copyProperties(req, SignInDO.class);
        return signInMapper.updateById(signInDO) > 0;

    }

    @Override
    public boolean deleteSignIn(Long id) {
        if (id != null) {
            return signInMapper.deleteById(id) > 0;
        }
        return false;
    }

    @Override
    public SignInResp getSignIn(Long id) {
        SignInDO signInDO = signInMapper.selectById(id);
        SignInResp signInResp = new SignInResp();
        if (signInDO != null) {
            signInResp = BeanUtil.copyProperties(signInDO, SignInResp.class);
        }
        return signInResp;
    }

    @Override
    public PageResp<SignInResp> getSignInPage(SignInQuery query, PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        Page page = signInMapper.selectPage(new Page<>(pageQuery.getPage(), pageQuery.getSize()), queryWrapper);
        return PageResp.build(page);
    }

    @Override
    public List<SignInResp> getTodayNosignInList(SignInQuery query) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        List list = this.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(list)) {
            List<SignInResp> signInResps = BeanUtil.copyToList(list, SignInResp.class);
            signInResps.stream().forEach(e -> {
                //todo
                Random random = new Random(100);
                e.setPresent(random.nextInt(10));
                e.setAbnormal(random.nextInt(10));
                e.setAbsent(random.nextInt(10));
                e.setLeaveCount(random.nextInt(10));
                e.setLeaveCause("生病假！");
            });
            return signInResps;
        }
        return Collections.emptyList();
    }

    @Override
    public PageResp<SignInResp> getHisSignInList(SignInQuery query, PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        Page page = signInMapper.selectPage(new Page<>(pageQuery.getPage(), pageQuery.getSize()), queryWrapper);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<SignInResp> signInResps = BeanUtil.copyToList(page.getRecords(), SignInResp.class);
            signInResps.forEach(e -> {
                //todo
                Random random = new Random(100);
                e.setPresent(random.nextInt(10));
                e.setAbnormal(random.nextInt(10));
                e.setAbsent(random.nextInt(10));
                e.setLeaveCount(random.nextInt(10));
                e.setLeaveCause("生病假");
            });
            page.setRecords(signInResps);
        }
        return PageResp.build(page);
    }

    @Override
    public void exportHisSignInList(SignInQuery query, SortQuery sortQuery, HttpServletResponse response) {
        List<SignInResp> list = getTodayNosignInList(query);
        List<SignInExportResp> res = BeanUtil.copyToList(list, SignInExportResp.class);
        res.forEach(e -> {

        });
        ExcelUtils.export(res, "导出历史签到列表", SignInExportResp.class, response);
    }

    @Override
    public void exportTodayNosignInList(SignInQuery query, SortQuery sortQuery, HttpServletResponse response) {
        PageResp<SignInResp> list = getHisSignInList(query, null);
        List<TodayNosignInExportResp> res = BeanUtil.copyToList(list.getList(), TodayNosignInExportResp.class);
        res.forEach(e -> {

        });
        ExcelUtils.export(res, "导出今日未签到列表", TodayNosignInExportResp.class, response);
    }

    /**
     * 设置排序
     *
     * @param queryWrapper 查询条件封装对象
     * @param sortQuery    排序查询条件
     */
    private void sort(QueryWrapper<SignInDO> queryWrapper, SortQuery sortQuery) {
        if (sortQuery == null || sortQuery.getSort().isUnsorted()) {
            return;
        }
        for (Sort.Order order : sortQuery.getSort()) {
            String property = order.getProperty();
            queryWrapper.orderBy(true, order.isAscending(), CharSequenceUtil.toUnderlineCase(property));
        }
    }

    /**
     * 构建 QueryWrapper
     *
     * @param query 查询条件
     * @return QueryWrapper
     */
    private QueryWrapper<SignInDO> buildQueryWrapper(SignInQuery query) {
        String courseName = query.getCourseName();
        String userName = query.getUserName();
        return new QueryWrapper<SignInDO>().and(StrUtil.isNotBlank(courseName), q -> q
            .like("t1.course_name", courseName))
            .and(StrUtil.isNotBlank(userName), q -> q.like("t1.user_name", userName));
    }
}