package cn.iocoder.yudao.module.system.service.assets;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.module.system.controller.admin.assets.vo.AssetsPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.assets.vo.AssetsSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.assets.AssetsDO;
import cn.iocoder.yudao.module.system.dal.dataobject.assets.AssetsTypeDO;
import cn.iocoder.yudao.module.system.dal.mysql.assets.AssetsMapper;
import cn.iocoder.yudao.module.system.dal.mysql.assets.AssetsTypeMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

/**
 * 资产 Service 实现类
 *
 * @author 艾楷
 */
@Service
@Validated
public class AssetsServiceImpl implements AssetsService {

    @Resource
    private AssetsMapper assetsMapper;
    @Resource
    private DeptAssetsInOutStockService deptAssetsInOutStockService;
    @Resource
    private AssetsTypeMapper assetsTypeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAssets(AssetsSaveReqVO createReqVO) {
        // -获取资产类型
        AssetsTypeDO assetsTypeDO = assetsTypeMapper.selectById(createReqVO.getTypeId());
        // 插入
        AssetsDO assets = BeanUtils.toBean(createReqVO, AssetsDO.class);
        // -- 如果是按量的话 状态设为无状态 - 如果是按件的话 状态设为空闲 并且 库存设为1
        assets.setStatus(assetsTypeDO.getType() == 0 ? -1 : 0);
        assets.setStock(assetsTypeDO.getType() == 0 ? createReqVO.getStock() : 1);
        assets.setAssetsNo(IdWorker.get32UUID());
        assetsMapper.insert(assets);
        // 返回
        return assets.getId();
    }

    @Override
    public void updateAssets(AssetsSaveReqVO updateReqVO) {
        // 更新
        AssetsDO updateObj = BeanUtils.toBean(updateReqVO, AssetsDO.class);
        assetsMapper.updateById(updateObj);
    }

    @Override
    public void deleteAssets(Long id) {
        // 删除
        assetsMapper.deleteById(id);
    }


    @Override
    public AssetsDO getAssets(Long id) {
        return assetsMapper.selectById(id);
    }

    @Override
    public PageResult<AssetsDO> getAssetsPage(AssetsPageReqVO pageReqVO) {
        IPage<AssetsDO> assetsDOIPage = assetsMapper.selectPageList(pageReqVO, MyBatisUtils.buildPage(pageReqVO));
        return new PageResult<>(assetsDOIPage.getRecords(), assetsDOIPage.getTotal());
    }

}