package com.ningdatech.kqapi.zzsfw.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.kqapi.common.model.PageVo;
import com.ningdatech.kqapi.zzsfw.model.dto.KqZzsfwPolicyDTO;
import com.ningdatech.kqapi.zzsfw.model.entity.KqZzsfwPolicy;
import com.ningdatech.kqapi.zzsfw.model.vo.ZzsfwPolicyVO;
import com.ningdatech.kqapi.zzsfw.service.IKqZzsfwPolicyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * @Classname PolicyManage
 * @Description
 * @Date 2023/11/02 14:55
 * @Author PoffyZhang
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class PolicyManage {

    private final IKqZzsfwPolicyService policyService;


    public PageVo<ZzsfwPolicyVO> list(long pageNumber, long pageSize) {
        Page<KqZzsfwPolicy> page = Page.of(pageNumber,pageSize);
        Page<KqZzsfwPolicy> pageRes = policyService.page(page, Wrappers.lambdaQuery(KqZzsfwPolicy.class)
                .orderByAsc(KqZzsfwPolicy::getSort));

        if(CollUtil.isEmpty(pageRes.getRecords())){
            return PageVo.empty();
        }
        List<ZzsfwPolicyVO> res = pageRes.getRecords().stream()
                .map(p -> BeanUtil.copyProperties(p, ZzsfwPolicyVO.class))
                .collect(Collectors.toList());
        return PageVo.of(res,pageRes.getTotal());
    }

    public String save(KqZzsfwPolicyDTO dto) {
        if(Objects.isNull(dto)){
            return "保存失败 传入为空";
        }

        KqZzsfwPolicy entity = BeanUtil.copyProperties(dto, KqZzsfwPolicy.class);
        if(policyService.save(entity)){
            return "保存成功 :" + entity;
        }else{
            return "保存失败";
        }
    }

    public String removeAll() {
        policyService.remove(Wrappers.lambdaQuery(KqZzsfwPolicy.class));
        return "删除成功";
    }

    /**
     * 批量保存
     * @param dtos
     * @return
     */
    public String saveBatch(List<KqZzsfwPolicyDTO> dtos) {
        if(CollUtil.isEmpty(dtos)){
            return "保存失败 传入为空";
        }

        List<KqZzsfwPolicy> entitys = dtos.stream().map(d -> BeanUtil.copyProperties(d, KqZzsfwPolicy.class))
                .collect(Collectors.toList());
        if(policyService.saveBatch(entitys)){
                return "保存成功";
        }else{
            return "保存失败";
        }
    }
}
