无关风月
2024-07-11 eb6b6dbb35a9f029e0b7d269773685c19fd40976
cloud-server-account/src/main/java/com/dsh/account/service/impl/TStudentServiceImpl.java
@@ -1,10 +1,62 @@
package com.dsh.account.service.impl;
import com.dsh.account.entity.TStudent;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.account.dto.*;
import com.dsh.account.entity.*;
import com.dsh.account.feignclient.activity.IntroduceRewardsClient;
import com.dsh.account.feignclient.activity.UserConponClient;
import com.dsh.account.feignclient.activity.model.IntrduceOfUserRequest;
import com.dsh.account.feignclient.competition.DeductionCompetitionsClient;
import com.dsh.account.feignclient.competition.ParticipantClient;
import com.dsh.account.feignclient.competition.model.GetStuSourseList;
import com.dsh.account.feignclient.competition.model.PurchaseRecordVo;
import com.dsh.account.feignclient.competition.model.SaveParticipant;
import com.dsh.account.feignclient.course.*;
import com.dsh.account.feignclient.course.model.*;
import com.dsh.account.feignclient.other.NoticeClient;
import com.dsh.account.feignclient.other.QuestionClient;
import com.dsh.account.feignclient.other.SiteClient;
import com.dsh.account.feignclient.other.StoreClient;
import com.dsh.account.feignclient.other.model.*;
import com.dsh.account.mapper.CoachMapper;
import com.dsh.account.mapper.TAppUserMapper;
import com.dsh.account.mapper.TStudentMapper;
import com.dsh.account.model.vo.classDetails.ClasspaymentRequest;
import com.dsh.account.model.vo.classDetails.StuEditInfoReq;
import com.dsh.account.model.vo.classDetails.classInsVo.ClassDetailsInsVo;
import com.dsh.account.model.vo.classDetails.classInsVo.StuDetailsReq;
import com.dsh.account.model.vo.classDetails.classInsVo.StuListVo;
import com.dsh.account.model.vo.exploreDetail.LonLatRequest;
import com.dsh.account.model.vo.exploreDetail.QuestionIns;
import com.dsh.account.model.vo.exploreDetail.StoreDetailsVo;
import com.dsh.account.model.vo.exploreDetail.StoreOfCourseVo;
import com.dsh.account.model.vo.sourceDetail.CouponStuAvailableVo;
import com.dsh.account.model.vo.sourceDetail.CourseDetailsOfContinuationResp;
import com.dsh.account.model.vo.sourceDetail.RecordTimeRequest;
import com.dsh.account.service.TCourseInfoRecordService;
import com.dsh.account.service.TStudentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dsh.account.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
/**
 * <p>
@@ -17,4 +69,846 @@
@Service
public class TStudentServiceImpl extends ServiceImpl<TStudentMapper, TStudent> implements TStudentService {
    @Resource
    private CourseSessionNameClient sessionNameClient;
    @Resource
    private DeductionCompetitionsClient dcttClient;
    @Resource
    private CancelListClient cancelcClient;
    @Resource
    private IntroduceRewardsClient idrClient;
    @Resource
    private CourseRecordClient crClient;
    @Resource
    private CoursePaymentClient couPayClient;
    @Resource
    private UserConponClient userCClient;
    @Resource
    private StoreClient storeClient;
    @Resource
    private NoticeClient noClient;
    @Resource
    private QuestionClient quesClient;
    @Resource
    private TAppUserMapper tauMapper;
    @Resource
    private CoachMapper coachMapper;
    @Resource
    private ParticipantClient participantClient;
    @Autowired
    private CoursePackageClient coursePackageClient;
    @Autowired
    private PayMoneyUtil payMoneyUtil;
    @Resource
    private SiteClient steClient;
    @Resource
    private CourseListClient culisClient;
    @Autowired
    private TCourseInfoRecordService courseInfoRecordService;
    @Override
    public ResultUtil addStuOfAppUser(StuDetailsReq stu, Integer appUserId) throws Exception {
        TStudent student = new TStudent();
        if (ToolUtil.isNotEmpty(stu.getName()) && ToolUtil.isNotEmpty(stu.getIdCard())) {
            Boolean aBoolean = JuHeUtil.idcardAuthentication(stu.getIdCard(), stu.getName());
            if (!aBoolean) {
                return ResultUtil.error("身份证和姓名不匹配");
            }
        }
        student.setAppUserId(appUserId);
        student.setName(stu.getName());
        student.setHeadImg(stu.getHeadImg());
        student.setPhone(ToolUtil.isNotEmpty(stu.getPhone()) ? stu.getPhone() : "");
        student.setSex(stu.getSex());
        student.setIdCard(ToolUtil.isNotEmpty(stu.getIdCard()) ? stu.getIdCard() : "");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        student.setBirthday(sdf.parse(stu.getBirthday()));
        student.setHeight(stu.getHeight());
        student.setWeight(stu.getWeight());
        BigDecimal bigDecimal = BigDecimal.valueOf(stu.getWeight());
        double v = stu.getHeight() / 100;
        double v1 = v * v;
        BigDecimal bigDecimal1 = new BigDecimal(v1).setScale(2, RoundingMode.HALF_UP);
        double v2 = bigDecimal.doubleValue() / bigDecimal1.doubleValue();
        BigDecimal bigDecimal2 = new BigDecimal(v2).setScale(2, RoundingMode.HALF_UP);
        student.setBmi(bigDecimal2.doubleValue());
        student.setInsertTime(new Date());
        student.setState(1);
        List<TStudent> tStudents = this.baseMapper.selectList(new LambdaQueryWrapper<TStudent>().eq(TStudent::getAppUserId, appUserId));
        if (tStudents.size() > 0) {
            student.setIsDefault(2);
        } else {
            student.setIsDefault(1);
        }
        this.baseMapper.insert(student);
        //同步信息到参赛人员信息中
        SaveParticipant saveParticipant = new SaveParticipant();
        saveParticipant.setAppUserId(appUserId);
        saveParticipant.setName(student.getName());
        saveParticipant.setBirthday(student.getBirthday());
        saveParticipant.setGender(student.getSex());
        saveParticipant.setHeight(student.getHeight().intValue());
        saveParticipant.setWeight(student.getWeight());
        saveParticipant.setPhone(student.getPhone());
        saveParticipant.setIdcard(student.getIdCard());
        participantClient.saveParticipant(saveParticipant);
        return ResultUtil.success();
    }
    @Override
    public ClassDetailsInsVo querySessionDetailsDt(Integer userIdFormRedis, Integer lessonId, Integer stuId) {
        ClassDetailsInsVo insVo = new ClassDetailsInsVo();
        Date localMonthStart = DateTimeHelper.getCurrentMouthStart();
        Date localMonthEnd = DateTimeHelper.getCurrentMouthEnd();
        GetStuSessionList getStuSessionList = new GetStuSessionList();
        getStuSessionList.setStartTime(localMonthStart);
        getStuSessionList.setEndTime(localMonthEnd);
        getStuSessionList.setStuId(stuId);
        getStuSessionList.setAppUserId(userIdFormRedis);
        List<StuSessionDetailsVo> stuSessionList = sessionNameClient.getStuSessionList(getStuSessionList);
        TStudent tStudent = this.baseMapper.selectById(stuId);
        if (ToolUtil.isNotEmpty(tStudent)) {
            insVo.setStuId(tStudent.getId());
            insVo.setStuName(tStudent.getName());
            insVo.setStuImage(tStudent.getHeadImg());
            List<PurchaseRecordVo> purchaseRecordVoList = new ArrayList<>();
            GetStuSourseList getStuSourseList = new GetStuSourseList();
            getStuSourseList.setStartTime(localMonthStart);
            getStuSourseList.setEndTime(localMonthEnd);
            getStuSourseList.setAppUserId(userIdFormRedis);
            List<PurchaseRecordVo> stuSourseList = dcttClient.getStuSourseList(getStuSourseList);
            purchaseRecordVoList.addAll(stuSourseList);
            GetStuSessionList sessionList = new GetStuSessionList();
            sessionList.setStartTime(localMonthStart);
            sessionList.setEndTime(localMonthEnd);
            sessionList.setStuId(stuId);
            sessionList.setAppUserId(userIdFormRedis);
            List<PurchaseRecordVo> cancelCourseList = cancelcClient.getCancelCourseList(sessionList);
            purchaseRecordVoList.addAll(cancelCourseList);
            List<PurchaseRecordVo> purchaseRecordVos = sessionNameClient.queryCourseDetails(getStuSessionList);
            purchaseRecordVoList.addAll(purchaseRecordVos);
            List<TAppUser> tAppUsers = tauMapper.selectList(new QueryWrapper<TAppUser>()
                    .eq("referralUserId", userIdFormRedis)
                    .between("insertTime", localMonthStart, localMonthEnd));
            List<Integer> userIds = tAppUsers.stream().map(TAppUser::getId).collect(Collectors.toList());
            IntrduceOfUserRequest request = new IntrduceOfUserRequest();
            request.setStartTime(localMonthStart);
            request.setEndTime(localMonthEnd);
            request.setUserIds(userIds);
            List<PurchaseRecordVo> purchaseRecordVos1 = idrClient.queryAppUsersofIntroduce(request);
            purchaseRecordVoList.addAll(purchaseRecordVos1);
            insVo.setSessionNames(stuSessionList);
            insVo.setDetails(dealDataOfTime(purchaseRecordVoList));
            GetStuOfCoursesDetails getStuOfCoursesDetails = new GetStuOfCoursesDetails();
            getStuOfCoursesDetails.setStuId(stuId);
            getStuOfCoursesDetails.setAppUserId(userIdFormRedis);
            StuWithCoursesListVo stuOfCoursesDetails = couPayClient.getStuOfCoursesDetails(getStuOfCoursesDetails);
            insVo.setTotalNums(ToolUtil.isEmpty(stuOfCoursesDetails.getTotalNums()) ? 0 : stuOfCoursesDetails.getTotalNums());
            insVo.setDeductedNums(ToolUtil.isEmpty(stuOfCoursesDetails.getDeductedNums()) ? 0 : stuOfCoursesDetails.getDeductedNums());
            insVo.setRemainingNums(ToolUtil.isEmpty(stuOfCoursesDetails.getRemainingNums()) ? 0 : stuOfCoursesDetails.getRemainingNums());
            GetStudentCourse course = new GetStudentCourse();
            course.setCourseId(lessonId);
            course.setStuId(stuId);
            course.setAppUserId(userIdFormRedis);
            Integer deductionClassHour = crClient.getDeductionClassHour(course);
            insVo.setDeductionClassHours(deductionClassHour);
        }
        return insVo;
    }
    @Override
    public List<PurchaseRecordVo> queryDeduRecordDetails(RecordTimeRequest timeRequest, Integer appUserId) {
        List<PurchaseRecordVo> record1 = sessionNameClient.getRecord(timeRequest);
        return record1;
    }
    @Override
    public List<CouponStuAvailableVo> queryStuOfConponDetails(Integer appUserId) {
        List<CouponStuAvailableVo> availableVos = new ArrayList<>();
        availableVos = userCClient.queryUserWithConponList(appUserId);
        return availableVos;
    }
    @Override
    public CourseDetailsOfContinuationResp queryStuOfCourseDetails(Integer lessonId, Integer stuId, Integer appUserId) {
        CourseDetailsOfContinuationResp resp = new CourseDetailsOfContinuationResp();
        GetStudentCourse getStudentCourse = new GetStudentCourse();
        getStudentCourse.setCourseId(lessonId);
        getStudentCourse.setStuId(stuId);
        getStudentCourse.setAppUserId(appUserId);
        StudentOfCourseVo studentCourse = couPayClient.getStudentCourse(getStudentCourse);
        resp.setCoursePackageId(studentCourse.getCoursePackageId());
        resp.setStuId(stuId);
        resp.setPackageImg(studentCourse.getPackageImg());
        resp.setCourseName(studentCourse.getCourseName());
        Coach coach = coachMapper.selectById(studentCourse.getCoachId());
        resp.setTeacherName(coach.getName());
        resp.setCourseWeek(studentCourse.getCourseWeek());
        resp.setCourseTime(studentCourse.getCourseTime());
        StoreDetailOfCourse courseOfStore = storeClient.getCourseOfStore(studentCourse.getStoreId());
        resp.setStoreName(courseOfStore.getStoreName());
        resp.setStoreAddr(courseOfStore.getStoreAddr());
        resp.setTypeList(studentCourse.getTypeList());
        TStudent tStudent = this.baseMapper.selectById(stuId);
        resp.setStuName(tStudent.getName());
        resp.setStuPhone(tStudent.getPhone());
        resp.setStuAge(DateUtil.age(tStudent.getBirthday()));
        resp.setAmount(studentCourse.getAmount());
        resp.setVipAmount(studentCourse.getVipAmount());
        resp.setWpGold(studentCourse.getWpGold());
        return resp;
    }
    @Override
    public List<SysNotice> querySystemNoticeDetails() {
        return noClient.getSysNoticeDetails();
    }
    @Override
    public SysNotice queryNoticeData(Integer noId) {
        return noClient.getSysNoticeBuId(noId);
    }
    @Override
    public List<QuestionIns> queryQuestionData() {
        return quesClient.getSysQuestionDetails();
    }
    @Override
    public QuestionIns queryQuestionDataInfo(Integer quesId) {
        return quesClient.getSysQuestionBuId(quesId);
    }
    @Override
    public List<String> queryCustomerDetails() {
        return noClient.queryCustomerTel();
    }
    @Override
    public List<StoreInfo> queryIndexOfExplores(LonLatRequest llrequest) {
        GetAllNearbyStoreList getAllNearbyStoreList = new GetAllNearbyStoreList();
        getAllNearbyStoreList.setLongitude(llrequest.getLongitude());
        getAllNearbyStoreList.setLatitude(llrequest.getLatitude());
        return storeClient.getAllNearbyStoreList(getAllNearbyStoreList);
    }
    @Override
    public List<StuListVo> switchStudentActions(Integer appUserId, Integer stuId) {
        List<StuListVo> stuListVos = new ArrayList<>();
        List<TStudent> tStudents = this.baseMapper.selectList(new QueryWrapper<TStudent>()
                .eq("appUserId", appUserId)
                .eq("state", 1));
        if (tStudents.size() > 0) {
            tStudents.forEach(sts -> {
                if (Objects.equals(sts.getId(), stuId)) {
                    sts.setIsDefault(1);
                } else {
                    sts.setIsDefault(2);
                }
                this.baseMapper.updateById(sts);
                StuListVo vo = new StuListVo();
                vo.setStuId(sts.getId());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                vo.setBirthday(simpleDateFormat.format(sts.getBirthday()));
                vo.setStuName(sts.getName());
                vo.setStuAge(DateUtil.age(sts.getBirthday()));
                vo.setStuHeight(sts.getHeight());
                vo.setStuWeight(sts.getWeight());
                vo.setIsNot(sts.getIsDefault());
                stuListVos.add(vo);
            });
        }
        return stuListVos;
    }
    public static List<PurchaseRecordVo> dealDataOfTime(List<PurchaseRecordVo> purchaseRecords) {
        Collections.sort(purchaseRecords, new Comparator<PurchaseRecordVo>() {
            @Override
            public int compare(PurchaseRecordVo record1, PurchaseRecordVo record2) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
                Date date1 = null;
                Date date2 = null;
                try {
                    date1 = dateFormat.parse(record1.getPurchaseTime());
                    date2 = dateFormat.parse(record2.getPurchaseTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                // 倒序排序
                return date2.compareTo(date1);
            }
        });
        return purchaseRecords;
    }
    @Override
    public ResultUtil renewClassPayment(Integer userIdFormRedis, ClasspaymentRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
        TCoursePackagePayment packagePayment = new TCoursePackagePayment();
        packagePayment.setCode(code);
        packagePayment.setAppUserId(userIdFormRedis);
        packagePayment.setStudentId(request.getStuId());
        packagePayment.setCoursePackageId(request.getLessonId());
        packagePayment.setPayType(request.getPayType());
        packagePayment.setAbsencesNumber(0);
        packagePayment.setPayUserType(1);
        packagePayment.setPayStatus(1);
        packagePayment.setPayUserId(userIdFormRedis);
        packagePayment.setStatus(1);
        packagePayment.setState(1);
        packagePayment.setInsertTime(new Date());
        couPayClient.savePaymentCoursePackage(packagePayment);
        Integer hour = couPayClient.getClassHour(request.getCourseConfigId());
        try {
            switch (request.getPayType()) {
                case 1:
                    return WeChatPayment(code, request.getPayAmount(), hour);
                case 2:
                    return AlipayPayment(code, request.getPayAmount(), hour);
                case 3:
                    int i = PlaypaiGoldPayment(code, request);
                    switch (i) {
                        case 1:
                            return ResultUtil.success();
                        case 2:
                            return ResultUtil.error("用户未登录!");
                        case 3:
                            return ResultUtil.error("续课失败,玩湃币不足,请充值");
                        case 4:
                            return ResultUtil.error("续课失败,请联系管理员");
                    }
                default:
                    break;
            }
        } catch (Exception e) {
            ResultUtil.runErr();
        }
        return ResultUtil.success();
    }
    public ResultUtil WeChatPayment(String code, BigDecimal amount, Integer hour) throws Exception {
        ResultUtil weixinpay = payMoneyUtil.weixinpay("课包续费", "", code, amount.toString(),
                "/base/coursePackage/wechatPaymentCallback", "APP", "");
        if (weixinpay.getCode() == 200) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 10) {
                            int min = 5000;
                            wait += (min * num);
                            Thread.sleep(wait);
                            TCoursePackagePayment coursePackagePayment = couPayClient.getCoursePackagePaymentByCode(code);
                            if (coursePackagePayment.getPayStatus() == 2) {
                                break;
                            }
                            ResultUtil<Map<String, String>> resultUtil = payMoneyUtil.queryWXOrder(code, "");
                            if (resultUtil.getCode() == 200 && coursePackagePayment.getPayStatus() == 1) {
                                /**
                                 * SUCCESS—支付成功,
                                 * REFUND—转入退款,
                                 * NOTPAY—未支付,
                                 * CLOSED—已关闭,
                                 * REVOKED—已撤销(刷卡支付),
                                 * USERPAYING--用户支付中,
                                 * PAYERROR--支付失败(其他原因,如银行返回失败)
                                 */
                                Map<String, String> data1 = resultUtil.getData();
                                String s = data1.get("trade_state");
                                String transaction_id = data1.get("transaction_id");
                                if ("REFUND".equals(s) || "NOTPAY".equals(s) || "CLOSED".equals(s) || "REVOKED".equals(s) || "PAYERROR".equals(s) || num == 10) {
                                    coursePackagePayment.setState(3);
                                    couPayClient.delPaymentCoursePackage(coursePackagePayment.getId());
                                    break;
                                }
                                if ("SUCCESS".equals(s)) {
                                    coursePackagePayment.setPayStatus(2);
                                    coursePackagePayment.setTotalClassHours(hour);
                                    coursePackagePayment.setLaveClassHours(hour);
                                    coursePackagePayment.setOrderNumber(transaction_id);
                                    couPayClient.updatePaymentCoursePackage(coursePackagePayment);
                                    break;
                                }
                                if ("USERPAYING".equals(s)) {
                                    num++;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return weixinpay;
    }
    private String smid = "2088330203191220";//平台支付宝商户号
    public ResultUtil AlipayPayment(String code, BigDecimal amount, Integer hour) {
        TCoursePackagePayment coursePackagePayment = couPayClient.getCoursePackagePaymentByCode(code);
        Integer coursePackageId = coursePackagePayment.getCoursePackageId();
        // 判断这个课包是属于哪个运营商的
        CoursePackage coursePackage = coursePackageClient.queryCoursePackageById(coursePackageId);
        Integer storeId = coursePackage.getStoreId();
        Store store = storeClient.queryStoreById(storeId);
        String smid1= "";
        if (store.getOperatorId()==null){
            // 平台
            smid1 = smid;
        }else{
            String smidByOperatorId = storeClient.getSMIDByOperatorId(store.getOperatorId());
            smid1 = smidByOperatorId;
        }
        ResultUtil alipay = payMoneyUtil.alipay(smid1,"课包续费", "课包续费", "", code, amount.toString(),
                "/base/coursePackage/alipayPaymentCallback");
        if (alipay.getCode() == 200) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 10) {
                            int min = 5000;
                            wait += (min * num);
                            Thread.sleep(wait);
                            TCoursePackagePayment coursePackagePayment = couPayClient.getCoursePackagePaymentByCode(code);
                            if (coursePackagePayment.getPayStatus() == 2) {
                                break;
                            }
                            AlipayTradeQueryResponse resultUtil = payMoneyUtil.queryALIOrder(code);
                            if (resultUtil.getCode().equals("10000") && coursePackagePayment.getPayStatus() == 1) {
                                /**
                                 * WAIT_BUYER_PAY(交易创建,等待买家付款)、
                                 * TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、
                                 * TRADE_SUCCESS(交易支付成功)、
                                 * TRADE_FINISHED(交易结束,不可退款)
                                 */
//                                Map<String, String> data1 = resultUtil.getData();
//                                String s = data1.get("tradeStatus");
//                                String tradeNo = data1.get("tradeNo");
                                String tradeNo = resultUtil.getTradeNo();
                                String tradeStatus = resultUtil.getTradeStatus();
                                System.out.println("ssssss" + tradeStatus);
                                if ("TRADE_CLOSED".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus) || num == 10) {
                                    coursePackagePayment.setState(3);
                                    couPayClient.delPaymentCoursePackage(coursePackagePayment.getId());
                                    break;
                                }
                                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                                    coursePackagePayment.setPayStatus(2);
                                    coursePackagePayment.setTotalClassHours(hour);
                                    coursePackagePayment.setLaveClassHours(hour);
                                    coursePackagePayment.setOrderNumber(tradeNo);
                                    couPayClient.updatePaymentCoursePackage(coursePackagePayment);
                                    Integer coursePackageId = coursePackagePayment.getCoursePackageId();
                                    // 判断这个课包是属于哪个运营商的
                                    CoursePackage coursePackage = coursePackageClient.queryCoursePackageById(coursePackageId);
                                    Integer storeId = coursePackage.getStoreId();
                                    Store store = storeClient.queryStoreById(storeId);
                                    String smid1= "";
                                    if (store.getOperatorId()==null || store.getOperatorId() == 0){
                                        // 平台
                                        smid1 = smid;
                                        // 属于平台 不做资金冻结 不做分账处理
                                        payMoneyUtil.confirm(smid1,code,tradeNo,amount.toString());
                                    }else{
                                        String smidByOperatorId = storeClient.getSMIDByOperatorId(store.getOperatorId());
                                        smid1 = smidByOperatorId;
                                        payMoneyUtil.confirm1(smid1,code,tradeNo,amount.toString());
                                        // 分账处理
                                        extracted(store.getOperatorId(), amount, tradeNo);
                                    }
                                    break;
                                }
                                if ("WAIT_BUYER_PAY".equals(tradeStatus)) {
                                    num++;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return alipay;
    }
    private void extracted(Integer operatorId, BigDecimal coursePackageOrder1, String tradeNo) throws Exception {
        // 分账
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                "2021004105665036",
                "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCi5i9nW/hGLJ3A06cZxTQdviFC7THpdSihoTYGLr9q006hu0V26ecBMY/o4w5bvIX0Ok/yofmZsVcCJpAPvbXL/uqVrIjnRRxXiaeBFThlxoBUTdunvbUSDYfzlEhJr5NvUKI6H6lz2niXlQGx4qy8Hau4ccWit9kM8jwUvsBVQoFgJA+xrjMvooA7YLopQtpOD+UJr5thApTSf1xrnr1W12yolTLEH15JmNV372cqXrYUuqnY0QsaPtxeqJUGAOcGdVLllQ7easEznP8DFBvDdHATcmp2SHNQDUEWN6MCVPbMgY06NQVqAXxqjTAYSVh+6TRu6bofPmpYC3TZB003AgMBAAECggEBAJAcR2+PA3NBYUYHeFrqBRMS8uX8ZR19kjZ7IgoSLTFaQsP9opRylPSPXhrPVBKAE5leRQAHn4MCSlESwHvMfxo7KFjFTFAc6dffZZpipYQUOc9bGampwJh58/3e/pyBgVMG6J23CPf/HJQtNFSkjd/V9+ayb/9l2dUEL3bC0fAZ/dbx8HsxdLw8wn3fLlWLj68hOMqa2deCZe3JdSVsPbeWqkh56FFsMLug0Nd+Ar4TgRl9/jnhXF0JWiD0LmPUYLhboY7EfUBzN4w1iYbDi1P+3zvoOYsiVKAXox9GMhQ2VzOO2UcSTuizSza2e98mGpabl/GpKmCz+RDFjtkX6eECgYEA2MyCij65eO3aGIm3FUe93DULRBYTfX8qJQSJq2WOWA3mmQlEW6L3O2B5/lG2h+8WmN6iLEs9eHpgycGYp7vAqgrANEn16ACVcuyx0scFtrZfZ+kmHMzFfiUWxJjVYk/6YngsGVBLdw6ueM42C8TTP67X9tU5TdVGoGWuqEj4W98CgYEAwFqwprXOch5Pqk/RPbb49r0Ou03K/UbciWnWWKzUhFFNS8MdlQPoDvQZbMwHLeWsa2VhaKITK3x5biLQb3U+0GLOn6lTvEyrEUH+ucREyLgVYTRAvwBPtnvlrzpyxPk2HnslQjju8WrvvLLBMKWUjlTrTOzhaHT21gz3pHMiOakCgYEAhLmfaXdBITGshb054sNLDtdCkGpbgEcrzAHdLps769iGxkYQHXHFngpQZUwtTUcoNGqIKknd1jZFrv7gsD+XkgKG7PwimehRlkwmCX5ilxtLiVgJRzRt6+5U5AMVD90a0tHzXYP0z2yjj73fBJF5KtGl0a10KZxaYrQdm1UhB00CgYBZZgzx/k9rtHC8LAqIj1CYhHejT92G53c6Gkl3vyOqN4sgKhfGmSEySfrDGPRBPZxr8ZtbIPCd5mUdberH0osWGMYFaJI1UsCy7aQwvGpniz7MhZeN7dweaOjwDs8mgtjHQ96mL4XGCDhR0BZ/wIURvZ/6iaGdhbbu9unlsWj3uQKBgQCmZYdsbbZkd3ev6f8rwyvMz+DrCQyYpY44cegBYuJgrZiQnL2fJioeN7ixX0UM48SfwsZEIrzshP/LGAwnc2MdjxKUl4jLN8SEe0NAjXOnz9Zaw740+aOmLpXcLWdP4uM2gIhWsvW1tEkQZCXmm7c9s/RsU8Pmzv+YL3+fSijOzA==",
                "json", "GBK",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmu8n/4yTHWbn7VOrNc9OsLtDL1bEQ8gC1dHkj8Wy5z0mkaOsjJRIG/28ze12M0V8jdCKuuDr5Z1OPKiqf+XO3ypguEh+mYUVMBM/cZodDFQfTY1TKLWjvQCuaqlA+QUTCK6f7T7stsgyQ1o9Jj0rXZDz6PM4QHSTzjrLIBaeqM5WIBvH+fy/X+QG5Utd+/UT0kc0JyvuKhZ65yVUd/C9VcwJJAPliRsAQNrqYterwAJ9zvw9tF11wj9W0XgJ8Ccu4x3gR1vrlLRJJo/OA97RmxPQ+5hSacWQZCUd1dwiBq+YCrKVHGTj14izRHXrLc0yBlRXo7tBOIqcy3IsvKVthQIDAQAB",
                "RSA2");
        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
        String randomCode = UUIDUtil.getRandomCode(16);
        String proportionByOperatorId1 = storeClient.getProportionByOperatorId(operatorId);
        // 支付宝分账比例
        String s1 = proportionByOperatorId1.split(",")[1];
        double i = Double.parseDouble(s1);
        double v = i * 0.01;
        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(v));
        // 分账金额
        BigDecimal bigDecimal2 = coursePackageOrder1.multiply(bigDecimal1).setScale(2, RoundingMode.DOWN);
        request.setBizContent("{" +
                "  \"out_request_no\":\"" + randomCode + "\"," +
                "  \"trade_no\":\"" + tradeNo + "\"," +
                "  \"royalty_parameters\":[" +
                "    {" +
                "      \"royalty_type\":\"transfer\"," +
                "      \"trans_out\":\"" + storeClient.getSMIDByOperatorId(operatorId)+ "\"," +
                "      \"trans_out_type\":\"userId\"," +
                "      \"trans_in_type\":\"userId\"," +
                "      \"trans_in\":\"" + smid + "\"," +
                "      \"amount\":" + bigDecimal2 + "," +
                "      \"desc\":\"平台服务费\"," +
                "      \"royalty_scene\":\"平台服务费\"," +
                "    }" +
                "  ]," +
                "  \"extend_params\":{" +
                "    \"royalty_finish\":\"true\"" +
                "  }," +
                "  \"royalty_mode\":\"async\"" +
                "}");
        AlipayTradeOrderSettleResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
    public int PlaypaiGoldPayment(String code, ClasspaymentRequest request) {
        PlayPaiGoldCoursePackage paiGoldCoursePackage = new PlayPaiGoldCoursePackage();
        paiGoldCoursePackage.setCoursePackageId(request.getLessonId());
        paiGoldCoursePackage.setStuId(request.getStuId());
        paiGoldCoursePackage.setCoursePayConfigId(request.getCourseConfigId());
        paiGoldCoursePackage.setCode(code);
        return couPayClient.paymentWanpaiRenewCourse(paiGoldCoursePackage);
    }
    @Override
    public ResultUtil insertVipPaymentCallback(String code, String orderNumber) {
        TCoursePackagePayment coursePackagePayment = couPayClient.getCoursePackagePaymentByCode(code);
        if (coursePackagePayment.getPayStatus() != 1) {
            return ResultUtil.success();
        }
        coursePackagePayment.setPayStatus(2);
        coursePackagePayment.setOrderNumber(orderNumber);
        couPayClient.updatePaymentCoursePackage(coursePackagePayment);
        return ResultUtil.success();
    }
    /**
     * @param stuId         学员id
     * @param appUserId     用户id
     * @param appointStatus 预约状态 0=全部 1=待上课 2=已完成 3=已取消
     * @param timeType      时间类型 0=全部 1=近一周 2=近一个月 3=近一年
     * @param search        课程名称
     * @return
     */
    @Override
    public List<RecordAppoint> getAppointmentRecords(Integer stuId, Integer appUserId, Integer appointStatus, Integer timeType, String search, Integer pageNum) {
        WeeksOfCourseRest courseRest = new WeeksOfCourseRest();
        courseRest.setAppUserId(appUserId);
        courseRest.setStuId(stuId);
        courseRest.setPageNum(pageNum);
        List<RecordAppoint> recordAppoints = couPayClient.obtainStudentClassDetailsData(courseRest);
        if (recordAppoints.size() > 0) {
            if (ToolUtil.isNotEmpty(appointStatus) && appointStatus != 0) {
                if (appointStatus == 2) {
                    recordAppoints = recordAppoints.stream()
                            .filter(record -> record.getStatus().equals(3))
                            .collect(Collectors.toList());
                } else if (appointStatus == 3) {
                    recordAppoints = recordAppoints.stream()
                            .filter(record -> record.getStatus().equals(4))
                            .collect(Collectors.toList());
                } else {
                    recordAppoints = recordAppoints.stream()
                            .filter(record -> record.getStatus().equals(appointStatus))
                            .collect(Collectors.toList());
                }
            }
            if (ToolUtil.isNotEmpty(search)) {
                recordAppoints = recordAppoints.stream()
                        .filter(record -> record.getCoursePackageName().contains(search))
                        .collect(Collectors.toList());
            }
            if (ToolUtil.isNotEmpty(timeType) && timeType != 0) {
//                Date lastOfDate = DateUtil.getLastOfDate();
                Date lastOfDate = DateUtil.getDate();
                switch (timeType) {
                    case 1:
                        Date lastWeekStartDate = DateUtil.getLastWeekStartDate();
                        recordAppoints = recordAppoints.stream()
                                .filter(record -> {
                                    try {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        String substring = record.getTimeFrame().substring(0,16);
                                        Date time = sdf.parse(substring);
                                        Instant instant = time.toInstant();
                                        LocalDate dateToCheck = instant.atZone(ZoneId.systemDefault()).toLocalDate();
                                        // 获取今天的日期
                                        LocalDate today = LocalDate.now();
                                        // 计算一周前的日期
                                        LocalDate oneWeekAgo = today.minusWeeks(1);
                                        // 计算一周后的日期
                                        LocalDate oneWeekLater = today.plusWeeks(1);
                                        return dateToCheck.isAfter(oneWeekAgo) && dateToCheck.isBefore(oneWeekLater);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                        return false;
                                    }
                                })
                                .collect(Collectors.toList());
                        break;
                    case 2:
                        Date lastMonthStartDate = DateUtil.getLastMonthStartDate();
                        recordAppoints = recordAppoints.stream()
                                .filter(record -> {
                                    try {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        String substring = record.getTimeFrame().substring(0,16);
                                        Date time = sdf.parse(substring);
                                        Instant instant = time.toInstant();
                                        LocalDate dateToCheck = instant.atZone(ZoneId.systemDefault()).toLocalDate();
                                        // 获取今天的日期
                                        LocalDate today = LocalDate.now();
                                        // 计算一周前的日期
                                        LocalDate oneWeekAgo = today.minusMonths(1);
                                        // 计算一周后的日期
                                        LocalDate oneWeekLater = today.plusMonths(1);
                                        return dateToCheck.isAfter(oneWeekAgo) && dateToCheck.isBefore(oneWeekLater);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                        return false;
                                    }
                                })
                                .collect(Collectors.toList());
                        break;
                    case 3:
                        Date lastYearStartDate = DateUtil.getLastYearStartDate();
                        recordAppoints = recordAppoints.stream()
                                .filter(record -> {
                                    try {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        String substring = record.getTimeFrame().substring(0,16);
                                        Date time = sdf.parse(substring);
                                        Instant instant = time.toInstant();
                                        LocalDate dateToCheck = instant.atZone(ZoneId.systemDefault()).toLocalDate();
                                        // 获取今天的日期
                                        LocalDate today = LocalDate.now();
                                        // 计算一周前的日期
                                        LocalDate oneWeekAgo = today.minusYears(1);
                                        // 计算一周后的日期
                                        LocalDate oneWeekLater = today.plusYears(1);
                                        return dateToCheck.isAfter(oneWeekAgo) && dateToCheck.isBefore(oneWeekLater);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                        return false;
                                    }
                                })
                                .collect(Collectors.toList());
                        break;
                    default:
                        break;
                }
            }
        }
        return recordAppoints;
    }
    @Override
    public ResultUtil cancelReservationOfCourse(Integer courseStuRecordId) {
        Integer integer = crClient.cancelCourseRecordClass(courseStuRecordId);
        switch (integer) {
            case 1:
                ResultUtil.success();
                break;
            case 2:
                ResultUtil.error("开课前三小时不能取消!");
                break;
            default:
                ResultUtil.runErr();
                break;
        }
        return null;
    }
    /**
     * @param space     1=升序/2=降序
     * @param cityCode  城市code
     * @param latitude
     * @param longitude
     * @return
     */
    @Override
    public List<StoreDetailList> queryStoreList(Integer space, String cityCode, String latitude, String longitude, String search) {
        StoreOfCitycodeResp citycodeResp = new StoreOfCitycodeResp();
        citycodeResp.setCityCode(cityCode);
        citycodeResp.setLongitude(latitude);
        citycodeResp.setLatitude(longitude);
        List<StoreDetailList> queryStoreList = storeClient.getQueryStoreList(citycodeResp);
        if (queryStoreList.size() > 0) {
            if (ToolUtil.isEmpty(space) || space ==1) {
                queryStoreList = queryStoreList.stream().sorted(Comparator.comparing(o -> o.getStoreDistance())).collect(Collectors.toList());
            } else {
                queryStoreList = queryStoreList.stream()
                        .sorted(Comparator.comparing(StoreDetailList::getStoreDistance).reversed())
                        .collect(Collectors.toList());
            }
            if (ToolUtil.isNotEmpty(search)) {
                queryStoreList = queryStoreList.stream().filter(o -> o.getStoreName().contains(search)).collect(Collectors.toList());
            }
        }
        return queryStoreList;
    }
    @Override
    public StoreDetailsVo getStoreDetail(Integer storeId) {
        Store store = storeClient.queryStoreById(storeId);
        StoreDetailsVo detailsVo = new StoreDetailsVo();
        String realPicture = store.getRealPicture();
        if (ToolUtil.isNotEmpty(realPicture)) {
            String[] split = realPicture.split(",");
            detailsVo.setImages(Arrays.asList(split));
        }
        detailsVo.setStoreId(store.getId());
        detailsVo.setStoreName(store.getName());
        detailsVo.setStoreAddress(store.getAddress());
        detailsVo.setStoreTime(store.getStartTime() + "至" + store.getEndTime());
        detailsVo.setStoreInfo(store.getIntroduce());
        detailsVo.setLon(store.getLon());
        detailsVo.setLat(store.getLat());
        detailsVo.setPhone(store.getPhone());
        detailsVo.setVenueList(steClient.getAppUserSiteList(storeId));
        List<StoreOfCourseVo> storeOfCourseList = culisClient.getStoreOfCourseList(storeId);
        System.out.println(storeOfCourseList);
        for (StoreOfCourseVo storeOfCourseVo : storeOfCourseList) {
            if (storeOfCourseVo.getClassHours().equals("0")) {
                storeOfCourseVo.setClassHours(null);
            }
            if (storeOfCourseVo.getClassStartTime().equals("-")) {
                storeOfCourseVo.setClassStartTime(null);
            }
        }
        detailsVo.setCourseVoList(storeOfCourseList);
        return detailsVo;
    }
    @Override
    public ResultUtil commitEditStudentInfo(StuEditInfoReq stu, Integer userIdFormRedis) {
        TStudent tStudent = this.baseMapper.selectOne(new LambdaQueryWrapper<TStudent>()
                .eq(TStudent::getId, stu.getId())
                .eq(TStudent::getAppUserId, userIdFormRedis));
        if (ToolUtil.isEmpty(tStudent)) {
            ResultUtil.error("会员信息不存在!");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        tStudent.setHeadImg(stu.getHeadImg());
        tStudent.setName(stu.getName());
        tStudent.setPhone(ToolUtil.isEmpty(stu.getPhone()) ? "" : stu.getPhone());
        try {
            tStudent.setBirthday(simpleDateFormat.parse(stu.getBirthday()));
        } catch (ParseException e) {
            ResultUtil.runErr();
        }
        tStudent.setSex(stu.getSex());
        tStudent.setHeight(stu.getHeight());
        tStudent.setWeight(stu.getWeight());
        tStudent.setIdCard(ToolUtil.isEmpty(stu.getIdCard()) ? "" : stu.getIdCard());
        this.baseMapper.updateById(tStudent);
        return ResultUtil.success();
    }
    @Override
    public List<TStudentDto> listAll(StudentSearch search) {
        return this.baseMapper.selectAll(search);
    }
    @Override
    public TStudentDto listOne(Integer id) {
        return this.baseMapper.selectWebOne(id);
    }
    @Override
    public void createHistory(CreateHistoryDto createHistoryDto) {
        this.baseMapper.createHistory(createHistoryDto);
    }
    @Override
    public List<GetHistoryDto> getHistory() {
        return this.baseMapper.getHistory();
    }
    @Override
    public Integer getGiftSelect(GiftSearchDto giftSearchDto) {
        return this.baseMapper.getGiftSelect(giftSearchDto);
    }
    @Resource
    private SiteClient siteClient;
    @Override
    public List<Map<String, Object>> queryCom(Integer id) {
        List<Map<String, Object>> maps = this.baseMapper.queryCom(id);
        for (Map<String, Object> map : maps) {
            Integer coachId = (Integer) map.get("coachId");
            System.err.println("==============XXXXXXXXXXXX"+coachId);
            if (coachId!=null) {
                User name = siteClient.queryUserName(coachId);
                map.put("name",name.getName());
            }
        }
    return maps;
    }
}