package com.unis.module.coding.service.zjxx;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yitter.idgen.YitIdHelper;
import com.unis.framework.common.util.kqbm.KQBMUtils;
import com.unis.framework.common.util.object.ObjectUtils;
import com.unis.module.coding.dal.dataobject.hwk.HwkDO;
import com.unis.module.coding.dal.mysql.hwk.HwkMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import com.unis.module.coding.controller.admin.zjxx.vo.*;
import com.unis.module.coding.dal.dataobject.zjxx.ZjxxDO;
import com.unis.framework.common.pojo.PageResult;
import com.unis.framework.common.pojo.PageParam;
import com.unis.framework.common.util.object.BeanUtils;

import com.unis.module.coding.dal.mysql.zjxx.ZjxxMapper;

import static com.unis.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.unis.module.core.enums.ErrorCodeConstants.ZJXX_NOT_EXISTS;

/**
 * 质检信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ZjxxServiceImpl implements ZjxxService {

    @Resource
    private ZjxxMapper zjxxMapper;
    @Resource
    private HwkMapper hwkMapper;

    @Override
    public Long createZjxx(ZjxxSaveReqVO createReqVO) {
        // 插入
        ZjxxDO zjxx = BeanUtils.toBean(createReqVO, ZjxxDO.class);
        if (ObjectUtil.isEmpty(createReqVO.getId())) {
            zjxx.setId(YitIdHelper.nextId());
            zjxx.setDeleted(false);
            // 插入前查询一下是否有hwkId
            List<HwkDO> hwks = hwkMapper.selectList(new QueryWrapper<HwkDO>().eq("CF_ID", createReqVO.getCfId()));
            if (CollectionUtil.isNotEmpty(hwks)) {
                //将已经存在的货位卡id放进去
                zjxx.setHwkId(hwks.get(0).getId());
            }
            zjxxMapper.insert(zjxx);
        } else {
            zjxxMapper.updateById(zjxx);
        }
        // 返回
        return zjxx.getId();
    }

    @Override
    public void updateZjxx(ZjxxSaveReqVO updateReqVO) {
        // 校验存在
        validateZjxxExists(updateReqVO.getId());
        // 更新
        ZjxxDO updateObj = BeanUtils.toBean(updateReqVO, ZjxxDO.class);
        zjxxMapper.updateById(updateObj);
    }

    @Override
    public void deleteZjxx(Long id) {
        // 校验存在
        validateZjxxExists(id);
        // 删除
        zjxxMapper.deleteById(id);
    }

    private void validateZjxxExists(Long id) {
        if (zjxxMapper.selectById(id) == null) {
            throw exception(ZJXX_NOT_EXISTS);
        }
    }

    @Override
    public ZjxxDO getZjxx(Long id) {
        return zjxxMapper.selectById(id);
    }

    @Override
    public PageResult<ZjxxDO> getZjxxPage(ZjxxPageReqVO pageReqVO) {
        return zjxxMapper.selectPage(pageReqVO);
    }

}