package com.ylx.massage.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.core.domain.model.LoginUser;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.DateUtils;
import com.ylx.common.utils.StringUtils;
import com.ylx.common.utils.bean.BeanUtils;
import com.ylx.home.category.domain.dto.ProjectRecommendDTO;
import com.ylx.massage.domain.dto.MaProjectAuditQueryDTO;
import com.ylx.massage.domain.dto.MaProjectAuditSubmitDTO;
import com.ylx.massage.domain.dto.MaProjectUpdateEnableDTO;
import com.ylx.home.category.domain.dto.MerchantsDto;
import com.ylx.massage.domain.vo.MaProjectAuditListVO;
import com.ylx.massage.domain.vo.MaProjectListVo;
import com.ylx.massage.domain.vo.MaProjectOpenServiceVO;
import com.ylx.massage.domain.vo.MaProjectSaveVo;
import com.ylx.home.category.domain.vo.MerchantsVo;
import com.ylx.home.category.domain.vo.ProjectRecommendVo;
import com.ylx.massage.mapper.MaProjectMapper;
import com.ylx.project.domain.bookMerchant.dto.BookMerchantDTO;
import com.ylx.project.domain.bookMerchant.vo.BookMerchantVO;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import com.ylx.massage.domain.MaProject;
import com.ylx.massage.service.IMaProjectService;

import javax.annotation.Resource;

/**
 * 服务项目Service业务层处理
 *
 * @author ylx
 * @date 2024-03-20
 */
@Service
public class MaProjectServiceImpl extends ServiceImpl<MaProjectMapper, MaProject> implements IMaProjectService {
    @Resource
    private MaProjectMapper maProjectMapper;

    /**
     * 查询服务项目
     *
     * @param id 服务项目主键
     * @return 服务项目
     */
    @Override
    public MaProjectListVo selectMaProjectById(Long id) {
        MaProject maProject = maProjectMapper.selectMaProjectById(id);
        MaProjectListVo vo = new MaProjectListVo();
        BeanUtils.copyProperties(maProject, vo);
        vo.setProjectIsEnable(maProject.getProjectIsEnable() == 1 ? "启用" : "停止");
        return vo;
    }

    /**
     * 查询服务项目列表
     *
     * @param maProject 服务项目
     * @return 服务项目
     */
    @Override
    public List<MaProjectListVo> selectMaProjectList(MaProject maProject) {
        ArrayList<MaProjectListVo> vos = Lists.newArrayList();
        List<MaProject> maProjects = maProjectMapper.selectMaProjectList(maProject);
        if (maProjects.isEmpty()) {
            return vos;
        }
        maProjects.forEach(project -> {
            MaProjectListVo vo = new MaProjectListVo();
            BeanUtils.copyProperties(project, vo);
            vo.setProjectIsEnable(project.getProjectIsEnable() == 1 ? "启用" : "停止");
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 查询技能审核列表
     *
     * @param page 分页参数
     * @param dto  查询条件
     * @return 技能审核分页列表
     */
    @Override
    public Page<MaProjectAuditListVO> selectProjectAuditList(Page<MaProjectAuditListVO> page, MaProjectAuditQueryDTO dto) {
        if (dto != null) {
            checkEnumValue(dto.getAuditStatus(), "技能审核状态", 0, 1, 2);
            checkEnumValue(dto.getAuditStatusGroup(), "审核页签", 0, 1);
            checkEnumValue(dto.getMerchantSex(), "性别", 0, 1);
            checkEnumValue(dto.getTechType(), "用户类型", 0, 1);
        }
        Page<MaProjectAuditListVO> pageParam = page == null ? new Page<>(1, 10) : page;
        return maProjectMapper.selectProjectAuditList(pageParam, dto);
    }

    /**
     * 查询商户申请开通的项目列表
     *
     * @param merchantId 商户ID
     * @return List<MaProjectOpenServiceVO> 商户申请开通项目列表
     */
    @Override
    public List<MaProjectOpenServiceVO> selectMerchantOpenProjectList(Long merchantId) {
        if (merchantId == null || merchantId <= 0) {
            throw new ServiceException("商户ID不能为空");
        }
        return maProjectMapper.selectMerchantOpenProjectList(merchantId);
    }

    /**
     * 审核商户申请开通的项目
     *
     * @param projectAuditId 技能审核记录ID
     * @param dto            审核提交参数
     * @param loginUser      当前登录用户
     * @return int 影响行数
     */
    @Override
    public int submitProjectAudit(Long projectAuditId, MaProjectAuditSubmitDTO dto, LoginUser loginUser) {
        if (projectAuditId == null || projectAuditId <= 0) {
            throw new ServiceException("技能审核记录ID不能为空");
        }
        if (dto == null) {
            throw new ServiceException("审核参数不能为空");
        }
        checkEnumValue(dto.getAuditStatus(), "审核状态", 1, 2);
        if (Integer.valueOf(2).equals(dto.getAuditStatus()) && StringUtils.isBlank(dto.getAuditRemark())) {
            throw new ServiceException("审核驳回时审核备注不能为空");
        }

        MaProject exists = maProjectMapper.selectProjectAuditById(projectAuditId);
        if (exists == null) {
            throw new ServiceException("技能审核记录不存在或已删除");
        }
        if (!Integer.valueOf(0).equals(exists.getAuditStatus())) {
            throw new ServiceException("当前项目不是待审核状态，不能重复审核");
        }

        MaProject maProject = new MaProject();
        maProject.setId(projectAuditId);
        maProject.setAuditStatus(dto.getAuditStatus());
        maProject.setReason(dto.getAuditRemark());
        maProject.setProjectIsEnable(Integer.valueOf(1).equals(dto.getAuditStatus()) ? 1 : 0);
        maProject.setApproveTime(DateUtils.getNowDate());
        maProject.setUpdateTime(DateUtils.getNowDate());
        if (loginUser != null && loginUser.getUser() != null) {
            maProject.setUpdateBy(loginUser.getUser().getUserId());
        }

        int rows = maProjectMapper.submitProjectAudit(maProject);
        if (rows <= 0) {
            throw new ServiceException("审核失败，当前项目状态已变更");
        }
        return rows;
    }


    @Override
    public int updateProjectEnable(MaProjectUpdateEnableDTO dto) {
        if (dto == null) {
            throw new ServiceException("上下架参数不能为空");
        }
        checkRequiredPositive(dto.getMerchantId(), "商户ID");
        checkRequiredPositive(dto.getProjectId(), "项目ID");
        if (dto.getProjectIsEnable() == null) {
            throw new ServiceException("上下架状态不能为空");
        }
        checkEnumValue(dto.getProjectIsEnable(), "上下架状态", 0, 1);

        LambdaUpdateWrapper<MaProject> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MaProject::getMerchantId, dto.getMerchantId())
                .eq(MaProject::getProjectId, dto.getProjectId())
                .eq(MaProject::getIsDelete, 0)
                .eq(MaProject::getAuditStatus, 1)
                .set(MaProject::getProjectIsEnable, dto.getProjectIsEnable())
                .set(MaProject::getUpdateTime, DateUtils.getNowDate());

        int rows = maProjectMapper.update(null, updateWrapper);
        if (rows <= 0) {
            throw new ServiceException("商户项目不存在或未审核通过");
        }
        return rows;
    }

    /**
     * 新增服务项目
     *
     * @param
     * @return 结果
     */
    @Override
    public int insertMaProject(MaProjectSaveVo maProjectVo, LoginUser loginUser) {
        MaProject maProject = new MaProject();
        BeanUtils.copyProperties(maProjectVo, maProject);

        if (maProjectVo.getId() == null) {
            // 新增
            maProject.setCreateBy(loginUser.getUser().getUserId());
            maProject.setUpdateBy(loginUser.getUser().getUserId());
            maProject.setCreateTime(DateUtils.getNowDate());
            return maProjectMapper.insertMaProject(maProject);
        } else {
            // 修改
            maProject.setUpdateBy(loginUser.getUser().getUserId());
            return maProjectMapper.updateMaProject(maProject);
        }

    }

    /**
     * 修改服务项目
     *
     * @param maProject 服务项目
     * @return 结果
     */
    @Override
    public int updateMaProject(MaProject maProject) {
        return maProjectMapper.updateMaProject(maProject);
    }

    /**
     * 批量删除服务项目
     *
     * @param ids 需要删除的服务项目主键
     * @return 结果
     */
    @Override
    public int deleteMaProjectByIds(String[] ids) {
        return maProjectMapper.deleteMaProjectByIds(ids);
    }

    /**
     * 删除服务项目信息
     *
     * @param id 服务项目主键
     * @return 结果
     */
    @Override
    public int deleteMaProjectById(Long id) {
        return maProjectMapper.deleteMaProjectById(id);
    }

    @Override
    public Page<ProjectRecommendVo> getProjectRecommend(Page<ProjectRecommendVo> page, ProjectRecommendDTO dto) {
        return maProjectMapper.getProjectRecommend(page, dto);
    }

    @Override
    public Page<MerchantsVo> getMerchants(Page<MerchantsVo> page, MerchantsDto dto) {
        return maProjectMapper.getMerchants(page, dto);
    }

    @Override
    public Page<BookMerchantVO> selectMerchantList(Page<BookMerchantVO> page, BookMerchantDTO dto) {
        return maProjectMapper.selectMerchantList(page, dto);
    }

    /**
     * 校验枚举值是否在指定范围内
     *
     * @param value
     * @param fieldName
     * @param values
     */
    private void checkEnumValue(Integer value, String fieldName, Integer... values) {
        if (value == null) {
            return;
        }
        for (Integer item : values) {
            if (value.equals(item)) {
                return;
            }
        }
        throw new ServiceException(fieldName + "参数不正确");
    }

    /**
     * 校验整数是否为正数
     *
     * @param value
     * @param fieldName
     */
    private void checkRequiredPositive(Integer value, String fieldName) {
        if (value == null || value <= 0) {
            throw new ServiceException(fieldName + "不能为空");
        }
    }

}
