package com.bonus.sharedstation.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.sharedstation.api.DictDataApi;
import com.bonus.sharedstation.api.vo.DictDataInfoDO;
import com.bonus.sharedstation.app.domain.ReservationContentDTO;
import com.bonus.sharedstation.app.domain.TherapyAppointments;
import com.bonus.sharedstation.app.dto.PaymentDto;
import com.bonus.sharedstation.app.dto.TherapyAppointmentsDTO;
import com.bonus.sharedstation.app.feign.OtherServiceClient;
import com.bonus.sharedstation.app.mapper.TherapyAppointmentsMapper;
import com.bonus.sharedstation.app.service.ITherapyAppointmentsService;
import com.bonus.sharedstation.app.vo.AjaxResultVo;
import com.bonus.sharedstation.app.vo.CodeTimeVO;
import com.bonus.sharedstation.common.pojo.ToDoEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Service实现
 *
 * @author 云归
 * @date 2024-03-15
 */
@Service
@Transactional(readOnly = true)
@Slf4j
public class TherapyAppointmentsServiceImpl extends ServiceImpl<TherapyAppointmentsMapper, TherapyAppointments> implements ITherapyAppointmentsService {

    private final ReentrantLock lock = new ReentrantLock();

    @Resource
    private TherapyAppointmentsMapper dao;

//    @Value("${niu.niupayurl}")
//    private String niupayurl;
//
//    @Value("${niu.niusearchuserurl}")
//    private String niusearchuserurl;
//
//    @Value("${niu.niupayreturnurl}")
//    private String niupayreturnurl;
//
//    @Value("${niu.applicationid}")
//    private String applicationid;
//
//    @Value("${niu.applicationidpsw}")
//    private String applicationidpsw;
//
//    @Value("${niu.sncode}")
//    private String sncode;
//
//    @Value("${niu.serialnum}")
//    private String serialnum;
//
//    @Value("${mljk.url}")
//    private String ML_BASE_URL;

    private static final String ML_CREATE_ORDER = "/api/PhysicalTherapy/CreateOrder";

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private OtherServiceClient otherServiceClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insert(TherapyAppointments dto) {
        try {
            // 检查是否已经存在相同的订单
            LambdaQueryWrapper<TherapyAppointments> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(TherapyAppointments::getOrderId, dto.getOrderId());
//            TherapyAppointments existingOrder = dao.selectOne(queryWrapper);
//            if (existingOrder != null) {
//                return AjaxResult.error("订单已存在，请勿重复提交");
//            }

            dto.setCreatedBy(SecurityUtils.getUsername());
            dto.setCreatedTime(new Date());
            dto.setUserId(String.valueOf(SecurityUtils.getUserId()));
            dto.setCustId(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
            dto.setCustId(String.valueOf(SecurityUtils.getUserId()));
            dto.setIsDeleted("0");
            List<DictDataInfoDO> equipmentTypeList = dictDataApi.getDictionaryInfo("time_slot");
            //拿到数据字典
            if (equipmentTypeList.isEmpty()) {
                throw new ServiceException("请先配置时间段字典");
            }
            //进行食堂卡进行扣费
            return payment(dto);
        } catch (Exception e) {
            return AjaxResult.error("支付失败！");
        }
    }

    /**
     * 支付逻辑
     *
     * @param dto 预约信息
     * @return 结果
     */
    private AjaxResult payment(TherapyAppointments dto) {
        if (ObjectUtil.isEmpty(dto.getProjectPrice())) {
            throw new IllegalArgumentException("支付金额不能为空！");
        }

        PaymentDto bean = new PaymentDto();
        bean.setMoney(dto.getProjectPrice());
        bean.setCustId(SecurityUtils.getUserId());

        //调用食堂卡支付
        AjaxResult result = otherServiceClient.payMoneyForStage(bean);
        AjaxResultVo ajaxResultVo = JSON.parseObject(JSON.toJSONString(result), AjaxResultVo.class);
        if (!ajaxResultVo.getCode().equals("200")) {
            return AjaxResult.error(ajaxResultVo.getMsg());
        }

        //新增订单信息 -- 出错调用退款
        dto.setOrderPayInfo(ajaxResultVo.getMsg());
        dto.setCustId(String.valueOf(SecurityUtils.getLoginUser().getUserid()));

        AjaxResult insertOrderInfoResult = insertOrderInfo(dto, bean, ajaxResultVo);
        AjaxResultVo insertOrderInfoErrorVo = JSON.parseObject(JSON.toJSONString(insertOrderInfoResult), AjaxResultVo.class);
        if (!insertOrderInfoErrorVo.getCode().equals("200")) {
            return AjaxResult.error(insertOrderInfoErrorVo.getMsg());
        }

        //创建预约订单
        ReservationContentDTO reservationContentDTO = JSON.parseObject(JSON.toJSONString(dto.getReservationContent()),
                ReservationContentDTO.class);
        AjaxResult createOrderInfo = createOrder(reservationContentDTO, ajaxResultVo, dto);
        AjaxResultVo createOrderInfoVo = JSON.parseObject(JSON.toJSONString(createOrderInfo), AjaxResultVo.class);
        if (!createOrderInfoVo.getCode().equals("200")) {
            return AjaxResult.error(createOrderInfoVo.getMsg());
        }
        return AjaxResult.success("预约成功");
    }

    /**
     * 新增订单
     *
     * @param dto          预约信息
     * @param bean         支付信息
     * @param ajaxResultVo 支付结果
     * @return 结果
     */
    private AjaxResult insertOrderInfo(TherapyAppointments dto, PaymentDto bean, AjaxResultVo ajaxResultVo) {
        try {
            //新增订单
            int code = this.baseMapper.insert(dto);
            if (code == 0) {
                return AjaxResult.error("订单异常，请稍后重试！");
            }
        } catch (Exception e) {
            bean.setOrderPayInfo(ajaxResultVo.getMsg());
            //调用食堂卡退款
            AjaxResult refundResultVo = refundOperation(bean);
            if (refundResultVo != null) {
                return refundResultVo;
            }
        }
        return AjaxResult.success();
    }

    /**
     * 创建订单
     *
     * @param reservationContentDTO 预约信息
     * @param payResult             支付结果
     * @param dto                   预约信息
     * @return 结果
     */
    public AjaxResult createOrder(ReservationContentDTO reservationContentDTO, AjaxResultVo payResult,
                                  TherapyAppointments dto) {
        //创建http请求  /api/PhysicalTherapy/CreateOrder 去创建订单
        //reservationContentDTO 所有值 转换为map
//        HttpRequest request = HttpUtil.createPost(ML_BASE_URL + ML_CREATE_ORDER);
//        request.body(JSONUtil.toJsonStr(reservationContentDTO), ContentType.JSON.toString());
//        HttpResponse response = request.execute();
////先验证名流 那边有没有预约成功
//        if (StringUtils.isEmpty(dto.getMlReturnStatus())) {
//            throw new RuntimeException("预约名流服务异常,请联系管理员");
//        }
//        if (Constant.FAILED.equals(dto.getMlReturnStatus())) {
//            throw new RuntimeException("预约名流医疗服务异常,请联系管理员");
//        }
        boolean payStatus = true;

        if (payStatus) {
            //成功返回
            // TODO 创建理疗预约（三方平台） 业务逻辑 待编写
            return AjaxResult.success();
        } else {
            //失败返回
            PaymentDto bean = new PaymentDto();
            bean.setOrderPayInfo(payResult.getMsg());
            bean.setCustId(Long.valueOf(dto.getCustId()));
            //退款
            AjaxResult refundResultVo = refundOperation(bean);
            if (refundResultVo != null) {
                return refundResultVo;
            }

            //逻辑删除当前订单
            this.baseMapper.deleteById(dto.getId());
            return AjaxResult.error("理疗预约失败，请稍后重试！");
        }
    }

    /**
     * 退款操作
     *
     * @param bean 退款信息
     * @return 结果
     */
    private AjaxResult refundOperation(PaymentDto bean) {
        AjaxResult refundResult = otherServiceClient.refundMoneyForStage(bean);
        AjaxResultVo refundResultVo = JSON.parseObject(JSON.toJSONString(refundResult), AjaxResultVo.class);
        if (!refundResultVo.getCode().equals("200")) {
            return AjaxResult.error(refundResultVo.getMsg());
        }
        return null;
    }

//
//    /**
//     * 支付相关接入第三方小牛支付
//     * @param dto 预约信息
//     * @return AjaxResult
//     */
//    private AjaxResult payByNiu(TherapyAppointments dto) {
//        String appsecret = applicationidpsw;
//        //传参
//        HashMap<Object, Object> bodyMap = new HashMap<>(2);
//        if (StringUtils.isEmpty(SecurityUtils.getLoginUser().getSysUser().getPhonenumber())) {
//            return AjaxResult.error("用户信息获取失败！");
//        }
//        //根据手机号查询
//        bodyMap.put("mobile", SecurityUtils.getLoginUser().getSysUser().getPhonenumber());
//        String content = JSON.toJSONString(bodyMap, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
//        //构造请求验签参数方法
//
//        Map<String, Object> map = makeSign(content, appsecret, bodyMap);
//        HttpRequest request = HttpUtil.createPost(niusearchuserurl);
//        request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
//        HttpResponse response = request.execute();
//        //转成实体类
//        ObjectMapper objectMapper = new ObjectMapper();
//        try {
//            ApiResponse apiResponse = objectMapper.readValue(response.body(), ApiResponse.class);
//            ResponseDatad data = apiResponse.getData();
//            List<Customer> customerList = data.getCustomerList();
//            if (StringUtils.isEmpty(customerList)) {
//                log.info("没有找到对应餐卡,无法下单,请联系管理员配置");
//                return AjaxResult.error("没有找到对应餐卡,无法下单,请联系管理员配置");
//            }
//            Customer customer = customerList.get(0);
//            //传参
//            HashMap<Object, Object> bodyMapForPayContent = new HashMap<>(2);
//            //构建 content
//            intoMapEnity(bodyMapForPayContent, dto, customer);
//            String payContent = JSON.toJSONString(bodyMapForPayContent, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
//            Map<String, Object> payBodyMap = makeSign(payContent, appsecret, bodyMapForPayContent);
//
//            HttpRequest requestForPay = HttpUtil.createPost(niupayurl);
//            requestForPay.body(JSONUtil.toJsonStr(payBodyMap), ContentType.JSON.toString());
//            HttpResponse responseForPay = requestForPay.execute();
//            //转成实体类响应数据
//            ApiResponseForPay apiResponseForPay = objectMapper.readValue(responseForPay.body(), ApiResponseForPay.class);
//            if (apiResponseForPay == null) {
//                log.error("扣款食堂卡失败,请检查");
//                return AjaxResult.error( "小牛支付提示扣款食堂卡失败,请检查");
//            }
//            if (apiResponseForPay.getCode() == 10000) {
//                //使用锁,防止出现多扣款的情况
//                lock.lock(); // 获取锁
//                try {
//                    // 这里是新增数据的代码
//                    dto.setCustId(String.valueOf(SecurityUtils.getUserId()));
//                    boolean b = save(dto);
//                    if (!b) {
//                        return AjaxResult.error("新增理疗服务失败");
//                    }
//                    return AjaxResult.success( "新增理疗服务成功");
//                } finally {
//                    lock.unlock(); // 释放锁
//                }
//            }
//            return AjaxResult.error( "小牛支付提示:" + apiResponseForPay.getMsg());
//
//        } catch (Exception e) {
//            log.error("下单失败",e);
//            return AjaxResult.error( "新增理疗服务失败");
//        }
//    }
//
//    /**
//     * 支付相关接入第三方小牛支付 退款
//     *
//     * @param dto     预约信息
//     * @return AjaxResult
//     */
//    private AjaxResult payReturnByNiu(TherapyAppointments dto) {
//        //1 先查询人员对应的卡号
//        //应用秘钥
//        String appsecret = applicationidpsw;
//        //传参
//        HashMap<Object, Object> bodyMap = new HashMap<>(2);
//        if (StringUtils.isEmpty(SecurityUtils.getLoginUser().getSysUser().getPhonenumber())) {
//            log.info("下单没有配置手机号,无法下单,请联系管理员配置");
//            throw new RuntimeException("没有配置手机号,无法下单,请联系管理员配置");
//        }
//        //根据手机号查询
//        bodyMap.put("mobile", SecurityUtils.getLoginUser().getSysUser().getPhonenumber());
//        String content = JSON.toJSONString(bodyMap, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
//        log.info("请求内容转换为JSON字符串，字典排序：{}", content);
//        //构造请求验签参数方法
//
//        Map<String, Object> map = makeSign(content, appsecret, bodyMap);
//        HttpRequest request = HttpUtil.createPost(niusearchuserurl);
//        request.body(JSONUtil.toJsonStr(map), ContentType.JSON.toString());
//        HttpResponse response = request.execute();
//        log.info("response={}", response.body());
//        //转成实体类
//        ObjectMapper objectMapper = new ObjectMapper();
//        try {
//            ApiResponse apiResponse = objectMapper.readValue(response.body(), ApiResponse.class);
//            ResponseDatad data = apiResponse.getData();
//            List<Customer> customerList = data.getCustomerList();
//            if (StringUtils.isEmpty(customerList)) {
//                log.info("没有找到对应餐卡,无法下单,请联系管理员配置");
//                throw new RuntimeException("没有找到对应餐卡,无法下单,请联系管理员配置");
//            }
//            Customer customer = customerList.get(0);
//            //传参
//            HashMap<Object, Object> bodyMapForPayContent = new HashMap<>(2);
//            //构建 content
//            contrutContent(bodyMapForPayContent, dto, customer);
//            String payContent = JSON.toJSONString(bodyMapForPayContent, SerializerFeature.MapSortField, SerializerFeature.WriteMapNullValue);
//            Map<String, Object> payBodyMap = makeSign(payContent, appsecret, bodyMapForPayContent);
//
//            HttpRequest requestForPay = HttpUtil.createPost(niupayreturnurl);
//            log.info("request=" + JSONUtil.toJsonStr(payBodyMap));
//            requestForPay.body(JSONUtil.toJsonStr(payBodyMap), ContentType.JSON.toString());
//            HttpResponse responseForPay = requestForPay.execute();
//            log.info("responseForPay={}", responseForPay.body());
//            //转成实体类响应数据
//            String resultResponse = responseForPay.body();
//            // 直接将 JSON 解析为 Map
//            Map<String, Object> jsonMap = objectMapper.readValue(resultResponse, Map.class);
//            String code = jsonMap.get("code").toString();
//            String msg = jsonMap.get("msg").toString();
//            if (code.equals("10000")) {
//                boolean b = updateById(dto);
//                if (!b) {
//                    return AjaxResult.error( "理疗服务修改失败");
//                }
//                return AjaxResult.success( "理疗服务修改成功");
//            }else{
//                return AjaxResult.success( "小牛支付提示:"+msg );
//            }
//
//        } catch (Exception e) {
//            log.error("退款失败",e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            throw new RuntimeException("退款失败");
//        }
//    }
//
//    /**
//     * 构建参数 content
//     *
//     * @param bodyMap
//     * @param dto
//     * @param customer
//     */
//    private void intoMapEnity(HashMap bodyMap, TherapyAppointments dto, Customer customer) {
//        //金额
//        Double usePrice = dto.getProjectPrice();
//        int convertedPrice = (int) (usePrice * 100);
//        bodyMap.put("amount", convertedPrice);
//        //人员 id
//        bodyMap.put("custId", Long.valueOf(customer.getCustId()));
//        //流水号
//        bodyMap.put("macOrdId", dto.getOrderId());
//        //sn码
//        bodyMap.put("machineSn", sncode);
//        //
//        bodyMap.put("nuClearMode", 2);
//
//        bodyMap.put("ordTime", DateUtils.formatDate(dto.getCreatedTime()));
//
//        bodyMap.put("deliveryType", "2");
//        //
//    }
//
//    /**
//     * 构建退款 参数 content
//     *
//     * @param bodyMap 退款参数
//     * @param dto    预约信息
//     * @param customer 人员信息
//     */
//    private void contrutContent(HashMap bodyMap, TherapyAppointments dto, Customer customer) {
//        //此次退款金额（分）注：不传或传0表示需整单退款
//        bodyMap.put("refundAmount", 0);
//        bodyMap.put("macOrdId", dto.getOrderId());
//        bodyMap.put("ordId", "");
//        bodyMap.put("refundMacOrdId", "");
//        bodyMap.put("backType", 1);
//
//        bodyMap.put("remark", "");
//        //
//    }
//
//
//    private Map<String, Object> makeSign(String content, String appsecret, HashMap<Object, Object> bodyMap) {
//        Map<String, Object> map = new TreeMap<>();
//        map.put("appid", applicationid);
//        map.put("version", "1.0.0");
//        map.put("signtype", "md5");
//        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
//        map.put("nonce", RandomUtil.randomNumbers(10));
//        map.put("content", content);
//        //生成sign，防篡改
//        String toSignStr = Joiner.on("&")
//                .useForNull("")
//                .withKeyValueSeparator("=")
//                .join(map) + "&appsecret=" + appsecret;
//        log.info("所有参数字典排序，待加签String：{}", toSignStr);
//
//        // md5/sha256 加签（其他方式待提供）
//        String sign = DigestUtils.md5Hex(toSignStr).toUpperCase();
//        System.err.println("sign: " + sign);
//        log.info("加签String：{}", sign);
//        map.put("sign", sign);
//
//        //post请求
//        map.replace("content", bodyMap);
//        return map;
//    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateInfoById(TherapyAppointments dto) {
        try {
            log.info("修改 入参: {}", dto);
            if (StringUtils.isEmpty(dto.getCustId())) {
                return AjaxResult.error("id不能为空");
            }
            if (StringUtils.isEmpty(dto.getOrderPayInfo())) {
                return AjaxResult.error("支付信息不能为空");
            }
            dto.setUpdatedBy(SecurityUtils.getUsername());
            dto.setUpdatedTime(new Date());

            //退款操作
            PaymentDto bean = new PaymentDto();
            bean.setOrderPayInfo(dto.getOrderPayInfo());
            bean.setCustId(Long.valueOf(dto.getCustId()));
            AjaxResult refundResult = refundOperation(bean);
            if (refundResult != null) {
                return refundResult;
            }

            //修改订单信息
            TherapyAppointments therapyAppointments = new TherapyAppointments();
            therapyAppointments.setId(dto.getId());
            therapyAppointments.setStatus("1");
            boolean b = updateById(therapyAppointments);
            if (!b) {
                return AjaxResult.error("理疗服务数据修改失败");
            }

        } catch (Exception e) {
            return AjaxResult.error("退款失败，请联系管理员进行处理！");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getListPage(TherapyAppointmentsDTO dto) {
        LambdaQueryWrapper<TherapyAppointments> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<TherapyAppointments> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        // 根据userId是否提供来动态添加条件
        if (dto.getUserId() != null) {
            queryWrapper.eq(TherapyAppointments::getUserId, dto.getUserId());
        }
        if (StringUtils.isNotEmpty(dto.getPatientName())) {
            queryWrapper.like(TherapyAppointments::getPatientName, dto.getPatientName());
        }
        queryWrapper
                .eq(TherapyAppointments::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(TherapyAppointments::getCreatedTime);

        Page<TherapyAppointments> result = dao.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult getListPageApp(TherapyAppointmentsDTO dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<TherapyAppointments> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<TherapyAppointments> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        queryWrapper
                .like(TherapyAppointments::getPhoneNumber, dto.getPhoneNumber())
                .eq(TherapyAppointments::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(TherapyAppointments::getCreatedTime);

        Page<TherapyAppointments> result = dao.selectPage(page, queryWrapper);
        //处理参数问题
        return AjaxResult.success(result);
    }

    @Override
    @Transactional(readOnly = false)
    public AjaxResult delete(TherapyAppointments dto) {
        return AjaxResult.success(dao.deleteById(dto.getId()));
    }

    @Override
    public AjaxResult selectAll(TherapyAppointments dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<TherapyAppointments> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        queryWrapper
                .like(TherapyAppointments::getPatientName, dto.getPatientName())
                .eq(TherapyAppointments::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(TherapyAppointments::getCreatedTime);

        List<TherapyAppointments> result = dao.selectList(queryWrapper);
        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult selectInfoById(TherapyAppointments dto) {
        TherapyAppointments result = dao.selectById(dto.getId());
        if (StringUtils.isNull(result)) {
            return AjaxResult.error("此预约理疗不存在");
        }
        //处理参数问题
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult selectByDate(TherapyAppointments dto) {
        LambdaQueryWrapper<TherapyAppointments> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = dateFormat.format(dto.getAppointmentDate());
        queryWrapper
                .like(TherapyAppointments::getPatientName, dto.getPatientName())
                .eq(TherapyAppointments::getIsDeleted, dto.getIsDeleted())
                .eq(TherapyAppointments::getAppointmentDate, formatDate)
                .orderByDesc(TherapyAppointments::getCreatedTime);

        List<TherapyAppointments> result = dao.selectList(queryWrapper);

        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult selectDirCode(TherapyAppointments dto) {
        //远程调用system 服务
        List<DictDataInfoDO> equipmentTypeList = dictDataApi.getDictionaryInfo("time_slot");
        //拿到数据字典
        if (equipmentTypeList.isEmpty()) {
            throw new RuntimeException("请先配置设备数据字典");
        }
        List<CodeTimeVO> codeTimeVOList = new ArrayList<>();
        // 创建分页对象
        if (dto.getAppointmentDate() == null) {
            throw new RuntimeException("请先选择理疗预约日期!");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        LambdaQueryWrapper<TherapyAppointments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(TherapyAppointments::getIsDeleted, dto.getIsDeleted())
                .eq(TherapyAppointments::getStatus, "0")
                .eq(TherapyAppointments::getAppointmentDate, trimTime(dto.getAppointmentDate()))
                .orderByDesc(TherapyAppointments::getCreatedTime);

        List<TherapyAppointments> resultTherapyAppointments = dao.selectList(queryWrapper);
        for (DictDataInfoDO dictDataRespDTO : equipmentTypeList) {
            CodeTimeVO codeTimeVO = new CodeTimeVO();
            //数据库中当前日期的 理疗预约的时间段是不是有当前时间
            if (resultTherapyAppointments == null) {
                codeTimeVO.setTime(dictDataRespDTO.getDataValue());
                codeTimeVO.setStatus(ToDoEnum.STATUS_BUTTON_WRITE);
                codeTimeVO.setCode(dictDataRespDTO.getDataCode());
            } else {
                boolean b = resultTherapyAppointments.stream().noneMatch(s -> s.getAppointmentTime().equals(dictDataRespDTO.getDataCode()));
                codeTimeVO.setTime(dictDataRespDTO.getDataValue());
                if (b) {
                    codeTimeVO.setStatus(ToDoEnum.STATUS_BUTTON_WRITE);
                } else {
                    codeTimeVO.setStatus(ToDoEnum.STATUS_BUTTON_BLACK);
                }
                codeTimeVO.setCode(dictDataRespDTO.getDataCode());
            }
            codeTimeVOList.add(codeTimeVO);
        }

        return AjaxResult.success(codeTimeVOList);
    }


    public Date trimTime(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(sdf.format(date));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
