package com.fs.doctor.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fs.doctor.domain.Doctor;
import com.fs.doctor.domain.DoctorBalanceLog;
import com.fs.doctor.domain.LimitCycle;
import com.fs.doctor.mapper.DoctorMapper;
import com.fs.doctor.mapper.LimitCycleMapper;
import com.fs.provider.domain.ServiceGenConfig;
import com.fs.provider.domain.ServiceOrder;
import com.fs.provider.domain.ServiceOrderTaskRel;
import com.fs.provider.enums.BalanceBusinessType;
import com.fs.provider.enums.BalanceChangeTypeEnum;
import com.fs.provider.enums.DoctorConfirmEnum;
import com.fs.provider.enums.SettlementStatusEnum;
import com.fs.provider.mapper.ServiceOrderMapper;
import com.fs.provider.mapper.ServiceOrderTaskRelMapper;
import com.fs.provider.service.IServiceGenConfigRunLogService;
import com.fs.provider.service.IServiceGenConfigService;
import com.fs.provider.service.IServiceOrderService;
import com.fs.task.domain.ServiceGenResult;
import com.fs.task.domain.TaskInfo;
import com.fs.task.enums.TaskFinishStatusEnum;
import com.fs.task.mapper.TaskInfoMapper;
import com.fs.task.utils.RunKeyUtil;
import com.fs.task.utils.ServerIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("doctorQuartzTask")
public class DoctorQuartzTask {
    @Autowired
    private LimitCycleMapper limitCycleMapper;
    @Autowired
    private ServiceOrderMapper serviceOrderMapper;
    @Autowired
    private IDoctorBalanceLogService iDoctorBalanceLogService;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private ServiceOrderTaskRelMapper serviceOrderTaskRelMapper;

    /**
     * 扫描配置 -> 抢占 -> 生成服务单
     * 注意：无参，给 sys_job 调
     */
    public void limitBankCardQuartzTask() {
        System.out.println("医生定时任务正在执行--------------------------");
        limitCycleMapper.delete(new LambdaQueryWrapper<LimitCycle>()
                        .eq(LimitCycle::getLimitCycleKey, "day")
                        .eq(LimitCycle::getLimitType, "updateBankCard")
        );

        serviceOrderQuartzTask();
    }

    // 批量结算服务单方法
    private void serviceOrderQuartzTask() {
        System.out.println("批量结算服务单方法开始执行--------------------------11");
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setSettlementStatus(SettlementStatusEnum.UNSETTLED.getCode());
        serviceOrder.setDeleted(0L);
        List<ServiceOrder> serviceOrders = serviceOrderMapper.selectServiceOrderList(serviceOrder);

        for (ServiceOrder order : serviceOrders) {
            // 根据服务单中的 doctorId 查询医生信息
            Doctor doctor = doctorMapper.selectDoctorById(Long.parseLong(order.getDoctorId())); // 假设 ServiceOrder 中有 getDoctorId()

            // 添加积分流转记录
            DoctorBalanceLog doctorBalanceLog = new DoctorBalanceLog();
            doctorBalanceLog.setBusinessId(order.getId()); // 服务单ID作为业务ID
            doctorBalanceLog.setBusinessType(BalanceBusinessType.SERVICE_TICKET.toString());
            doctorBalanceLog.setDoctorId(Long.parseLong(order.getDoctorId()));
            doctorBalanceLog.setDoctorName(doctor.getDoctorName());
            doctorBalanceLog.setChangeType(BalanceChangeTypeEnum.INCREASE.getCode());
            doctorBalanceLog.setChangeMoney(order.getTotalAmount()); // 假设 ServiceOrder 中有 getTotalAmount()
            doctorBalanceLog.setRelatedTaskId(order.getId()); // 关联服务单ID
            iDoctorBalanceLogService.insertDoctorBalanceLog(doctorBalanceLog);

            // 修改医生账户余额（增加积分/金额）
            doctorMapper.addPoints(Long.parseLong(order.getDoctorId()), order.getTotalAmount());

            // 根据服务单查询所有任务项
            ServiceOrderTaskRel serviceOrderTaskRel = new ServiceOrderTaskRel();
            serviceOrderTaskRel.setServiceOrderId(order.getId());
            List<ServiceOrderTaskRel> serviceOrderTaskRels = serviceOrderTaskRelMapper.selectServiceOrderTaskRelList(serviceOrderTaskRel);
            List<Long> taskIds = serviceOrderTaskRels.stream()
                    .map(ServiceOrderTaskRel::getTaskId)
                    .collect(Collectors.toList());

            if (!taskIds.isEmpty()) {
                List<TaskInfo> taskInfos = taskInfoMapper.selectTaskInfoByIds(taskIds);
                taskInfos.forEach(taskInfo -> {
                    // 修改任务单为已完成
                    taskInfo.setFinishStatus(Long.parseLong(TaskFinishStatusEnum.FINISHED.getCode().toString()));
                    taskInfoMapper.updateTaskInfo(taskInfo);
                });
            }

            // 改变服务单确认状态
            ServiceOrder updateOrder = new ServiceOrder();
            updateOrder.setId(order.getId());
            updateOrder.setDoctorConfirm(DoctorConfirmEnum.CONFIRMED.getCode().longValue());
            updateOrder.setSettlementStatus(SettlementStatusEnum.SETTLED.getCode());
            serviceOrderMapper.updateServiceOrder(updateOrder);
        }
    }

}
