package org.jeecg.modules.system.app.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.app.entity.*;
import org.jeecg.modules.system.app.form.CoursesVerificationRecordForm;
import org.jeecg.modules.system.app.form.VerifyForm;
import org.jeecg.modules.system.app.mapper.*;
import org.jeecg.modules.system.app.service.IAppCoursesVerificationRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Description: nm_courses_verification_record
 * @Author: jeecg-boot
 * @Date: 2025-08-04
 * @Version: V1.0
 */
@Service
@Slf4j
public class AppCoursesVerificationRecordServiceImpl extends ServiceImpl<AppCoursesVerificationRecordMapper, AppCoursesVerificationRecord> implements IAppCoursesVerificationRecordService {

    @Resource
    private FamilyMembersMapper  familyMembersMapper;

    @Resource
    private AppOrderMapper appOrderMapper;

    @Resource
    private AppCoursesPriceRulesMapper appCoursesPriceRulesMapper;

    @Resource
    private AppOrderProInfoMapper appOrderProInfoMapper;
    @Autowired
    private AppCoursesMapper appCoursesMapper;
    @Resource
    private AppSiteMapper appSiteMapper;
    @Resource
    private AppIsinMapper appIsinMapper;

    @Override
    public Boolean courseUploadImage(VerifyForm verifyForm) {

        //获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        AppCoursesPriceRules appCoursesPriceRules = appCoursesPriceRulesMapper.selectById(verifyForm.getCoursePriceRulesId());
        AppCourses appCourses = appCoursesMapper.selectById(appCoursesPriceRules.getCoursesId());
        //如果是教练
        String roleCode = sysUser.getRoleCode();
        if (!roleCode.contains("instructor")) {
            if (!Objects.equals(appCourses.getOrgCode(), sysUser.getOrgCode())) {
                throw new JeecgBootException("当前用户没有权限操作此课程");
            }
        } else {
            if (!appCourses.getUserId().contains(sysUser.getId())) {
                throw new JeecgBootException("当前用户没有权限操作此课程");
            }
        }

        AppSite appSite = appSiteMapper.selectOne(Wrappers.lambdaQuery(AppSite.class).eq(AppSite::getId, appCourses.getAddressSiteId()));
        if(ObjectUtil.isNotEmpty(appSite)){
            if (Objects.equals(appSite.getType(), CommonConstant.STATUS_0_INT)){
                for (CoursesVerificationRecordForm coursesVerificationRecordForm : verifyForm.getFormList()) {
                    List<AppIsin> appIsins = appIsinMapper.selectList(Wrappers.<AppIsin>lambdaQuery()
                            .eq(AppIsin::getCoursePriceRuleId, verifyForm.getCoursePriceRulesId())
                            .eq(AppIsin::getFamilyId, coursesVerificationRecordForm.getId())
                            .eq(AppIsin::getIsinStatus, CommonConstant.STATUS_NORMAL)
                    );
                    if (CollUtil.isNotEmpty(appIsins)) {
                        appIsins.forEach(appIsin -> {
                            appIsin.setIsinStatus(CommonConstant.STATUS_1_INT);
                            appIsin.setUseAddress(appSite.getAddress());
                            appIsin.setUseTime(DateUtils.getDate());
                            appIsin.setUseImage(coursesVerificationRecordForm.getVerifyImage());
                            appIsin.setVerifyUserId(sysUser.getId());
                            appIsin.setVerifyUserName(sysUser.getRealname());
                            appIsinMapper.updateById(appIsin);
                        });
                    }
                }
            }
        }

        for (CoursesVerificationRecordForm coursesVerificationRecordForm : verifyForm.getFormList()) {
            List<AppCoursesVerificationRecord> verificationRecordList = baseMapper.selectList(Wrappers.<AppCoursesVerificationRecord>lambdaQuery()
                    .eq(AppCoursesVerificationRecord::getCoursesPriceRuleId, verifyForm.getCoursePriceRulesId())
                    .eq(AppCoursesVerificationRecord::getUseUserId, coursesVerificationRecordForm.getId())
                    .eq(AppCoursesVerificationRecord::getVerifyStatus, CommonConstant.STATUS_NORMAL)
            );

            if(CollUtil.isEmpty(verificationRecordList)){
                FamilyMembers familyMembers = familyMembersMapper.selectById(coursesVerificationRecordForm.getId());
                throw new JeecgBootException("当前用户"+familyMembers.getFullName()+"没有应验课程");
            }
            verificationRecordList.forEach(verificationRecord -> {
                verificationRecord.setVerifyStatus(CommonConstant.STATUS_1_INT);
                verificationRecord.setVerifyUserId(sysUser.getId());
                verificationRecord.setVerifyUserName(sysUser.getRealname());
                verificationRecord.setVerifyTime(DateUtils.getDate());
                verificationRecord.setVerifyImage(coursesVerificationRecordForm.getVerifyImage());
                baseMapper.updateById(verificationRecord);
                //修改订单状态
                String useUserId = verificationRecord.getUseUserId();
                String coursesId = verificationRecord.getCoursesId();
                List<AppOrderProInfo> orderProInfoList =
                        appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery()
                                .eq(AppOrderProInfo::getFamilyUserId, useUserId)
                                .eq(AppOrderProInfo::getProductId, coursesId));
                if (ObjectUtil.isNotEmpty(orderProInfoList)) {
                    for (AppOrderProInfo orderProInfo : orderProInfoList) {
                        orderProInfo.setOrderStatus(CommonConstant.ORDER_STATUS_2);
                        appOrderProInfoMapper.updateById(orderProInfo);
                        String orderId = orderProInfo.getOrderId();
                        AppOrder appOrder = appOrderMapper.selectById(orderId);
                        if (ObjectUtil.isNotEmpty(appOrder)) {
                            if (Objects.equals(appOrder.getOrderOrFree(), CommonConstant.STATUS_1_INT)) {
                                appOrder.setOrderStatus(CommonConstant.ORDER_STATUS_2);
                                appOrderMapper.updateById(appOrder);
                            }
                            List<AppOrderProInfo> proInfoList = appOrderProInfoMapper.selectList(Wrappers.<AppOrderProInfo>lambdaQuery().eq(AppOrderProInfo::getOrderId, orderId)
                                    .eq(AppOrderProInfo::getOrderStatus, CommonConstant.ORDER_STATUS_1)
                                    .eq(AppOrderProInfo::getType, CommonConstant.ORDER_PRO_INFO_TYPE_5));
                            if (ObjectUtil.isEmpty(proInfoList) && Objects.equals(appOrder.getOrderStatus(), CommonConstant.ORDER_STATUS_1)) {
                                appOrder.setOrderStatus(CommonConstant.ORDER_STATUS_2);
                                appOrderMapper.updateById(appOrder);
                            }
                        }
                    }
                }else {
                    log.info("未查询到订单信息，表示当前人员属于延课人员不走订单");
                }
            });
        }
        return Boolean.TRUE;
    }

    @Override
    public List<AppCoursesVerificationRecord> courseQueryUsersList(String coursePriceRulesId, Integer orPostpone, Integer verifyStatus,
                                                                   String coachUserId) {
        return baseMapper.courseQueryUsersList(coursePriceRulesId,orPostpone, verifyStatus,coachUserId);
    }

    @Override
    public List<AppCoursesVerificationRecord> queryTemporaryCourseUser(String coursePriceRulesId, Integer orPostpone, Integer verifyStatus,
                                                                       String coachUserId) {
        return baseMapper.queryTemporaryCourseUser(coursePriceRulesId,orPostpone, verifyStatus,coachUserId);
    }
}
