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

import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiAppointmentCheckService;
import com.yd.csf.api.service.ApiBeneficiaryService;
import com.yd.csf.feign.dto.appointment.ApiBeneficiaryInfoDto;
import com.yd.csf.feign.dto.appointment.ApiBeneficiaryInfoFzDto;
import com.yd.csf.feign.request.beneficiary.ApiBatchEditBeneficiaryRequest;
import com.yd.csf.feign.utils.CommonUtil;
import com.yd.csf.service.dto.BeneficiaryDto;
import com.yd.csf.service.model.Beneficiary;
import com.yd.csf.service.model.Insurant;
import com.yd.csf.service.service.IBeneficiaryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 受益人信息业务实现类
 */
@Slf4j
@Service
public class ApiBeneficiaryServiceImpl implements ApiBeneficiaryService {

    @Autowired
    private IBeneficiaryService iBeneficiaryService;

    @Autowired
    private ApiAppointmentCheckService apiAppointmentCheckService;

    /**
     * 受益人信息列表查询
     * @param appointmentBizId
     * @return
     */
    @Override
    public Result<List<ApiBeneficiaryInfoDto>> list(String appointmentBizId) {
        List<ApiBeneficiaryInfoDto> dtoList = new ArrayList<>();
        List<Beneficiary> list = iBeneficiaryService.queryList(BeneficiaryDto.builder()
                .appointmentBizId(appointmentBizId)
                .build());
        if (!CollectionUtils.isEmpty(list)) {
            dtoList = list.stream().map(dto -> {
                ApiBeneficiaryInfoDto infoDto = new ApiBeneficiaryInfoDto();
                BeanUtils.copyProperties(dto,infoDto);
                return infoDto;
            }).collect(Collectors.toList());
        }
        return Result.success(dtoList);
    }

    /**
     * 受益人信息详情
     * @param beneficiaryBizId 受益人信息表唯一业务ID
     * @return
     */
    @Override
    public Result<ApiBeneficiaryInfoDto> detail(String beneficiaryBizId) {
        //校验受益人信息是否存在
        Result<Beneficiary> result = checkBeneficiaryIsExist(beneficiaryBizId);
        Beneficiary beneficiary = result.getData();
        ApiBeneficiaryInfoDto dto = new ApiBeneficiaryInfoDto();
        BeanUtils.copyProperties(beneficiary,dto);
        return Result.success(dto);
    }

    /**
     * 新增单个受益人信息
     * @param apiBeneficiaryInfoDto
     * @return
     */
    @Override
    public Result add(ApiBeneficiaryInfoDto apiBeneficiaryInfoDto) {
        List<ApiBeneficiaryInfoDto> list = new ArrayList<>();
        list.add(apiBeneficiaryInfoDto);
//        apiAppointmentCheckService.checkAddApiBeneficiaryInfoDtoList(list);

        //批量添加受益人信息表数据
        batchAddBeneficiaryData(list,apiBeneficiaryInfoDto.getAppointmentBizId());
        return Result.success();
    }

    /**
     * 编辑单个受益人信息
     * @param apiBeneficiaryInfoDto
     * @return
     */
    @Override
    public Result edit(ApiBeneficiaryInfoDto apiBeneficiaryInfoDto) {
        //编辑预约入参字段校验 - 编辑单个受益人信息字段校验
        apiAppointmentCheckService.checkEditApiBeneficiaryInfoDto(apiBeneficiaryInfoDto);
        //校验受益人信息是否存在
        Result<Beneficiary> result = checkBeneficiaryIsExist(apiBeneficiaryInfoDto.getBeneficiaryBizId());
        Beneficiary beneficiary = result.getData();
        BeanUtils.copyProperties(apiBeneficiaryInfoDto,beneficiary);
        beneficiary.setId(result.getData().getId());
        beneficiary.setAppointmentBizId(result.getData().getAppointmentBizId());
        iBeneficiaryService.saveOrUpdate(beneficiary);
        return Result.success();
    }

    /**
     * 批量编辑受益人信息
     * @param request
     * @return
     */
    @Override
    public Result batchEdit(ApiBatchEditBeneficiaryRequest request) {
        apiAppointmentCheckService.checkEditApiBeneficiaryInfoDtoList(request.getApiBeneficiaryInfoDtoList());
        //批量编辑受益人信息表数据
        batchEditBeneficiaryData(request.getApiBeneficiaryInfoDtoList(),request.getAppointmentBizId());
        return Result.success();
    }

    /**
     * 删除单个受益人信息
     * @param beneficiaryBizId
     * @return
     */
    @Override
    public Result del(String beneficiaryBizId) {
        //校验受益人信息是否存在
        Result<Beneficiary> result = checkBeneficiaryIsExist(beneficiaryBizId);
        Beneficiary beneficiary = result.getData();
        iBeneficiaryService.removeById(beneficiary.getId());
        return Result.success();
    }

    /**
     * 批量添加受益人信息表数据
     * @param apiBeneficiaryInfoDtoList
     * @param appointmentBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result batchAddBeneficiaryData(List<ApiBeneficiaryInfoDto> apiBeneficiaryInfoDtoList,
                                                       String appointmentBizId) {
        if (CollectionUtils.isEmpty(apiBeneficiaryInfoDtoList)){
            //为空放行
            return Result.success();
        }

        //构造需要新增数据的对象集合
        List<Beneficiary> beneficiaryList = apiBeneficiaryInfoDtoList.stream().map(dto -> {
            Beneficiary beneficiary = new Beneficiary();
            BeanUtils.copyProperties(dto,beneficiary);
            //生成受益人信息表唯一业务ID
            beneficiary.setBeneficiaryBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_BENEFICIARY.getCode()));
            //预约信息主表唯一业务ID
            beneficiary.setAppointmentBizId(appointmentBizId);
            return beneficiary;
        }).collect(Collectors.toList());

        iBeneficiaryService.saveOrUpdateBatch(beneficiaryList);

        return Result.success();
    }

    /**
     * 批量编辑受益人信息表数据
     * @param list
     * @param appointmentBizId
     * @return
     */
    @Override
    public Result batchEditBeneficiaryData(List<ApiBeneficiaryInfoDto> list,String appointmentBizId) {
        if (CollectionUtils.isEmpty(list)){
            //为空放行
            return Result.success();
        }
        //先删后增加
        iBeneficiaryService.del(appointmentBizId);
        //新增
        List<Beneficiary> saveList = list.stream().map(dto -> {
            Beneficiary beneficiary = new Beneficiary();
            BeanUtils.copyProperties(dto,beneficiary);
            beneficiary.setId(null);
            beneficiary.setAppointmentBizId(appointmentBizId);
            beneficiary.setBeneficiaryBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_BENEFICIARY.getCode()));
            return beneficiary;
        }).collect(Collectors.toList());
        //批量新增
        iBeneficiaryService.saveOrUpdateBatch(saveList);
        return Result.success();
    }

    /**
     * 校验受益人信息是否存在
     * @param beneficiaryBizId
     * @return
     */
    public Result<Beneficiary> checkBeneficiaryIsExist(String beneficiaryBizId) {
        Beneficiary beneficiary = iBeneficiaryService.queryOne(beneficiaryBizId);
        if (Objects.isNull(beneficiary)) {
            //数据不存在
            throw new BusinessException(ResultCode.NULL_ERROR.getCode(),ResultCode.NULL_ERROR.getMessage());
        }
        return Result.success(beneficiary);
    }
}
