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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.csf.feign.dto.appointment.ApiProductPlanAdditionalInfoDto;
import com.yd.csf.feign.dto.appointment.ApiProductPlanMainInfoDto;
import com.yd.csf.service.dto.*;
import com.yd.csf.service.model.AppointmentFile;
import com.yd.csf.service.model.Policy;
import com.yd.csf.service.model.PolicyAdditional;
import com.yd.csf.service.service.PolicyAdditionalService;
import com.yd.csf.service.service.PolicyPolicyholderService;
import com.yd.csf.service.service.PolicyService;
import com.yd.csf.service.dao.PolicyMapper;
import com.yd.csf.service.vo.PolicyVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Zhang Jianan
* @description 针对表【policy(保单表)】的数据库操作Service实现
* @createDate 2025-09-18 15:07:25
*/
@Service
public class PolicyServiceImpl extends ServiceImpl<PolicyMapper, Policy>
    implements PolicyService{

    @Resource
    private PolicyAdditionalService policyAdditionalService;

    @Override
    public QueryWrapper<Policy> getQueryWrapper(PolicyQueryRequest policyQueryRequest) {
        QueryWrapper<Policy> queryWrapper = new QueryWrapper<>();
        if (policyQueryRequest == null) {
            return queryWrapper;
        }
        String status = policyQueryRequest.getStatus();
        String policyNo = policyQueryRequest.getPolicyNo();
        String customerName = policyQueryRequest.getCustomerName();
        String customerBizId = policyQueryRequest.getCustomerBizId();
        String insurer = policyQueryRequest.getInsurer();
        String productName = policyQueryRequest.getProductName();
        String issueDateStart = policyQueryRequest.getIssueDateStart();
        String issueDateEnd = policyQueryRequest.getIssueDateEnd();

        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        queryWrapper.eq(StringUtils.isNotBlank(policyNo), "policy_no", policyNo);
        queryWrapper.eq(StringUtils.isNotBlank(customerName), "customer_name", customerName);
        queryWrapper.eq(StringUtils.isNotBlank(customerBizId), "customer_biz_id", customerBizId);
        queryWrapper.eq(StringUtils.isNotBlank(insurer), "insurer", insurer);
        queryWrapper.eq(StringUtils.isNotBlank(productName), "product_name", productName);
        queryWrapper.ge(StringUtils.isNotBlank(issueDateStart), "issue_date", issueDateStart);
        queryWrapper.le(StringUtils.isNotBlank(issueDateEnd), "issue_date", issueDateEnd);

        // 默认排序
        queryWrapper.orderByDesc("id");

        return queryWrapper;
    }

    @Override
    public Page<PolicyVO> getPolicyVOPage(Page<Policy> policyPage) {
        List<Policy> policyList = policyPage.getRecords();
        Page<PolicyVO> policyVOPage = new Page<>(policyPage.getCurrent(), policyPage.getSize(), policyPage.getTotal());
        if (CollUtil.isEmpty(policyList)) {
            return policyVOPage;
        }

        // 填充信息
        List<PolicyVO> policyVOList = policyList.stream().map(policy -> {
            PolicyVO policyVO = PolicyVO.objToVo(policy);
            return policyVO;
        }).collect(Collectors.toList());
        policyVOPage.setRecords(policyVOList);
        return policyVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePolicy(PolicyUpdateRequest policyUpdateRequest) {
        String policyBizId = policyUpdateRequest.getPolicyBizId();
        if (StringUtils.isBlank(policyBizId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR.getCode(), "policyBizId不能为空");
        }
        Policy policy = this.getOne(new QueryWrapper<Policy>().eq("policy_biz_id", policyBizId));
        if (policy == null) {
            throw new BusinessException(ResultCode.NULL_ERROR.getCode(), "保单不存在");
        }
        Date now = new Date();
        // 保单信息
        ApiProductPlanMainInfoDto apiProductPlanMainInfoDto = policyUpdateRequest.getApiProductPlanMainInfoDto();
        if (apiProductPlanMainInfoDto != null) {
            BeanUtils.copyProperties(apiProductPlanMainInfoDto, policy, "policyBizId", "id");
            policy.setPaymentPremium(apiProductPlanMainInfoDto.getEachIssuePremium());
            policy.setIsPrepaid(apiProductPlanMainInfoDto.getIsPrepay());
            policy.setUpdateTime(now);
            // 更新保单
            this.updateById(policy);
        }
        String policyNo = policy.getPolicyNo();

        // 先删除旧的附加险
        policyAdditionalService.remove(new QueryWrapper<PolicyAdditional>().eq("policy_biz_id", policyBizId));
        // 保单附加险列表
        List<ApiProductPlanAdditionalInfoDto> apiProductPlanAdditionalInfoDtoList = policyUpdateRequest.getApiProductPlanAdditionalInfoDtoList();
        if (CollUtil.isNotEmpty(apiProductPlanAdditionalInfoDtoList)) {
            // 转换为实体类
            List<PolicyAdditional> policyAdditionalList = apiProductPlanAdditionalInfoDtoList.stream().map(additionalDto -> {
                PolicyAdditional policyAdditional  = new PolicyAdditional();
                BeanUtils.copyProperties(additionalDto, policyAdditional);

                policyAdditional.setPolicyBizId(policyBizId);
                policyAdditional.setPolicyNo(policyNo);
                policyAdditional.setUpdateTime(now);
                policyAdditional.setCreateTime(now);
                return policyAdditional;
            }).collect(Collectors.toList());
            // 批量插入
            policyAdditionalService.saveBatch(policyAdditionalList);
        }

        policy.setUpdateTime(now);
        return true;
    }


    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public List<Policy> queryList(QueryPolicyDto dto) {
        List<Policy> list = baseMapper.selectList(new LambdaQueryWrapper<Policy>()
                .in(!CollectionUtils.isEmpty(dto.getPolicyNoList()),Policy::getPolicyNo,dto.getPolicyNoList())
        );
        return list;
    }

    @Override
    public List<QueryPolicyAndBrokerDto> queryPolicyBrokerList(String policyNo) {
        return baseMapper.queryPolicyBrokerList(policyNo);
    }
}





