package org.dromara.machinery.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.machinery.domain.EqpMachinery;
import org.dromara.machinery.domain.EqpMachineryDetail;
import org.dromara.machinery.domain.dto.machinery.EqpMachineryCreateReq;
import org.dromara.machinery.domain.dto.machinery.EqpMachineryGisReq;
import org.dromara.machinery.domain.dto.machinery.EqpMachineryQueryReq;
import org.dromara.machinery.domain.dto.machinery.EqpMachineryUpdateReq;
import org.dromara.machinery.domain.vo.machinery.EqpMachineryVo;
import org.dromara.machinery.domain.vo.machinery.EqpMachineryGisVo;
import org.dromara.machinery.mapper.EqpMachineryMapper;
import org.dromara.machinery.service.IEqpMachineryDetailService;
import org.dromara.machinery.service.IEqpMachineryService;
import org.dromara.project.domain.BusProject;
import org.dromara.project.service.IBusProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 机械Service业务层处理
 *
 * @author lcj
 * @date 2025-03-07
 */
@Service
public class EqpMachineryServiceImpl extends ServiceImpl<EqpMachineryMapper, EqpMachinery>
    implements IEqpMachineryService {

    @Resource
    private IBusProjectService projectService;

    @Lazy
    @Resource
    private IEqpMachineryDetailService machineryDetailService;

    /**
     * 查询机械
     *
     * @param id 主键
     * @return 机械
     */
    @Override
    public EqpMachineryVo queryById(Long id) {
        EqpMachinery machinery = this.getById(id);
        if (machinery == null) {
            throw new ServiceException("机械信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(machinery);
    }

    /**
     * 分页查询机械列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 机械分页列表
     */
    @Override
    public TableDataInfo<EqpMachineryVo> queryPageList(EqpMachineryQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<EqpMachinery> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的机械列表
     *
     * @param req 查询条件
     * @return 机械列表
     */
    @Override
    public List<EqpMachineryVo> queryList(EqpMachineryQueryReq req) {
        LambdaQueryWrapper<EqpMachinery> lqw = this.buildQueryWrapper(req);
        List<EqpMachinery> list = this.list(lqw);
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 查询机械大屏数据列表
     *
     * @param req 筛选条件
     * @return 大屏数据列表
     */
    @Override
    public List<EqpMachineryGisVo> queryGisList(EqpMachineryGisReq req) {
        Long projectId = req.getProjectId();
        BusProject project = projectService.getById(projectId);
        if (project == null) {
            throw new ServiceException("项目信息不存在", HttpStatus.NOT_FOUND);
        }
        List<EqpMachinery> list = this.lambdaQuery()
            .eq(EqpMachinery::getProjectId, projectId).list();
        return list.stream().map(machinery -> {
            EqpMachineryGisVo machineryGisVo = new EqpMachineryGisVo();
            machineryGisVo.setMachineryName(machinery.getMachineryName());
            machineryGisVo.setMachineryCount(machinery.getNumber());
            return machineryGisVo;
        }).toList();
    }

    /**
     * 新增机械
     *
     * @param req 机械
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(EqpMachineryCreateReq req) {
        // 将实体类和 DTO 进行转换
        EqpMachinery machinery = new EqpMachinery();
        BeanUtils.copyProperties(req, machinery);
        // 数据校验
        validEntityBeforeSave(machinery, true);
        // 操作数据库
        boolean save = this.save(machinery);
        if (!save) {
            throw new ServiceException("新增机械失败，数据库异常", HttpStatus.ERROR);
        }
        return machinery.getId();
    }

    /**
     * 修改机械
     *
     * @param req 机械
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EqpMachineryUpdateReq req) {
        // 将实体类和 DTO 进行转换
        EqpMachinery machinery = new EqpMachinery();
        BeanUtils.copyProperties(req, machinery);
        // 数据校验
        validEntityBeforeSave(machinery, false);
        // 判断是否存在
        EqpMachinery oldMachinery = this.getById(machinery.getId());
        if (oldMachinery == null) {
            throw new ServiceException("修改机械失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(machinery);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EqpMachinery entity, Boolean create) {
        // 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        String machineryName = entity.getMachineryName();
        String principal = entity.getPrincipal();
        String principalPhone = entity.getPrincipalPhone();
        if (projectId == null) {
            throw new ServiceException("项目 id 不能为空", HttpStatus.BAD_REQUEST);
        }
        if (create) {
            if (StrUtil.isBlank(machineryName)) {
                throw new ServiceException("机械名称不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(principal)) {
                throw new ServiceException("负责人不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(principalPhone)) {
                throw new ServiceException("负责人手机号不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        if (StringUtils.isNotBlank(principalPhone) && !PhoneUtil.isPhone(principalPhone)) {
            throw new ServiceException("负责人手机号格式不正确", HttpStatus.BAD_REQUEST);
        }
        // 判断用户是否对项目下的内容有操作权限
        Long userId = LoginHelper.getUserId();
        projectService.validAuth(projectId, userId);
    }

    /**
     * 校验并批量删除机械信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<EqpMachinery> machineryList = this.listByIds(ids);
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            // 获取项目id列表
            List<Long> projectIdList = machineryList.stream().map(EqpMachinery::getProjectId).toList();
            // 判断是否有权限操作对应项目下的内容
            projectService.validAuth(projectIdList, userId);
            // 判断是否还存在机械详情信息
            QueryWrapper<EqpMachineryDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("machinery_id", ids);
            if (machineryDetailService.count(queryWrapper) > 0) {
                throw new ServiceException("删除机械失败，机械存在机械详情信息", HttpStatus.BAD_REQUEST);
            }
        }
        if (machineryList.size() != ids.size()) {
            throw new ServiceException("删除机械失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取机械视图对象
     *
     * @param machinery 机械对象
     * @return 机械视图对象
     */
    @Override
    public EqpMachineryVo getVo(EqpMachinery machinery) {
        // 对象转封装类
        EqpMachineryVo machineryVo = new EqpMachineryVo();
        if (machinery == null) {
            return machineryVo;
        }
        BeanUtils.copyProperties(machinery, machineryVo);
        return machineryVo;
    }

    /**
     * 获取机械查询条件封装
     *
     * @param req 机械查询条件
     * @return 机械查询条件封装
     */
    @Override
    public LambdaQueryWrapper<EqpMachinery> buildQueryWrapper(EqpMachineryQueryReq req) {
        LambdaQueryWrapper<EqpMachinery> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String machineryName = req.getMachineryName();
        String machineryNumber = req.getMachineryNumber();
        Long projectId = req.getProjectId();
        Long number = req.getNumber();
        String principal = req.getPrincipal();
        String principalPhone = req.getPrincipalPhone();
        String provider = req.getProvider();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(machineryName), EqpMachinery::getMachineryName, machineryName);
        lqw.like(StringUtils.isNotBlank(principal), EqpMachinery::getPrincipal, principal);
        lqw.like(StringUtils.isNotBlank(principalPhone), EqpMachinery::getPrincipalPhone, principalPhone);
        lqw.like(StringUtils.isNotBlank(provider), EqpMachinery::getProvider, provider);
        lqw.like(StringUtils.isNotBlank(machineryNumber), EqpMachinery::getMachineryNumber, machineryNumber);
        lqw.like(StringUtils.isNotBlank(remark), EqpMachinery::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), EqpMachinery::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), EqpMachinery::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(number), EqpMachinery::getNumber, number);
        return lqw;
    }

    /**
     * 获取机械分页对象视图
     *
     * @param machineryPage 机械分页对象
     * @return 机械分页对象视图
     */
    @Override
    public Page<EqpMachineryVo> getVoPage(Page<EqpMachinery> machineryPage) {
        List<EqpMachinery> machineryList = machineryPage.getRecords();
        Page<EqpMachineryVo> machineryVoPage = new Page<>(
            machineryPage.getCurrent(),
            machineryPage.getSize(),
            machineryPage.getTotal());
        if (CollUtil.isEmpty(machineryList)) {
            return machineryVoPage;
        }
        List<EqpMachineryVo> machineryVoList = machineryList.stream().map(this::getVo).toList();
        machineryVoPage.setRecords(machineryVoList);
        return machineryVoPage;
    }
}
