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.Industry.IndustryDataAddRequest;
import com.ruoyi.web.domain.dto.Industry.IndustryDataEditRequest;
import com.ruoyi.web.domain.dto.Industry.IndustryDataQueryRequest;
import com.ruoyi.web.domain.entity.IndustryData;
import com.ruoyi.web.domain.vo.TimeAndValueVo.TimeAndValueVo;
import com.ruoyi.web.mapper.IndustryDataMapper;
import com.ruoyi.web.service.IndustryDataService;
import org.springframework.beans.factory.annotation.Autowired;
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 IndustryDataServiceImpl extends ServiceImpl<IndustryDataMapper, IndustryData>
        implements IndustryDataService {

    @Autowired
    private IndustryDataMapper industryDataMapper;

    @Override
    public Integer addIndustryData(IndustryDataAddRequest industryDataAddRequest) {
        if (industryDataAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            IndustryData newIndustryData = new IndustryData();
            BeanUtil.copyProperties(industryDataAddRequest, newIndustryData);
            // 数据校验
            validIndustryData(newIndustryData, BusinessType.INSERT);
            // 保存到数据库
            this.save(newIndustryData);
            return newIndustryData.getId();
        } catch (Exception e) {
            log.error("添加产业失败", e);
            throw new ServiceException("添加产业失败");
        }
    }

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

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

    @Override
    public void editIndustryData(IndustryDataEditRequest industryDataEditRequest) {
        // 判断是否存在
        Integer id = industryDataEditRequest.getId();
        IndustryData oldIndustryData = this.getById(id);
        if (oldIndustryData == null) {
            throw new ServiceException("没有找到产业数据");
        }
        IndustryData newIndustryData = new IndustryData();
        BeanUtil.copyProperties(industryDataEditRequest, newIndustryData);
        newIndustryData.setUpdateTime(new Date());
        // 数据校验
        validIndustryData(newIndustryData, BusinessType.UPDATE);

        // 操作数据库
        boolean result = this.updateById(newIndustryData);
        if (!result) {
            throw new ServiceException("修改产业数据操作失败");
        }
    }

    /**
     * 校验产业数据
     *
     * @param industryData
     */
    public void validIndustryData(IndustryData industryData, BusinessType type) {
        if (ObjectUtil.isEmpty(industryData)) {
            throw new ServiceException("数据为空");
        }

        Integer id = industryData.getId();
        String year = industryData.getYear();
        Integer category = industryData.getCategory();
        String value = industryData.getValue();

        // 修改数据时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(year)) {
            throw new ServiceException("年份不能为空");
        }
        if (ObjectUtil.isEmpty(category)) {
            throw new ServiceException("产业类别不能为空");
        }
        if (StrUtil.isBlank(value)) {
            throw new ServiceException("产值不能为空");
        }
    }


    @Override
    public IndustryData getIndustryDataById(int id) {
        if (ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        return this.getById(id);
    }

    @Override
    public Page<IndustryData> getListIndustryDataByPage(IndustryDataQueryRequest industryDataQueryRequest) {
        QueryWrapper<IndustryData> queryWrapper = new QueryWrapper<>();
        Integer id = industryDataQueryRequest.getId();
        String year = industryDataQueryRequest.getYear();
        String category = industryDataQueryRequest.getCategory();
        long pageNum = industryDataQueryRequest.getPageNum();
        long pageSize = industryDataQueryRequest.getPageSize();
        String sortField = industryDataQueryRequest.getSortField();
        String sortOrder = industryDataQueryRequest.getSortOrder();

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

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

    @Override
    public List<TimeAndValueVo> listGroupByYear() {
        return  industryDataMapper.listGroupByYear();
    }

    @Override
    public TimeAndValueVo listGroupByYearTwo(int year) {
        return  industryDataMapper.listGroupByYearTwo(year);
    }

    @Override
    public List<TimeAndValueVo> listLaoWu() {
        return industryDataMapper.listLaoWu();
    }
}




