package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.domain.dto.localPolicy.LocalPolicyAddRequest;
import com.ruoyi.web.domain.dto.localPolicy.LocalPolicyEditRequest;
import com.ruoyi.web.domain.dto.localPolicy.LocalPolicyQueryRequest;
import com.ruoyi.web.domain.entity.LocalPolicy;
import com.ruoyi.web.mapper.LocalPolicyMapper;
import com.ruoyi.web.service.LocalPolicyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 当地政策服务
 */
@Service
@Slf4j
public class LocalPolicyServiceImpl extends ServiceImpl<LocalPolicyMapper, LocalPolicy>
        implements LocalPolicyService {

    /**
     * 添加
     *
     * @param localPolicyAddRequest
     * @return
     */
    @Override
    public Integer addLocalPolicy(LocalPolicyAddRequest localPolicyAddRequest) {
        if (localPolicyAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            LocalPolicy localPolicy = new LocalPolicy();
            BeanUtil.copyProperties(localPolicyAddRequest, localPolicy);
            // 数据校验
            validLocalPolicy(localPolicy, BusinessType.INSERT);
            // 保存到数据库
            this.save(localPolicy);
            return localPolicy.getId();
        } catch (Exception e) {
            log.error("添加政策失败", e);
            throw new ServiceException("添加政策失败");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteLocalPolicy(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<LocalPolicy> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);

    }

    /**
     * 编辑
     *
     * @param localPolicyEditRequest
     */
    @Override
    public void editLocalPolicy(LocalPolicyEditRequest localPolicyEditRequest) {
        // 判断是否存在
        Integer id = localPolicyEditRequest.getId();
        LocalPolicy oldLocalPolicy = this.getById(id);
        if (oldLocalPolicy == null) {
            throw new ServiceException("没有找到当地政策");
        }
        LocalPolicy localPolicy = new LocalPolicy();
        BeanUtil.copyProperties(localPolicyEditRequest, localPolicy);
        localPolicy.setUpdateTime(new Date());
        // 数据校验
        validLocalPolicy(localPolicy, BusinessType.UPDATE);

        // 操作数据库
        boolean result = this.updateById(localPolicy);
        if (!result) {
            throw new ServiceException("修改当地政策操作失败");
        }
    }

    /**
     * 校验当地政策
     *
     * @param localPolicy
     */
    public void validLocalPolicy(LocalPolicy localPolicy, BusinessType type) {
        if (ObjectUtil.isEmpty(localPolicy)) {
            throw new ServiceException("数据为空");
        }

        // 从对象中取值
        Integer id = localPolicy.getId();
        String name = localPolicy.getName();
        String label = localPolicy.getLabel();
        String file = localPolicy.getFile();

        // 修改数据时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("当地政策名称不能为空");
        }
        if (StrUtil.isBlank(file)) {
            throw new ServiceException("政策文件不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public LocalPolicy getLocalPolicyById(int id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        return this.getById(id);
    }

    /**
     * 分页查询
     *
     * @param localPolicyQueryRequest
     * @return
     */
    @Override
    public Page<LocalPolicy> getListLocalPolicyByPage(LocalPolicyQueryRequest localPolicyQueryRequest) {
        QueryWrapper<LocalPolicy> queryWrapper = new QueryWrapper<>();
        String keyword = localPolicyQueryRequest.getKeyword();
        long current = localPolicyQueryRequest.getPageNum();
        long pageSize = localPolicyQueryRequest.getPageSize();
        String sortField = localPolicyQueryRequest.getSortField();
        String sortOrder = localPolicyQueryRequest.getSortOrder();

        // 如果关键字不为空，添加模糊查询条件
        if (StrUtil.isNotBlank(keyword)) {
            // 构造条件：政策名称 or 政策描述
            queryWrapper.like("name", keyword)
                    .or()
                    .like("label", keyword);
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);

        // 分页查询
        return this.page(new Page<>(current, pageSize),
                queryWrapper);
    }
}




