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.productionData.ProductionDataAddRequest;
import com.ruoyi.web.domain.dto.villageSpecial.VillageSpecialAddRequest;
import com.ruoyi.web.domain.dto.villageSpecial.VillageSpecialEditRequest;
import com.ruoyi.web.domain.dto.villageSpecial.VillageSpecialQueryRequest;
import com.ruoyi.web.domain.entity.ProductionData;
import com.ruoyi.web.domain.entity.VillageSpecial;
import com.ruoyi.web.domain.vo.VillageSpecial.BaoAnVO;
import com.ruoyi.web.domain.vo.VillageSpecial.BaseVillageSpecialVO;
import com.ruoyi.web.domain.vo.VillageSpecial.FarmHouseVO;
import com.ruoyi.web.domain.vo.VillageSpecial.SpecialVOFactory;
import com.ruoyi.web.mapper.VillageSpecialMapper;
import com.ruoyi.web.service.ProductionDataService;
import com.ruoyi.web.service.VillageSpecialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class VillageSpecialServiceImpl extends ServiceImpl<VillageSpecialMapper, VillageSpecial>
        implements VillageSpecialService {

    @Autowired
    private ProductionDataService productionDataService;

    @Override
    public Integer addVillageSpecial(VillageSpecialAddRequest villageSpecialAddRequest) {
        if (villageSpecialAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            VillageSpecial villageSpecial = new VillageSpecial();
            BeanUtil.copyProperties(villageSpecialAddRequest, villageSpecial);
            //数据校验
            validVillageSpecial(villageSpecial, BusinessType.INSERT);

            List<ProductionDataAddRequest> productionDataAddList = villageSpecialAddRequest.getList();
            List<ProductionData> productionDataList = new ArrayList<>();
            if (productionDataAddList != null && !productionDataAddList.isEmpty()) {
                // 遍历列表
                for (ProductionDataAddRequest addRequest : productionDataAddList) {
                    ProductionData productionData = new ProductionData();
                    BeanUtil.copyProperties(addRequest, productionData);
                    productionDataList.add(productionData);
                }
            }

            // 处理产品数据
            if (!productionDataList.isEmpty()) {
                // 设置创建时间
                Date now = new Date();
                for (ProductionData productionData : productionDataList) {
                    productionData.setCreateTime(now);
                }

                // 批量保存产品数据
                boolean saveResult = productionDataService.saveBatch(productionDataList);
                if (!saveResult) {
                    throw new ServiceException("保存产品数据失败");
                }

                // 获取保存后的产品ID列表
                List<Integer> idList = productionDataList.stream()
                        .map(ProductionData::getId)
                        .filter(id -> ObjectUtil.isNotEmpty(id))
                        .collect(Collectors.toList());

                // 如果ID列表为空或部分为空，可能是因为ID没有回填，通过其他方式查询
                if (idList.size() != productionDataList.size()) {
                    // 根据产品名称和创建时间查询刚插入的记录
                    List<String> nameList = productionDataList.stream()
                            .map(ProductionData::getName)
                            .collect(Collectors.toList());

                    QueryWrapper<ProductionData> queryWrapper = new QueryWrapper<>();
                    queryWrapper.in("name", nameList);
                    queryWrapper.ge("create_time", now);

                    List<ProductionData> savedList = productionDataService.list(queryWrapper);
                    idList = savedList.stream()
                            .map(ProductionData::getId)
                            .collect(Collectors.toList());
                }

                // 将ID列表转换为逗号分隔的字符串
                String ids = StringUtils.join(idList, ",");

                // 设置到villageSpecial的ids字段
                villageSpecial.setIds(ids);
            }

            // 保存到数据库
            this.save(villageSpecial);
            return villageSpecial.getId();
        } catch (Exception e) {
            log.error("添加特色产业失败", e);
            throw new ServiceException("添加特色产业失败");
        }
    }

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

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

    @Override
    public void editVillageSpecial(VillageSpecialEditRequest villageSpecialEditRequest) {
        // 判断是否存在
        Integer id = villageSpecialEditRequest.getId();
        VillageSpecial oldVillageSpecial = this.getById(id);
        if (oldVillageSpecial == null) {
            throw new ServiceException("没有找到特色产业");
        }
        VillageSpecial villageSpecial = new VillageSpecial();
        BeanUtil.copyProperties(villageSpecialEditRequest, villageSpecial);
        villageSpecial.setUpdateTime(new Date());

        // 数据校验
        validVillageSpecial(villageSpecial, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(villageSpecial);
        if (!result) {
            throw new ServiceException("修改特色产业操作失败");
        }
    }


    /**
     * 校验特色产业
     *
     * @param villageSpecial
     */
    public void validVillageSpecial(VillageSpecial villageSpecial, BusinessType type) {
        if (ObjectUtil.isEmpty(villageSpecial)) {
            throw new ServiceException("数据为空");
        }
        Integer id = villageSpecial.getId();
        String category = villageSpecial.getCategory();
        String name = villageSpecial.getName();
        String location = villageSpecial.getLocation();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(category)) {
            throw new ServiceException("产业类别不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("名称不能为空");
        }
        if (StrUtil.isBlank(location)) {
            throw new ServiceException("位置不能为空");
        }
    }


    @Override
    public BaseVillageSpecialVO getVillageSpecialById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        VillageSpecial villageSpecial = this.getById(id);
        if (villageSpecial == null) {
            throw new ServiceException("未找到特色产业信息");
        }
        return getBaseVillageSpecialVO(villageSpecial);
    }

    @Override
    public BaseVillageSpecialVO getBaseVillageSpecialVO(VillageSpecial villageSpecial) {
        BaseVillageSpecialVO villageSpecialVO = SpecialVOFactory.convert(villageSpecial);

        // 判断是保安腰刀产业或农家乐产业，需要填充产品数量
        String category = villageSpecialVO.getCategory();
        if ("0".equals(category) || "1".equals(category)) {
            String ids = villageSpecial.getIds();
            if (StringUtils.isNotBlank(ids)) {
                // 分割ID字符串为List<Integer>
                List<Integer> idList = Arrays.stream(ids.split(","))
                        .map(String::trim)
                        .filter(StrUtil::isNotBlank)
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());

                if (!idList.isEmpty()) {
                    // 查询productData表获取产品数量
                    QueryWrapper<ProductionData> queryWrapper = new QueryWrapper<>();
                    queryWrapper.in("id", idList);
                    long count = productionDataService.count(queryWrapper);

                    // 填充产品数量到VO
                    if ("0".equals(category)) {
                        ((BaoAnVO) villageSpecialVO).setProduceNum((int) count);
                    } else {
                        ((FarmHouseVO) villageSpecialVO).setVegetable((int) count);
                    }
                }
            }
        }
        return villageSpecialVO;
    }


    @Override
    public Page<BaseVillageSpecialVO> getListVillageSpecialByPage(VillageSpecialQueryRequest villageSpecialQueryRequest) {
        long current = villageSpecialQueryRequest.getPageNum();
        long size = villageSpecialQueryRequest.getPageSize();
        Page<VillageSpecial> villageSpecialPage = this.page(new Page<>(current, size),
                getQueryWrapper(villageSpecialQueryRequest));

        // 创建新的VO分页对象
        Page<BaseVillageSpecialVO> voPage = new Page<>(current, size, villageSpecialPage.getTotal());

        // 将每个实体转换为VO
        List<BaseVillageSpecialVO> voList = villageSpecialPage.getRecords().stream()
                .map(this::getBaseVillageSpecialVO)
                .collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }


    @Override
    public QueryWrapper<VillageSpecial> getQueryWrapper(VillageSpecialQueryRequest villageSpecialQueryRequest) {
        QueryWrapper<VillageSpecial> queryWrapper = new QueryWrapper<>();
        if (villageSpecialQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        String category = villageSpecialQueryRequest.getCategory();
        String name = villageSpecialQueryRequest.getName();
        String sortField = villageSpecialQueryRequest.getSortField();
        String sortOrder = villageSpecialQueryRequest.getSortOrder();

        queryWrapper.eq(StringUtils.isNotBlank(category), "category", category);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    /**
     * 通过id获取 产品/菜品 列表
     * @param id 特色产业id
     * @return
     */
    @Override
    public List<ProductionData> getProductDataList(int id) {
        if(ObjectUtil.isEmpty(id)){
            throw new ServiceException("id为空或id异常");
        }
        VillageSpecial villageSpecial = this.getById(id);
        if (villageSpecial == null) {
            throw new ServiceException("未找到特色产业");
        }
        String ids = villageSpecial.getIds();
        List<ProductionData> productionDataList = null;
        if (StringUtils.isNotBlank(ids)) {
            // 分割ID字符串为List<Integer>
            List<Integer> idList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(StrUtil::isNotBlank)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            if (!idList.isEmpty()) {
                // 查询productData表获取产品数量
                QueryWrapper<ProductionData> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("id", idList);
                productionDataList = productionDataService.list(queryWrapper);
            }
        }
        return productionDataList;
    }
}




