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.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.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);
                //地址列表
                infoDto.setAddressList(CommonUtil.getAddressList(dto.getAddressList()));
                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);
        //地址列表
        dto.setAddressList(CommonUtil.getAddressList(beneficiary.getAddressList()));
        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);
        List<ApiBeneficiaryInfoDto> list = new ArrayList<>();
        list.add(apiBeneficiaryInfoDto);
        //批量编辑受益人信息表数据
        batchEditBeneficiaryData(list,apiBeneficiaryInfoDto.getAppointmentBizId());
        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
    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);
            //地址列表（json串）
            beneficiary.setAddressList(CommonUtil.getAddressListJsonStr(dto.getAddressList()));
            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();
        }

//        //获取不为空的受益人信息表唯一业务ID列表
//        List<String> beneficiaryBizIdList = list.stream()
//                .filter(dto -> StringUtils.isNotBlank(dto.getBeneficiaryBizId()))
//                .map(ApiBeneficiaryInfoDto::getBeneficiaryBizId)
//                .collect(Collectors.toList());
//
//        if (!CollectionUtils.isEmpty(beneficiaryBizIdList)) {
//            //入参的受益人业务id列表至少一个不为空就走表数据校验，全部为空是全部新增操作，不走表数据校验
//
//            //根据受益人信息表唯一业务ID列表查询表里面的列表信息
//            List<Beneficiary> beneficiarys = iBeneficiaryService.queryList(BeneficiaryDto.builder()
//                    .beneficiaryBizIdList(beneficiaryBizIdList).build());
//
//            //过滤入参的受益人列表信息在表里不存在的集合，然后抛出这些不存在的列表信息
//            // 提取 existingBeneficiaryBizIds：从 beneficiarys 中获取所有已存在的 beneficiaryBizId 集合
//            Set<String> existingBeneficiaryBizIds = beneficiarys.stream()
//                    .map(Beneficiary::getBeneficiaryBizId)
//                    .collect(Collectors.toSet());
//            // 过滤 list：保留 beneficiaryBizId 不在 existingBeneficiaryBizIds 中的对象
//            List<ApiBeneficiaryInfoDto> filteredList = list.stream()
//                    .filter(dto -> StringUtils.isNotBlank(dto.getBeneficiaryBizId()) && !existingBeneficiaryBizIds.contains(dto.getBeneficiaryBizId()))
//                    .collect(Collectors.toList());
//            if (!CollectionUtils.isEmpty(filteredList)) {
//                //入参对象列表中有传值的业务id在库中不存在的对象，提示
//                List<String> beneficiaryProductNameList = filteredList
//                        .stream()
//                        .map(ApiBeneficiaryInfoDto::getName)
//                        .collect(Collectors.toList());
//                throw new BusinessException("以下是在库里不存在的受益人数据的名字："+String.join(" ；",beneficiaryProductNameList));
//            }
//        }

        //先删后增加
        iBeneficiaryService.del(appointmentBizId);

        //构造需要新增或者更新数据的对象集合
        List<Beneficiary> updateList = list.stream().map(dto -> {
            Beneficiary beneficiary = new Beneficiary();
            BeanUtils.copyProperties(dto,beneficiary);
            beneficiary.setAppointmentBizId(appointmentBizId);
            if (StringUtils.isBlank(dto.getBeneficiaryBizId())) {
                //为空表示新增数据
                //生成受益人信息表唯一业务ID
                beneficiary.setBeneficiaryBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_BENEFICIARY.getCode()));
            }
            //地址列表（json串）
            beneficiary.setAddressList(CommonUtil.getAddressListJsonStr(dto.getAddressList()));
            beneficiary.setId(null);
            return beneficiary;
        }).collect(Collectors.toList());

        //批量新增或者更新
        iBeneficiaryService.saveOrUpdateBatch(updateList);

        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);
    }
}
