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.controller.screen.dto.YangZhiQuXian;
import com.ruoyi.web.controller.screen.dto.ZhongQuXianDto;
import com.ruoyi.web.controller.screen.vo.ZhongZhiQuXianVo;
import com.ruoyi.web.domain.dto.villageTradition.VillageTraditionAddRequest;
import com.ruoyi.web.domain.dto.villageTradition.VillageTraditionEditRequest;
import com.ruoyi.web.domain.dto.villageTradition.VillageTraditionQueryRequest;
import com.ruoyi.web.domain.entity.VillageTradition;
import com.ruoyi.web.mapper.VillageTraditionMapper;
import com.ruoyi.web.service.VillageTraditionService;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 *
 */
@Service
public class VillageTraditionServiceImpl extends ServiceImpl<VillageTraditionMapper, VillageTradition>
        implements VillageTraditionService {
    @Autowired
    private VillageTraditionMapper villageTraditionMapper;

    @Override
    public Integer addVillageTradition(VillageTraditionAddRequest villageTraditionAddRequest) {
        if (villageTraditionAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            VillageTradition villageTradition = new VillageTradition();
            BeanUtil.copyProperties(villageTraditionAddRequest, villageTradition);
            //数据校验
            validVillageTradition(villageTradition, BusinessType.INSERT);

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

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

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

    @Override
    public void editVillageTradition(VillageTraditionEditRequest villageTraditionEditRequest) {
        // 判断是否存在
        Integer id = villageTraditionEditRequest.getId();
        VillageTradition oldVillageTradition = this.getById(id);
        if (oldVillageTradition == null) {
            throw new ServiceException("没有找到传统产业");
        }
        VillageTradition villageTradition = new VillageTradition();
        BeanUtil.copyProperties(villageTraditionEditRequest, villageTradition);
        villageTradition.setUpdateTime(new Date());

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


    /**
     * 校验传统产业
     *
     * @param villageTradition
     */
    public void validVillageTradition(VillageTradition villageTradition, BusinessType type) {
        if (ObjectUtil.isEmpty(villageTradition)) {
            throw new ServiceException("数据为空");
        }
        Integer id = villageTradition.getId();
        String category = villageTradition.getCategory();
        String name = villageTradition.getName();
        String location = villageTradition.getLocation();
        String area = villageTradition.getArea();
        String variety = villageTradition.getVariety();
        String promotion = villageTradition.getPromotion();

        // 添加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("位置不能为空");
        }
        if (StrUtil.isBlank(area)) {
            throw new ServiceException("种植面积或养殖规模不能为空");
        }
        if (StrUtil.isBlank(variety)) {
            throw new ServiceException("品种不能为空");
        }
    }


    @Override
    public VillageTradition getVillageTraditionById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        return this.getById(id);
    }

    @Override
    public Page<VillageTradition> getListVillageTraditionByPage(VillageTraditionQueryRequest villageTraditionQueryRequest) {
        long current = villageTraditionQueryRequest.getPageNum();
        long size = villageTraditionQueryRequest.getPageSize();
        return this.page(new Page<>(current, size),
                getQueryWrapper(villageTraditionQueryRequest));
    }

    @Override
    public QueryWrapper<VillageTradition> getQueryWrapper(VillageTraditionQueryRequest villageTraditionQueryRequest) {
        QueryWrapper<VillageTradition> queryWrapper = new QueryWrapper<>();
        if (villageTraditionQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        String category = villageTraditionQueryRequest.getCategory();
        String name = villageTraditionQueryRequest.getName();
        String sortField = villageTraditionQueryRequest.getSortField();
        String sortOrder = villageTraditionQueryRequest.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;
    }

    @Override
    public List<VillageTradition> zhongZhiPingZhong() {
        QueryWrapper<VillageTradition> wrapper = new QueryWrapper<>();
        wrapper.select("variety");
        wrapper.groupBy("variety");
        wrapper.eq("category",1);
        return this.list(wrapper);
    }

    @Override
    public List<ZhongQuXianDto> zhongZhiQuXian(ZhongZhiQuXianVo zhongZhiQuXianVo) {
        String pingZhongName = zhongZhiQuXianVo.getPingZhongName();
        return  villageTraditionMapper.zhongZhiQuXian();
    }

    @Override
    public List<YangZhiQuXian> yagnZhiQuXian() {
        QueryWrapper<VillageTradition> wrapper = new QueryWrapper<>();
        wrapper.select("variety");
        wrapper.groupBy("variety");
        wrapper.eq("category",2);
        List<VillageTradition> villageTraditions = this.list(wrapper);
        List<YangZhiQuXian> list = new ArrayList();
        for (VillageTradition villageTradition : villageTraditions) {
            YangZhiQuXian yangZhiQuXian = new YangZhiQuXian();
            yangZhiQuXian.setVariety(villageTradition.getVariety());
            yangZhiQuXian.setData(villageTraditionMapper.YangZhiQuXian(villageTradition.getVariety()));
            list.add(yangZhiQuXian);
        }

        return list;
    }
}




