package com.fuyuanshen.app.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.app.domain.AppDeviceShare;
import com.fuyuanshen.app.mapper.AppDeviceShareMapper;
import com.fuyuanshen.app.service.IAppDeviceShareService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Set;

/**
 * 设备分享Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppDeviceShareServiceImpl implements IAppDeviceShareService {

    private final AppDeviceShareMapper baseMapper;

    private final DeviceMapper deviceMapper;

    /**
     * 查询设备分享
     *
     * @param id 主键
     * @return 设备分享
     */
    @Override
    public AppDeviceShareVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询设备分享列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备分享分页列表
     */
    @Override
    public TableDataInfo<AppDeviceShareVo> queryPageList(AppDeviceShareBo bo, PageQuery pageQuery) {
        Long userId = AppLoginHelper.getUserId();
        bo.setCreateBy(userId);
        LambdaQueryWrapper<AppDeviceShare> lqw = buildQueryWrapper(bo);
        Page<AppDeviceShareVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<AppDeviceShareVo> records = result.getRecords();
        records.forEach(r -> {
            Device device = deviceMapper.selectById(r.getDeviceId());
            if(device != null){
                r.setDevicePic(device.getDevicePic());
                r.setDeviceName(device.getDeviceName());
                r.setDeviceImei(device.getDeviceImei());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的设备分享列表
     *
     * @param bo 查询条件
     * @return 设备分享列表
     */
    @Override
    public List<AppDeviceShareVo> queryList(AppDeviceShareBo bo) {
        LambdaQueryWrapper<AppDeviceShare> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppDeviceShare> buildQueryWrapper(AppDeviceShareBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppDeviceShare> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeviceId() != null, AppDeviceShare::getDeviceId, bo.getDeviceId());
        lqw.eq(StringUtils.isNotBlank(bo.getPhonenumber()), AppDeviceShare::getPhonenumber, bo.getPhonenumber());
        lqw.eq(StringUtils.isNotBlank(bo.getPermission()), AppDeviceShare::getPermission, bo.getPermission());
        lqw.eq(bo.getCreateBy()!=null, AppDeviceShare::getCreateBy, bo.getCreateBy());
        return lqw;
    }

    /**
     * 新增设备分享
     *
     * @param bo 设备分享
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppDeviceShareBo bo) {
        AppDeviceShare add = MapstructUtils.convert(bo, AppDeviceShare.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改设备分享
     *
     * @param bo 设备分享
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppDeviceShareBo bo) {
        AppDeviceShare update = MapstructUtils.convert(bo, AppDeviceShare.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppDeviceShare entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除设备分享信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery) {
        String username = AppLoginHelper.getUsername();
        bo.setPhonenumber(username);
        Page<AppDeviceShareVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<AppDeviceShareVo> result = baseMapper.otherDeviceShareList(bo, page);
        List<AppDeviceShareVo> records = result.getRecords();
        records.forEach(r -> {
            Device device = deviceMapper.selectById(r.getDeviceId());
            if(device != null){
                r.setDevicePic(device.getDevicePic());
                r.setDeviceName(device.getDeviceName());
                r.setDeviceImei(device.getDeviceImei());
            }
        });
        return TableDataInfo.build(result);
    }

    @Override
    public void deleteByDeviceIds(Set<Long> deviceIds) {
        baseMapper.deleteByDeviceIds(deviceIds);
    }
}
