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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.common.enums.CommonEnum;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.common.utils.UrlPathExtractor;
import com.yd.csf.api.service.ApiPremiumRemittanceFileService;
import com.yd.csf.api.service.ApiPremiumRemittanceService;
import com.yd.csf.feign.dto.premiumremittance.ApiPremiumRemittanceDto;
import com.yd.csf.feign.dto.premiumremittancefile.ApiPremiumRemittanceFileDto;
import com.yd.csf.feign.request.premiumremittance.ApiPremiumRemittancePageRequest;
import com.yd.csf.feign.response.premiumreconciliation.ApiPremiumReconciliationPageResponse;
import com.yd.csf.service.dto.PremiumRemittanceDto;
import com.yd.csf.service.model.PremiumRemittance;
import com.yd.csf.service.service.IPremiumRemittanceService;
import com.yd.oss.feign.client.ApiOssFileFeignClient;
import com.yd.oss.feign.request.ApiOssFileListRequest;
import com.yd.oss.feign.response.ApiOssFileListResponse;
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.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiPremiumRemittanceServiceImpl implements ApiPremiumRemittanceService {

    @Autowired
    private IPremiumRemittanceService iPremiumRemittanceService;

    @Autowired
    private ApiPremiumRemittanceFileService apiPremiumRemittanceFileService;

    @Autowired
    private ApiOssFileFeignClient apiOssFileFeignClient;

    /**
     * 分页列表查询-保费对账汇款记录信息
     * @param request
     * @return
     */
    @Override
    public Result<IPage<ApiPremiumRemittanceDto>> page(ApiPremiumRemittancePageRequest request) {
        Page<ApiPremiumRemittanceDto> page = new Page<>(request.getPageNo(), request.getPageSize());
        IPage<ApiPremiumRemittanceDto> iPage = iPremiumRemittanceService.page(page, request);
        return Result.success(iPage);
    }

    /**
     * 添加-单个保费对账汇款记录信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(ApiPremiumRemittanceDto request) {
        if (StringUtils.isBlank(request.getPremiumReconciliationBizId())) {
            throw new BusinessException("保费对账记录表唯一业务ID不能为空");
        }
        List<ApiPremiumRemittanceDto> apiPremiumRemittanceDtoList = new ArrayList<>();
        apiPremiumRemittanceDtoList.add(request);
        //添加-保费对账汇款记录列表
        addPremiumRemittanceList(apiPremiumRemittanceDtoList,request.getPremiumReconciliationBizId());
        return Result.success();
    }

    /**
     * 编辑-单个保费对账汇款记录信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result edit(ApiPremiumRemittanceDto request) {
        if (StringUtils.isBlank(request.getPremiumRemittanceBizId())) {
            throw new BusinessException("保费对账-汇款记录表唯一业务ID不能为空");
        }
        Result<PremiumRemittance> result = checkPremiumRemittanceIsExist(request.getPremiumRemittanceBizId());
        PremiumRemittance premiumRemittance = result.getData();
        BeanUtils.copyProperties(request,premiumRemittance);
        //支付凭证
        List<String> paymentVoucherList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(request.getPaymentVoucherDtoList())) {
            paymentVoucherList = request.getPaymentVoucherDtoList().stream()
                    .filter(dto -> StringUtils.isNotBlank(dto.getFileUrl()))
                    .map(ApiPremiumRemittanceFileDto::getFileUrl)
                    .collect(Collectors.toList());
        }
        premiumRemittance.setPaymentVoucher(!CollectionUtils.isEmpty(paymentVoucherList) ? String.join(";",paymentVoucherList) : "");
        //账户证明
        List<String> accountVerificationList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(request.getAccountVerificationDtoList())) {
            accountVerificationList = request.getAccountVerificationDtoList().stream()
                    .filter(dto -> StringUtils.isNotBlank(dto.getFileUrl()))
                    .map(ApiPremiumRemittanceFileDto::getFileUrl)
                    .collect(Collectors.toList());
        }
        premiumRemittance.setAccountVerification(!CollectionUtils.isEmpty(accountVerificationList) ? String.join(";",accountVerificationList) : "");
        iPremiumRemittanceService.saveOrUpdate(premiumRemittance);
        //保存-保费对账汇款记录附件列表
        apiPremiumRemittanceFileService.savePremiumRemittanceFileList(request.getApiPremiumRemittanceFileDtoList(),request.getPremiumRemittanceBizId());
        return Result.success();
    }

    /**
     * 详情-保费对账汇款记录信息
     * @param premiumRemittanceBizId 保费对账-汇款记录表唯一业务ID
     * @return
     */
    @Override
    public Result<ApiPremiumRemittanceDto> detail(String premiumRemittanceBizId) {
        ApiPremiumRemittanceDto dto = new ApiPremiumRemittanceDto();
        Result<PremiumRemittance> result = checkPremiumRemittanceIsExist(premiumRemittanceBizId);
        PremiumRemittance premiumRemittance = result.getData();
        BeanUtils.copyProperties(premiumRemittance,dto);
        //其他资料列表
        List<ApiPremiumRemittanceFileDto> fileDtoList = apiPremiumRemittanceFileService.apiPremiumRemittanceFileDtoList(premiumRemittanceBizId);
        dto.setApiPremiumRemittanceFileDtoList(fileDtoList);
        return Result.success(dto);
    }

    /**
     * 删除-单个保费对账汇款记录信息
     * @param premiumRemittanceBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(String premiumRemittanceBizId) {
        checkPremiumRemittanceIsExist(premiumRemittanceBizId);
        //删除保费对账汇款记录附件列表
        apiPremiumRemittanceFileService.delByPremiumRemittanceBizId(premiumRemittanceBizId);
        //删除单个保费对账汇款记录信息
        iPremiumRemittanceService.delByPremiumRemittanceBizId(premiumRemittanceBizId);
        return Result.success();
    }

    /**
     * 添加-保费对账汇款记录列表
     * @param apiPremiumRemittanceDtoList
     * @param premiumReconciliationBizId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addPremiumRemittanceList(List<ApiPremiumRemittanceDto> apiPremiumRemittanceDtoList,
                                            String premiumReconciliationBizId) {
        if (CollectionUtils.isEmpty(apiPremiumRemittanceDtoList)) {
            return Result.success();
        }
        //添加保费对账汇款记录列表
        for (ApiPremiumRemittanceDto dto : apiPremiumRemittanceDtoList) {
            PremiumRemittance premiumRemittance = new PremiumRemittance();
            BeanUtils.copyProperties(dto,premiumRemittance);
            //保费对账记录表唯一业务ID
            premiumRemittance.setPremiumReconciliationBizId(premiumReconciliationBizId);
            //保费对账-汇款记录表唯一业务ID
            premiumRemittance.setPremiumRemittanceBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_PREMIUM_REMITTANCE.getCode()));
            //支付凭证
            List<String> paymentVoucherList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(dto.getPaymentVoucherDtoList())) {
                paymentVoucherList = dto.getPaymentVoucherDtoList().stream()
                        .filter(dto1 -> StringUtils.isNotBlank(dto1.getFileUrl()))
                        .map(ApiPremiumRemittanceFileDto::getFileUrl)
                        .collect(Collectors.toList());
            }
            premiumRemittance.setPaymentVoucher(!CollectionUtils.isEmpty(paymentVoucherList) ? String.join(";",paymentVoucherList) : "");
            //账户证明
            List<String> accountVerificationList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(dto.getAccountVerificationDtoList())) {
                accountVerificationList = dto.getAccountVerificationDtoList().stream()
                        .filter(dto1 -> StringUtils.isNotBlank(dto1.getFileUrl()))
                        .map(ApiPremiumRemittanceFileDto::getFileUrl)
                        .collect(Collectors.toList());
            }
            premiumRemittance.setAccountVerification(!CollectionUtils.isEmpty(accountVerificationList) ? String.join(";",accountVerificationList) : "");
            iPremiumRemittanceService.saveOrUpdate(premiumRemittance);

            //添加-保费对账汇款记录附件列表
            apiPremiumRemittanceFileService.addPremiumRemittanceFileList(dto.getApiPremiumRemittanceFileDtoList()
                    ,premiumRemittance.getPremiumRemittanceBizId());

        }
        return Result.success();
    }

    /**
     * 根据保费对账记录表唯一业务ID查询保费对账-汇款记录
     * @param premiumReconciliationBizId
     * @return
     */
    @Override
    public List<ApiPremiumRemittanceDto> apiPremiumRemittanceDtoList(String premiumReconciliationBizId) {
        List<PremiumRemittance> list = iPremiumRemittanceService.queryList(PremiumRemittanceDto.builder()
                .premiumReconciliationBizId(premiumReconciliationBizId).build());
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<ApiPremiumRemittanceDto> dtoList = list.stream().map(dto -> {
            ApiPremiumRemittanceDto remittanceDto = new ApiPremiumRemittanceDto();
            BeanUtils.copyProperties(dto,remittanceDto);
            //支付凭证列表
            ApiOssFileListRequest request = new ApiOssFileListRequest();
            if (StringUtils.isNotBlank(dto.getPaymentVoucher())) {
                List<String> fileKeyList = UrlPathExtractor.extractPaths(dto.getPaymentVoucher());
                request.setFileKeyList(fileKeyList);
                Result<List<ApiOssFileListResponse>> result = apiOssFileFeignClient.list(request);
                if (!CollectionUtils.isEmpty(result.getData())) {
                    List<ApiPremiumRemittanceFileDto> paymentVoucherDtoList = result.getData().stream().map(d -> {
                        ApiPremiumRemittanceFileDto fileDto = new ApiPremiumRemittanceFileDto();
                        fileDto.setFileName(d.getOriginalName());
                        fileDto.setFileUrl(d.getFileUrl());
                        fileDto.setFileType(d.getFileType());
                        return fileDto;
                    }).collect(Collectors.toList());
                    remittanceDto.setPaymentVoucherDtoList(paymentVoucherDtoList);
                }
            }
//            remittanceDto.setPaymentVoucherList(StringUtils.isNotBlank(dto.getPaymentVoucher()) ? Arrays.asList(dto.getPaymentVoucher().split(";").clone()) : new ArrayList<>());
            //账户证明列表
            ApiOssFileListRequest request1 = new ApiOssFileListRequest();
            if (StringUtils.isNotBlank(dto.getAccountVerification())) {
                List<String> fileKeyList = UrlPathExtractor.extractPaths(dto.getAccountVerification());
                request1.setFileKeyList(fileKeyList);
                Result<List<ApiOssFileListResponse>> result = apiOssFileFeignClient.list(request1);
                if (!CollectionUtils.isEmpty(result.getData())) {
                    List<ApiPremiumRemittanceFileDto> accountVerificationDtoList = result.getData().stream().map(d -> {
                        ApiPremiumRemittanceFileDto fileDto = new ApiPremiumRemittanceFileDto();
                        fileDto.setFileName(d.getOriginalName());
                        fileDto.setFileUrl(d.getFileUrl());
                        fileDto.setFileType(d.getFileType());
                        return fileDto;
                    }).collect(Collectors.toList());
                    remittanceDto.setAccountVerificationDtoList(accountVerificationDtoList);
                }
            }
//            remittanceDto.setAccountVerificationList(StringUtils.isNotBlank(dto.getAccountVerification()) ? Arrays.asList(dto.getAccountVerification().split(";").clone()) : new ArrayList<>());

            //其他资料列表
            List<ApiPremiumRemittanceFileDto> fileDtoList = apiPremiumRemittanceFileService.apiPremiumRemittanceFileDtoList(dto.getPremiumRemittanceBizId());
            remittanceDto.setApiPremiumRemittanceFileDtoList(fileDtoList);
            return remittanceDto;
        }).collect(Collectors.toList());
        return dtoList;
    }

    /**
     * 校验保费对账汇款记录信息是否存在
     * @param premiumRemittanceBizId
     * @return
     */
    @Override
    public Result<PremiumRemittance> checkPremiumRemittanceIsExist(String premiumRemittanceBizId) {
        PremiumRemittance premiumRemittance = iPremiumRemittanceService.queryOne(premiumRemittanceBizId);
        if (Objects.isNull(premiumRemittance)) {
            //数据不存在
            throw new BusinessException("保费对账汇款记录信息不存在");
        }
        return Result.success(premiumRemittance);
    }

    /**
     * 查询列表
     * @param premiumReconciliationBizIdList
     * @return
     */
    @Override
    public List<ApiPremiumRemittanceDto> list(List<String> premiumReconciliationBizIdList) {
        List<ApiPremiumRemittanceDto> apiPremiumRemittanceDtoList = new ArrayList<>();
        List<PremiumRemittance> list = iPremiumRemittanceService.queryList(PremiumRemittanceDto.builder().premiumReconciliationBizIdList(premiumReconciliationBizIdList).build());
        if (!CollectionUtils.isEmpty(list)) {
            apiPremiumRemittanceDtoList = list.stream().map(dto -> {
                ApiPremiumRemittanceDto remittanceDto = new ApiPremiumRemittanceDto();
                BeanUtils.copyProperties(dto,remittanceDto);
                return remittanceDto;
            }).collect(Collectors.toList());
        }
        return apiPremiumRemittanceDtoList;
    }
}
