package cn.iocoder.yudao.module.course.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.course.entity.SchoolCommission;
import cn.iocoder.yudao.module.course.mapper.SchoolCommissionMapper;
import cn.iocoder.yudao.module.course.service.SchoolCommissionService;
import cn.iocoder.yudao.module.course.vo.*;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.exception.ServiceException;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 提成记录 Service 实现类
 *
 * @author 若依
 */
@Service
@Validated
public class SchoolCommissionServiceImpl extends ServiceImpl<SchoolCommissionMapper, SchoolCommission> implements SchoolCommissionService {

    @Resource
    private SchoolCommissionMapper schoolCommissionMapper;

    @Resource
    private AdminUserApi userApi;


    /**
     * 分页查询提成记录
     *
     * @param page      分页参数
     * @param pageReqVO {@link SchoolCommissionVO}
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.course.vo.SchoolCommissionVO>
     * @author PQZ
     * @date 14:00 2025/2/19
     **/
    @Override
    public IPage<SchoolCommissionVO> queryPage(Page<SchoolCommissionVO> page, SchoolCommissionVO pageReqVO) {
        return schoolCommissionMapper.queryPage(pageReqVO, page);
    }

    /**
     * 创建提成记录
     */
    @Override
    public boolean createSchoolCommission(SchoolCommissionVO entity) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        String userName = user.getNickname();

        SchoolCommission commission = new SchoolCommission();
        BeanUtils.copyProperties(entity, commission);

        commission.setCheckId(userId);
        commission.setCheckName(userName);
        commission.setCreateTime(LocalDateTime.now());
        commission.setUpdateTime(LocalDateTime.now());

        if (!this.save(commission)) {
            throw new RuntimeException("创建提成记录失败");
        }

        return true;
    }

    @Override
    public boolean exists(SchoolCommission entity) {
        return this.lambdaQuery()
                .eq(SchoolCommission::getCoachUserId, entity.getCoachUserId())
                .eq(SchoolCommission::getStudentId, entity.getStudentId())
                .eq(SchoolCommission::getCourseId, entity.getCourseId())
                .eq(SchoolCommission::getSubject, entity.getSubject())
                .exists();
    }

    /**
     * 根据id获取提成记录详细信息
     */
    @Override
    public SchoolCommissionVO getSchoolCommissionById(String id) {
        return schoolCommissionMapper.getSchoolCommissionById(id);
    }

    /**
     * 出纳审核提成记录
     */
    @Override
    public boolean cashierConfirm(SchoolCommissionVO schoolCommissionVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO sysUser = userApi.getUser(userId);
        schoolCommissionVO.setCashierName(sysUser.getNickname());
        schoolCommissionVO.setCashierUserId(userId);
        return this.updateById(schoolCommissionVO);
    }

    /**
     * 教练提成合计列表
     */
    @Override
    public List<SchoolCommissionVO> getCoachTotalCommission(SchoolCommissionVO schoolCommissionVO) {
        String startTime = "";
        String endTime = "";
        if ("more".equals(schoolCommissionVO.getTimeType())) {
            if (StringUtils.isNotEmpty(schoolCommissionVO.getStartTimeStr())) {
                startTime = schoolCommissionVO.getStartTimeStr() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(schoolCommissionVO.getEndTimeStr())) {
                endTime = schoolCommissionVO.getEndTimeStr() + " 23:59:59";
            }
        } else if ("month".equals(schoolCommissionVO.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(schoolCommissionVO.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        schoolCommissionVO.setStartTimeStr(startTime);
        schoolCommissionVO.setEndTimeStr(endTime);
        return schoolCommissionMapper.getCoachTotalCommission(schoolCommissionVO);
    }

    /**
     * 教练提成列表
     */
    @Override
    public IPage<SchoolCommissionVO> getCommissionListByCoachId(SchoolCommissionVO schoolCommissionVO, Page<SchoolCommissionVO> page) {
        String startTime = "";
        String endTime = "";
        if ("more".equals(schoolCommissionVO.getTimeType())) {
            if (StringUtils.isNotEmpty(schoolCommissionVO.getStartTimeStr())) {
                startTime = schoolCommissionVO.getStartTimeStr() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(schoolCommissionVO.getEndTimeStr())) {
                endTime = schoolCommissionVO.getEndTimeStr() + " 23:59:59";
            }
        } else if ("month".equals(schoolCommissionVO.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(schoolCommissionVO.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        schoolCommissionVO.setStartTimeStr(startTime);
        schoolCommissionVO.setEndTimeStr(endTime);
        return schoolCommissionMapper.getCommissionListByCoachId(schoolCommissionVO, page);
    }

    /**
     * 需要导出的数据
     * @param exportVO
     * @param page
     * @return
     */
    @Override
    public IPage<CommissionExportVO> getAllCommissionPage(CommissionExportVO exportVO, Page<CommissionExportVO> page) {
        return schoolCommissionMapper.getCommissionListExport(exportVO, page);
    }

    @Override
    public CommissionStatisticsVO getCommissionStatistics(CommissionExportVO exportVO) {
        return schoolCommissionMapper.getCommissionStatistics(exportVO);
    }


    /**
     * 导出的三种形式
     * @param exportVO
     * @return
     */
    @Override
    public List<CommissionExportVO> getCommissionList(CommissionExportVO exportVO) {
        // 分页查询当前页
        Page<CommissionExportVO> page = new Page<>(exportVO.getPageNo(), exportVO.getPageSize());
        IPage<CommissionExportVO> result = schoolCommissionMapper.getCommissionListExport(exportVO, page);
        return result.getRecords();
    }

    @Override
    public List<CommissionExportVO> getAllCommissionList(CommissionExportVO exportVO) {
        // 不分页查询全部数据
        Page<CommissionExportVO> page = new Page<>(1, Integer.MAX_VALUE);
        IPage<CommissionExportVO> result = schoolCommissionMapper.getCommissionListExport(exportVO, page);
        return result.getRecords();
    }

    @Override
    public List<CommissionExportVO> getCommissionListByRange(CommissionExportVO exportVO) {
        List<CommissionExportVO> allData = new ArrayList<>();

        // 循环查询指定范围内的数据
        for (int i = exportVO.getStartPage(); i <= exportVO.getEndPage(); i++) {
            Page<CommissionExportVO> page = new Page<>(i, exportVO.getPageSize());
            IPage<CommissionExportVO> result = schoolCommissionMapper.getCommissionListExport(exportVO, page);
            allData.addAll(result.getRecords());

            if (i >= result.getPages()) {
                break;
            }
        }
        return allData;
    }



    /**
     * 首页财务应付部分
     */
    @Override
    public List<FinanceDeductInfoVO> getFinanceDeductList(FinanceDeductInfoVO entity) {

        String startTime = "";
        String endTime = "";
        if ("more".equals(entity.getTimeType())) {
            if (StringUtils.isNotEmpty(entity.getStartTime())) {
                startTime = entity.getStartTime() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(entity.getEndTime())) {
                endTime = entity.getEndTime() + " 23:59:59";
            }
        } else if ("month".equals(entity.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(entity.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        entity.setStartTime(startTime);
        entity.setEndTime(endTime);
        return schoolCommissionMapper.getFinanceDeductList(entity);
    }

    @Override
    public IPage<FinanceDeductInfoVO> getFinanceDeductDetailsListByCoach(FinanceDeductInfoVO entity, Page<FinanceDeductInfoVO> page) {

        String startTime = "";
        String endTime = "";
        if ("more".equals(entity.getTimeType())) {
            if (StringUtils.isNotEmpty(entity.getStartTime())) {
                startTime = entity.getStartTime() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(entity.getEndTime())) {
                endTime = entity.getEndTime() + " 23:59:59";
            }
        } else if ("month".equals(entity.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(entity.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        entity.setStartTime(startTime);
        entity.setEndTime(endTime);
        return schoolCommissionMapper.getFinanceDeductDetailsListByCoach(entity, page);
    }
}
