package com.ylx.servicecategory.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.StringUtils;
import com.ylx.project.domain.Project;
import com.ylx.project.domain.vo.ProjectBaseVo;
import com.ylx.project.enums.ProjectStatusEnum;
import com.ylx.project.mapper.ProjectMapper;
import com.ylx.servicecategory.domain.ServiceCategory;
import com.ylx.servicecategory.domain.vo.ClientServiceCategoryVO;
import com.ylx.servicecategory.mapper.ServiceCategoryMapper;
import com.ylx.servicecategory.service.ServiceCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务类目服务实现类
 */
@Service
public class ServiceCategoryServiceImpl extends ServiceImpl<ServiceCategoryMapper, ServiceCategory> implements ServiceCategoryService {

    @Autowired
    private ProjectMapper projectMapper;
    private static final int ONLINE = 1;
    private static final int NOT_DELETE = 0;
    private static final int IS_DISPLAY = 1;


    /**
     * H5查询首页服务类目
     *
     * @return List<ServiceCategory> H5首页服务类目列表
     */
    @Override
    public List<ServiceCategory> listH5ServiceCategory() {
        LambdaQueryWrapper<ServiceCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceCategory::getIsHomeDisplay, 1)
                .eq(ServiceCategory::getIsOnline, 1)
                .orderByAsc(ServiceCategory::getSort)
                .orderByAsc(ServiceCategory::getId);
        return baseMapper.selectH5ServiceCategoryList(queryWrapper);
    }

    /**
     * 根据主键ID查询服务类目详情
     *
     * @param id 服务类目ID
     * @return 服务类目详情
     */
    @Override
    public ServiceCategory getServiceCategoryDetail(Long id) {
        checkIdParam(id);

        ServiceCategory serviceCategory = this.baseMapper.selectServiceCategoryById(id);
        if (serviceCategory == null) {
            throw new ServiceException("服务类目不存在");
        }
        return serviceCategory;
    }

    /**
     * 分页查询服务类目
     *
     * @param page            分页参数
     * @param serviceCategory 查询条件
     * @return Page<ServiceCategory> 服务类目分页数据
     */
    @Override
    public Page<ServiceCategory> pageServiceCategory(Page<ServiceCategory> page, ServiceCategory serviceCategory) {
        Page<ServiceCategory> pageParam = page == null ? new Page<>(1, 10) : page;
        LambdaQueryWrapper<ServiceCategory> queryWrapper = new LambdaQueryWrapper<>();

        if (serviceCategory != null) {
            queryWrapper.like(StringUtils.isNotBlank(serviceCategory.getName()), ServiceCategory::getName, serviceCategory.getName())
                    .eq(serviceCategory.getIsHomeDisplay() != null, ServiceCategory::getIsHomeDisplay, serviceCategory.getIsHomeDisplay())
                    .eq(serviceCategory.getIsOnline() != null, ServiceCategory::getIsOnline, serviceCategory.getIsOnline());
        }
        queryWrapper.orderByAsc(ServiceCategory::getSort).orderByAsc(ServiceCategory::getId);
        return this.baseMapper.selectServiceCategoryPage(pageParam, queryWrapper);
    }

    /**
     * 新增服务类目
     *
     * @param serviceCategory 服务类目
     * @return Long 新增后的服务类目ID
     */
    @Override
    public Integer addServiceCategory(ServiceCategory serviceCategory) {
        checkAddParam(serviceCategory);
        //检查服务类目名称是否重复
        LambdaQueryWrapper<ServiceCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceCategory::getName, serviceCategory.getName());
        ServiceCategory dbServiceCategory = this.baseMapper.selectOne(queryWrapper);
        if (dbServiceCategory != null) {
            throw new ServiceException("服务类目名称已存在");
        }

        LocalDateTime now = LocalDateTime.now();
        serviceCategory.setId(null);
        serviceCategory.setCreateTime(now);
        serviceCategory.setUpdateTime(now);
        serviceCategory.setIsDelete(0);

        int insertResult = this.baseMapper.insertServiceCategory(serviceCategory);
        if (insertResult <= 0) {
            throw new ServiceException("新增服务类目失败");
        }
        return serviceCategory.getId();
    }

    /**
     * 修改服务类目
     *
     * @param serviceCategory 服务类目
     * @return 是否修改成功
     */
    @Override
    public Boolean updateServiceCategory(ServiceCategory serviceCategory) {
        checkUpdateParam(serviceCategory);

        ServiceCategory dbServiceCategory = this.baseMapper.selectById(serviceCategory.getId());
        if (dbServiceCategory == null) {
            throw new ServiceException("服务类目不存在");
        }

        serviceCategory.setUpdateTime(LocalDateTime.now());
        int updateResult = this.baseMapper.updateServiceCategoryById(serviceCategory);
        if (updateResult <= 0) {
            throw new ServiceException("修改服务类目失败");
        }
        return true;
    }

    /**
     * 删除服务类目
     *
     * @param id 服务类目ID
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteServiceCategory(Long id) {
        checkIdParam(id);

        ServiceCategory dbServiceCategory = this.baseMapper.selectById(id);
        if (dbServiceCategory == null) {
            throw new ServiceException("服务类目不存在");
        }
        //检查当前服务类目下是否有项目
        LambdaQueryWrapper<Project> projectQueryWrapper = new LambdaQueryWrapper<>();
        projectQueryWrapper.eq(Project::getType, id);
        List<Project> projectList = projectMapper.selectList(projectQueryWrapper);
        if (!projectList.isEmpty()) {
            throw new ServiceException("服务类目下有项目，不能删除");
        }

        int deleteResult = this.baseMapper.deleteServiceCategoryById(id);
        if (deleteResult <= 0) {
            throw new ServiceException("删除服务类目失败");
        }
        return true;
    }

    @Override
    public Page<ClientServiceCategoryVO> page(Page<ServiceCategory> page) {
        LambdaQueryWrapper<ServiceCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ServiceCategory::getIsDelete, NOT_DELETE)
                .eq(ServiceCategory::getIsOnline, ONLINE)
                .eq(ServiceCategory::getIsHomeDisplay, IS_DISPLAY)
                .orderByDesc(ServiceCategory::getSort);

        Page<ServiceCategory> serviceCategoryrPage = this.baseMapper.selectPage(page, wrapper);
        Page<ClientServiceCategoryVO> pageData = new Page<>(
                serviceCategoryrPage.getCurrent(),
                serviceCategoryrPage.getSize(),
                serviceCategoryrPage.getTotal()
        );

        if (CollectionUtil.isNotEmpty(serviceCategoryrPage.getRecords())) {
            List<ClientServiceCategoryVO> voList = serviceCategoryrPage.getRecords().stream()
                    .map(ClientServiceCategoryVO::new)
                    .collect(Collectors.toList());
            pageData.setRecords(voList);
        }

        return pageData;
    }

    @Override
    public List<ClientServiceCategoryVO> listServiceCategory() {
        LambdaQueryWrapper<ServiceCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ServiceCategory::getIsDelete, NOT_DELETE)
                .eq(ServiceCategory::getIsOnline, ONLINE)
                .eq(ServiceCategory::getIsHomeDisplay, IS_DISPLAY)
                .orderByDesc(ServiceCategory::getSort);

        List<ServiceCategory> serviceCategoryList = this.baseMapper.selectList(wrapper);

        return BeanUtil.copyToList(serviceCategoryList, ClientServiceCategoryVO.class);
    }

    private void checkAddParam(ServiceCategory serviceCategory) {
        checkRequiredParam(serviceCategory);
    }

    private void checkUpdateParam(ServiceCategory serviceCategory) {
        checkRequiredParam(serviceCategory);
        if (serviceCategory.getId() == null) {
            throw new ServiceException("服务类目ID不能为空");
        }
    }

    private void checkIdParam(Long id) {
        if (id == null) {
            throw new ServiceException("服务类目ID不能为空");
        }
    }

    /**
     * 校验服务类目参数是否为空
     *
     * @param serviceCategory 服务类目
     */
    private void checkRequiredParam(ServiceCategory serviceCategory) {
        if (serviceCategory == null) {
            throw new ServiceException("服务类目不能为空");
        }
        if (StringUtils.isBlank(serviceCategory.getName())) {
            throw new ServiceException("服务名称不能为空");
        }
        //图表URL不能为空
        if (StringUtils.isBlank(serviceCategory.getIcon())) {
            throw new ServiceException("图标不能为空");
        }
        if (serviceCategory.getSort() == null) {
            throw new ServiceException("序号不能为空");
        }
        if (serviceCategory.getSort() < 0) {
            throw new ServiceException("序号不能小于0");
        }

        serviceCategory.setName(serviceCategory.getName().trim());
        serviceCategory.setIcon(serviceCategory.getIcon().trim());
        serviceCategory.setIsHomeDisplay(normalizeSwitchValue(serviceCategory.getIsHomeDisplay(), "首页展示"));
        serviceCategory.setIsOnline(normalizeSwitchValue(serviceCategory.getIsOnline(), "上架"));
    }

    private Integer normalizeSwitchValue(Integer value, String fieldName) {
        if (value == null) {
            return 0;
        }
        if (value == 0 || value == 1) {
            return value;
        }
        throw new ServiceException(fieldName + "状态值不正确");
    }
}
