package com.yd.csf.api.service.impl;

import com.yd.common.enums.CommonEnum;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiAppointmentReferrerService;
import com.yd.csf.feign.dto.appointment.ApiAppointmentReferrerDto;
import com.yd.csf.service.model.AppointmentReferrer;
import com.yd.csf.service.service.IAppointmentReferrerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiAppointmentReferrerServiceImpl implements ApiAppointmentReferrerService {

    @Autowired
    private IAppointmentReferrerService iAppointmentReferrerService;

    /**
     * 保存预约-转介人信息列表
     * @param referrerDtoList
     * @param appointmentBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveAppointmentReferrerList(List<ApiAppointmentReferrerDto> referrerDtoList,
                                              String appointmentBizId) {
        if (CollectionUtils.isEmpty(referrerDtoList)) {
            return Result.success();
        }
        //先删后新增
        iAppointmentReferrerService.delByAppointmentBizId(appointmentBizId);

        //新增
        List<AppointmentReferrer> saveList = referrerDtoList.stream().map(dto -> {
            AppointmentReferrer referrer = new AppointmentReferrer();
            BeanUtils.copyProperties(dto,referrer);
            referrer.setAppointmentBizId(appointmentBizId);
            referrer.setAppointmentReferrerBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_APPOINTMENT_REFERRER.getCode()));
            return referrer;
        }).collect(Collectors.toList());
        iAppointmentReferrerService.saveOrUpdateBatch(saveList);

        return Result.success();
    }

    /**
     * 查询-转介人信息列表
     * @param appointmentBizId
     * @return
     */
    @Override
    public List<ApiAppointmentReferrerDto> referrerDtoList(String appointmentBizId) {
        List<AppointmentReferrer> appointmentReferrerList = iAppointmentReferrerService.queryList(appointmentBizId);
        if (CollectionUtils.isEmpty(appointmentReferrerList)) {
            return new ArrayList<>();
        }
        List<ApiAppointmentReferrerDto> list = appointmentReferrerList.stream().map(dto -> {
            ApiAppointmentReferrerDto referrerDto = new ApiAppointmentReferrerDto();
            BeanUtils.copyProperties(dto,referrerDto);
            return referrerDto;
        }).collect(Collectors.toList());
        return list;
    }
}
