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

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.jx.payment.entity.DriveSchoolPay;
import cn.iocoder.yudao.module.jx.payment.mapper.DriveSchoolPayMapper;
import cn.iocoder.yudao.module.jx.payment.service.DriveSchoolPayService;
import cn.iocoder.yudao.module.jx.payment.utils.PhoneValidator;
import cn.iocoder.yudao.module.jx.payment.utils.SendSmsUtil;
import cn.iocoder.yudao.module.jx.payment.vo.PayVo;
import cn.iocoder.yudao.module.jx.utils.DateUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCoach;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCourse;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolExamPass;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolCoachMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolCourseMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolExamPassMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolInfoMapper;
import cn.iocoder.yudao.module.jx.service.IDriveSchoolExamPassService;
import cn.iocoder.yudao.module.jx.vo.DriveSchoolInfoVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thoughtworks.xstream.core.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;

/**
 * 考试通过Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-07
 */
@Service
public class DriveSchoolExamPassServiceImpl implements IDriveSchoolExamPassService {
    @Autowired
    @Lazy
    private DriveSchoolExamPassMapper driveSchoolExamPassMapper;

    @Autowired
    @Lazy
    private DriveSchoolPayMapper driveSchoolPayMapper;

    @Autowired
    @Lazy
    private DriveSchoolCourseMapper driveSchoolCourseMapper;

    @Autowired
    @Lazy
    private DriveSchoolCoachMapper driveSchoolCoachMapper;

    @Resource
    private AdminUserApi userApi;

    /**
     * 查询考试通过
     *
     * @param id 考试通过主键
     * @return 考试通过
     */
    @Override
    public DriveSchoolExamPass selectDriveSchoolExamPassById(Long id) {
        return driveSchoolExamPassMapper.selectDriveSchoolExamPassById(id);
    }

    @Resource
    private DriveSchoolInfoMapper driveSchoolInfoMapper;

    /**
     * 查询考试通过列表
     *
     * @param driveSchoolExamPass 考试通过
     * @return 考试通过
     */
    @Override
    public IPage<DriveSchoolExamPass> selectDriveSchoolExamPassList(DriveSchoolExamPass driveSchoolExamPass, Page<DriveSchoolExamPass> page) {
        if (driveSchoolExamPass == null) {
            throw new IllegalArgumentException("driveSchoolExamPass cannot be null");
        }

        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        Long deptId = user.getDeptId();

        // 空值检查
        if (deptId == null || deptId <= 0) {
            throw new IllegalArgumentException("无效的部门 ID");
        }

        // 获取驾校信息
        DriveSchoolInfoVO schoolInfoByDeptId = driveSchoolInfoMapper.getSchoolInfoByDeptId(deptId);
        if (schoolInfoByDeptId == null) {
            throw new RuntimeException("未找到指定部门的驾校信息");
        }

        driveSchoolExamPass.setJxId(schoolInfoByDeptId.getId());
        return driveSchoolExamPassMapper.selectDriveSchoolExamPassList(driveSchoolExamPass, page);
    }


    @Autowired
    private DriveSchoolPayService driveSchoolPayService;

    /**
     * 新增考试通过
     *
     * @param driveSchoolExamPass 考试通过
     * @return 结果
     */
    @Override
    public int insertDriveSchoolExamPass(DriveSchoolExamPass driveSchoolExamPass) {
        DriveSchoolPay driveSchoolPay1 = new DriveSchoolPay();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        DriveSchoolPay driveSchoolPay2 = driveSchoolPayService.selectByUserId(userId);

        driveSchoolPay1.setJlName(driveSchoolPay2.getJlName());
        driveSchoolPay1.setPhone(driveSchoolPay2.getPhone());
        driveSchoolPay1.setName(driveSchoolPay2.getName());

        //提成金额
        PayVo payVo = driveSchoolPayService.getDeductByUserInfo(driveSchoolPay1);
        BigDecimal bd = BigDecimal.valueOf(payVo.getDeduct());
        driveSchoolExamPass.setDeduct(bd);

        driveSchoolExamPass.setName(driveSchoolPay2.getName());
        driveSchoolExamPass.setJlName(driveSchoolPay2.getJlName());
        driveSchoolExamPass.setJlId(driveSchoolPay2.getJlId());
        driveSchoolExamPass.setJxId(driveSchoolPay2.getJxId());
        driveSchoolExamPass.setPhone(driveSchoolPay2.getPhone());

        driveSchoolPay1.setUserId(userId);
        DriveSchoolPay deductByUserInfo = driveSchoolPayMapper.getDeductByUserInfo(driveSchoolPay1);
        if (ObjectUtils.isNotEmpty(deductByUserInfo)) {
            driveSchoolExamPass.setOrderNumber(deductByUserInfo.getOrderNumber());
            DriveSchoolCourse driveSchoolCourse = driveSchoolCourseMapper.selectDriveSchoolCourseById(deductByUserInfo.getCourseId());
            driveSchoolExamPass.setCoursePrice(driveSchoolCourse.getPrice());
            driveSchoolExamPass.setCourseId(deductByUserInfo.getCourseId());
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDate = sdf.format(date);

        //发送短信
        if (PhoneValidator.isValid(driveSchoolPay2.getPhone())) {
            SendSmsUtil.sendMsgCommon(new String[]{driveSchoolPay2.getName() + "同学，恭喜通过科目" + driveSchoolExamPass.getCourseSubject() + "的考试，继续加油！",}, driveSchoolPay2.getPhone(), "1400852709", "蓝安汽车小程序", "2143603");
        }
        return driveSchoolExamPassMapper.insertDriveSchoolExamPass(driveSchoolExamPass);
    }

    /**
     * 修改考试通过
     *
     * @param driveSchoolExamPass 考试通过
     * @return 结果
     */
    @Override
    public int updateDriveSchoolExamPass(DriveSchoolExamPass driveSchoolExamPass) {
        //driveSchoolExamPass.setUpdateTime(DateUtils.getNowDate());
        return driveSchoolExamPassMapper.updateDriveSchoolExamPass(driveSchoolExamPass);
    }

    /**
     * 批量删除考试通过
     *
     * @param ids 需要删除的考试通过主键
     * @return 结果
     */
    @Override
    public int deleteDriveSchoolExamPassByIds(Long[] ids) {
        return driveSchoolExamPassMapper.deleteDriveSchoolExamPassByIds(ids);
    }

    /**
     * 删除考试通过信息
     *
     * @param id 考试通过主键
     * @return 结果
     */
    @Override
    public int deleteDriveSchoolExamPassById(Long id) {
        return driveSchoolExamPassMapper.deleteDriveSchoolExamPassById(id);
    }


    @Override
    public IPage<DriveSchoolExamPass> checkList(DriveSchoolExamPass driveSchoolExamPass, Page<DriveSchoolExamPass> page) {

        IPage<DriveSchoolExamPass> driveSchoolExamPassIPage = driveSchoolExamPassMapper.checkList(driveSchoolExamPass.getJlId(), page);
        List<DriveSchoolExamPass> driveSchoolExamPasses = driveSchoolExamPassIPage.getRecords();
        for (DriveSchoolExamPass schoolExamPass : driveSchoolExamPasses) {
            DriveSchoolCourse driveSchoolCourse = driveSchoolCourseMapper.selectDriveSchoolCourseById(schoolExamPass.getCourseId());
            if (ObjectUtils.isNotEmpty(driveSchoolCourse)) {
                schoolExamPass.setCourseName(driveSchoolCourse.getName());
            }
        }
        return driveSchoolExamPassIPage;
    }

    /**
     * 查询教练工资
     *
     * @param driveSchoolExamPass
     * @return
     */
    @Override
    public IPage<DriveSchoolExamPass> getBalanceList(DriveSchoolExamPass driveSchoolExamPass, Page<DriveSchoolExamPass> page) {
        // 检查 JX ID
        if (ObjectUtils.isNotEmpty(driveSchoolExamPass.getJxId())) {
            driveSchoolExamPass.setJxId(driveSchoolExamPass.getId());
        } else {
            Long userId = SecurityFrameworkUtils.getLoginUserId();
            AdminUserRespDTO user = userApi.getUser(userId);
            Long deptId = user.getDeptId();

            // 获取驾校信息
            DriveSchoolInfoVO schoolInfoByDeptId = driveSchoolInfoMapper.getSchoolInfoByDeptId(deptId);

            // 检查 schoolInfoByDeptId 是否为 null
            if (schoolInfoByDeptId == null) {
                throw new RuntimeException("未找到指定部门的驾校信息"); // 抛出合理的异常
            }

            driveSchoolExamPass.setJxId(schoolInfoByDeptId.getId());
        }

        // 进一步的逻辑处理
        // 否则进行时间格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (ObjectUtils.isNotEmpty(driveSchoolExamPass.getPayStartTime()) &&
                ObjectUtils.isNotEmpty(driveSchoolExamPass.getPayEndTime())) {
            driveSchoolExamPass.setPayStartTimes(simpleDateFormat.format(driveSchoolExamPass.getPayStartTime()));
            driveSchoolExamPass.setPayEndTimes(simpleDateFormat.format(driveSchoolExamPass.getPayEndTime()));
        }

        IPage<DriveSchoolExamPass> records = driveSchoolExamPassMapper.getBalanceList(driveSchoolExamPass, page);

        // 处理余额逻辑
        List<DriveSchoolExamPass> balanceList = records.getRecords();
        balanceList.forEach(s -> {
            DriveSchoolExamPass driveSchoolExamPass1 = new DriveSchoolExamPass();
            DriveSchoolExamPass balance = driveSchoolExamPassMapper.getBalance(driveSchoolExamPass1);
            if (ObjectUtils.isNotEmpty(balance)) {
                s.setDeducts(balance.getDeduct());
            } else {
                s.setDeducts(new BigDecimal(0));
            }
        });

        return records;
    }


    @Override
    public int pay(DriveSchoolExamPass driveSchoolExamPass) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        Long deptId = user.getDeptId();
        DriveSchoolInfoVO schoolInfoByDeptId = driveSchoolInfoMapper.getSchoolInfoByDeptId(deptId);
        driveSchoolExamPass.setJxId(schoolInfoByDeptId.getId());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (ObjectUtils.isNotEmpty(driveSchoolExamPass.getPayStartTime()) && ObjectUtils.isNotEmpty(driveSchoolExamPass.getPayEndTime())) {
            driveSchoolExamPass.setPayStartTimes(simpleDateFormat.format(driveSchoolExamPass.getPayStartTime()));
            driveSchoolExamPass.setPayEndTimes(simpleDateFormat.format(driveSchoolExamPass.getPayEndTime()));
        }

        int pay = driveSchoolExamPassMapper.pay(driveSchoolExamPass);
        return pay;
    }

    @Override
    public DriveSchoolExamPass getTime(DriveSchoolExamPass driveSchoolExamPass) {
        LocalDate now = LocalDate.now();
        // 当月第一天
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        // 当月最后一天
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());

        Instant instant1 = Timestamp.valueOf(firstDayOfMonth.atTime(LocalTime.MIDNIGHT)).toInstant();
        Date startTime = Date.from(instant1);

        Instant instant2 = Timestamp.valueOf(lastDayOfMonth.atTime(LocalTime.MIDNIGHT)).toInstant();
        Date endTime = Date.from(instant2);

        driveSchoolExamPass.setPayStartTime(startTime);
        driveSchoolExamPass.setPayEndTime(endTime);
        return driveSchoolExamPass;
    }

    @Override
    public DriveSchoolExamPass getBalanceApp(DriveSchoolExamPass driveSchoolExamPass) {
        if (ObjectUtils.isNotEmpty(driveSchoolExamPass.getJxId())) {
            driveSchoolExamPass.setJxId(driveSchoolExamPass.getId());
        } else {
            Long userId = SecurityFrameworkUtils.getLoginUserId();
            AdminUserRespDTO user = userApi.getUser(userId);
            Long deptId = user.getDeptId();
            DriveSchoolInfoVO schoolInfoByDeptId = driveSchoolInfoMapper.getSchoolInfoByDeptId(deptId);
            driveSchoolExamPass.setJxId(schoolInfoByDeptId.getId());
        }

        DriveSchoolExamPass driveSchoolExamPass1 = driveSchoolExamPassMapper.getBalanceApp(driveSchoolExamPass);

        DriveSchoolExamPass balance = driveSchoolExamPassMapper.getBalance(driveSchoolExamPass);
        if (ObjectUtils.isNotEmpty(balance)) {
            driveSchoolExamPass1.setDeducts(balance.getDeduct());
        } else {
            driveSchoolExamPass1.setDeducts(new BigDecimal(0));
        }
        return driveSchoolExamPass1;
    }


//    @Resource
//    private  ISysUserService iSysUserService;

    /**
     * 查询教练工资
     *
     * @param driveSchoolExamPass
     * @return
     */
    @Override
    public DriveSchoolExamPass getBalanceByCoachId(DriveSchoolExamPass driveSchoolExamPass) {

        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO sysUser = userApi.getUser(userId);
        //SysUser sysUser = iSysUserService.selectUserById(userId);

        DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectByPhonenumber(sysUser.getMobile());
        driveSchoolExamPass.setJlId(driveSchoolCoach.getId());
      /*  if (ObjectUtils.isNotEmpty(driveSchoolExamPass.getJxId())){
            driveSchoolExamPass.setJxId(driveSchoolExamPass.getId());
        }*/
/*        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (ObjectUtils.isNotEmpty(driveSchoolExamPass.getPayStartTime()) && ObjectUtils.isNotEmpty(driveSchoolExamPass.getPayEndTime())){
            driveSchoolExamPass.setPayStartTimes(simpleDateFormat.format(driveSchoolExamPass.getPayStartTime()));
            driveSchoolExamPass.setPayEndTimes(simpleDateFormat.format(driveSchoolExamPass.getPayEndTime()));
        }*/

        DriveSchoolExamPass balanceByCoachId = driveSchoolExamPassMapper.getBalanceByCoachId(driveSchoolExamPass);

        DriveSchoolExamPass driveSchoolExamPass1 = new DriveSchoolExamPass();
        DriveSchoolExamPass balance = driveSchoolExamPassMapper.getBalanceByCaochId(driveSchoolExamPass1);

        if (ObjectUtils.isNotEmpty(balanceByCoachId) && ObjectUtils.isNotEmpty(balance) && ObjectUtils.isNotEmpty(balance.getDeduct())) {
            balanceByCoachId.setDeducts(balance.getDeduct());
        } else {
            DriveSchoolExamPass driveSchoolExamPass2 = new DriveSchoolExamPass();
            driveSchoolExamPass2.setDeducts(new BigDecimal(0));
            return driveSchoolExamPass2;
        }
        return balanceByCoachId;
    }
}
