package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
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.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.ethnicActivities.EthnicActivitiesAddRequest;
import com.ruoyi.web.domain.dto.ethnicActivities.EthnicActivitiesEditRequest;
import com.ruoyi.web.domain.dto.ethnicActivities.EthnicActivitiesQueryRequest;
import com.ruoyi.web.domain.entity.EthnicActivities;
import com.ruoyi.web.domain.vo.EthnicActivitiesVO;
import com.ruoyi.web.mapper.EthnicActivitiesMapper;
import com.ruoyi.web.service.EthnicActivitiesService;
import org.springframework.stereotype.Service;

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

/**
 *
 */
@Service
public class EthnicActivitiesServiceImpl extends ServiceImpl<EthnicActivitiesMapper, EthnicActivities>
        implements EthnicActivitiesService {
    @Override
    public Integer addEthnicActivities(EthnicActivitiesAddRequest ethnicActivitiesAddRequest) {
        if (ethnicActivitiesAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            EthnicActivities newEthnicActivities = new EthnicActivities();
            BeanUtil.copyProperties(ethnicActivitiesAddRequest, newEthnicActivities);
            newEthnicActivities.setStatus(0);
            // 将民族 List 转为 String
            newEthnicActivities.setEthnic(JSONUtil.toJsonStr(ethnicActivitiesAddRequest.getEthnic()));
            // 数据校验
            validEthnicActivities(newEthnicActivities, BusinessType.INSERT);

            // 保存到数据库
            this.save(newEthnicActivities);
            return newEthnicActivities.getId();
        } catch (Exception e) {
            log.error("添加民族团结活动数据失败", e);
            throw new ServiceException("添加民族团结活动数据失败");
        }
    }

    @Override
    public boolean deleteEthnicActivities(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<EthnicActivities> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

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

    @Override
    public void editEthnicActivities(EthnicActivitiesEditRequest ethnicActivitiesEditRequest) {
        // 判断是否存在
        Integer id = ethnicActivitiesEditRequest.getId();
        EthnicActivities oldEthnicActivities = this.getById(id);
        if (oldEthnicActivities == null) {
            throw new ServiceException("没有找到民族团结活动数据");
        }
        EthnicActivities newEthnicActivities = new EthnicActivities();
        BeanUtil.copyProperties(ethnicActivitiesEditRequest, newEthnicActivities);
        newEthnicActivities.setUpdateTime(new Date());
        // 将民族 List 转为 String
        newEthnicActivities.setEthnic(JSONUtil.toJsonStr(ethnicActivitiesEditRequest.getEthnic()));
        // 数据校验
        validEthnicActivities(newEthnicActivities, BusinessType.UPDATE);

        // 操作数据库
        boolean result = this.updateById(newEthnicActivities);
        if (!result) {
            throw new ServiceException("修改民族团结活动数据操作失败");
        }
    }

    /**
     * 完成
     * @param id
     * @return
     */
    @Override
    public boolean completeEthnicActivities(int id) {
        if (id <= 0) {
            throw new ServiceException("参数错误");
        }
        EthnicActivities ethnicActivities = this.getById(id);
        if (ethnicActivities == null){
            throw new ServiceException("未找到民族团结活动");
        }
        ethnicActivities.setStatus(1);
        return this.updateById(ethnicActivities);
    }

    /**
     * 校验数据
     *
     * @param ethnicActivities
     */
    public void validEthnicActivities(EthnicActivities ethnicActivities, BusinessType type) {
        if (ObjectUtil.isEmpty(ethnicActivities)) {
            throw new ServiceException("数据为空");
        }
        Integer id = ethnicActivities.getId();
        String name = ethnicActivities.getName();
        Date date = ethnicActivities.getDate();
        String location = ethnicActivities.getLocation();
        String category = ethnicActivities.getCategory();
        String ethnic = ethnicActivities.getEthnic();

        // 修改数据时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("活动名称不能为空");
        }
        if (ObjectUtil.isEmpty(date)) {
            throw new ServiceException("日期不能为空");
        }
        if (StrUtil.isEmpty(location)) {
            throw new ServiceException("地点不能为空");
        }
        if (StrUtil.isEmpty(category)) {
            throw new ServiceException("活动类别不能为空");
        }
        if (StrUtil.isBlank(ethnic)) {
            throw new ServiceException("参与民族不能为空");
        }
    }


    @Override
    public EthnicActivitiesVO getEthnicActivitiesById(int id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        EthnicActivities ethnicActivities = this.getById(id);
        return getEthnicActivitiesVO(ethnicActivities);
    }

    /**
     * 获取包装类
     *
     * @param ethnicActivities
     * @return
     */
    @Override
    public EthnicActivitiesVO getEthnicActivitiesVO(EthnicActivities ethnicActivities) {
        if (ObjectUtil.isEmpty(ethnicActivities)) {
            throw new ServiceException("请求参数不存在");
        }
        EthnicActivitiesVO ethnicActivitiesVO = new EthnicActivitiesVO();
        BeanUtils.copyProperties(ethnicActivities, ethnicActivitiesVO);
        return ethnicActivitiesVO;
    }


    @Override
    public Page<EthnicActivitiesVO> getListEthnicActivitiesByPage(EthnicActivitiesQueryRequest ethnicActivitiesQueryRequest) {
        QueryWrapper<EthnicActivities> queryWrapper = new QueryWrapper<>();
        Date startTime = ethnicActivitiesQueryRequest.getStartTime();
        Date endTime = ethnicActivitiesQueryRequest.getEndTime();
        String category = ethnicActivitiesQueryRequest.getCategory();
        List<String> ethnic = ethnicActivitiesQueryRequest.getEthnic();
        Integer status = ethnicActivitiesQueryRequest.getStatus();
        long pageNum = ethnicActivitiesQueryRequest.getPageNum();
        long pageSize = ethnicActivitiesQueryRequest.getPageSize();
        String sortField = ethnicActivitiesQueryRequest.getSortField();
        String sortOrder = ethnicActivitiesQueryRequest.getSortOrder();

        queryWrapper.eq(StrUtil.isNotEmpty(category), "category", category)
                .eq(ObjectUtil.isNotEmpty(status), "status", status)
                .orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);

        // 民族
        if (CollUtil.isNotEmpty(ethnic)) {
            for (String e : ethnic) {
                queryWrapper.like("ethnic", "\"" + e + "\"");
            }
        }

        // 日期范围查询（优先判断范围）
        if (startTime != null && endTime != null) {
            queryWrapper.between("date", startTime, endTime);
        } else if (startTime != null) {
            queryWrapper.ge("date", startTime); // >= 开始日期
        } else if (endTime != null) {
            queryWrapper.le("date", endTime);   // <= 结束日期
        }

        // 分页查询
        Page<EthnicActivities> page = this.page(new Page<>(pageNum, pageSize),
                queryWrapper);
        Page<EthnicActivitiesVO> ethnicActivitiesVOPage = new Page<>();
        BeanUtil.copyProperties(page, ethnicActivitiesVOPage, "records");
        List<EthnicActivitiesVO> voList = page.getRecords().stream()
                .map(this::getEthnicActivitiesVO)
                .collect(Collectors.toList());
        ethnicActivitiesVOPage.setRecords(voList);
        return ethnicActivitiesVOPage;
    }
}




