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

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.pojo.PageResult;
import com.unis.framework.common.util.object.BeanUtils;
import com.unis.module.coding.controller.admin.hwk.vo.HwkPageReqVO;
import com.unis.module.coding.controller.admin.hwk.vo.HwkSaveReqVO;
import com.unis.module.coding.dal.dataobject.crkxx.CrkxxDO;
import com.unis.module.coding.dal.dataobject.hwk.HwkDO;
import com.unis.module.coding.dal.dataobject.lqjcxx.LqjcxxDO;
import com.unis.module.coding.dal.dataobject.syxx.SyxxDO;
import com.unis.module.coding.dal.dataobject.zjxx.ZjxxDO;
import com.unis.module.coding.dal.mysql.crkxx.CrkxxMapper;
import com.unis.module.coding.dal.mysql.hwk.HwkMapper;
import com.unis.module.coding.dal.mysql.lqjcxx.LqjcxxMapper;
import com.unis.module.coding.dal.mysql.syxx.SyxxMapper;
import com.unis.module.coding.dal.mysql.zjxx.ZjxxMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

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

/**
 * 货位卡信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class HwkServiceImpl implements HwkService {

    @Resource
    private HwkMapper hwkMapper;
    @Resource
    private CrkxxMapper crkxxMapper;
    @Resource
    private LqjcxxMapper lqjcxxMapper;
    @Resource
    private ZjxxMapper zjxxMapper;
    @Resource
    private SyxxMapper syxxMapper;

    /**
     * @param createReqVO 创建信息 有id修改，无id创建
     * @return
     * @desc 创建货位卡时查看其他四项（出入库，粮情，质检，损益）是否存在，存在就将其插入
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createHwk(HwkSaveReqVO createReqVO) {
        HwkDO hwk = BeanUtils.toBean(createReqVO, HwkDO.class);
        if (ObjectUtil.isEmpty(createReqVO.getId())) {
            // 插入
            hwk.setId(YitIdHelper.nextId());
            hwkMapper.insert(hwk);
            //查询（出入库，粮情，质检，损益）是否存在存在无货位卡id插入
            //=================================
            //(1)出入库（多条）
            List<CrkxxDO> crks = crkxxMapper.selectList(new QueryWrapper<CrkxxDO>().eq("CF_ID", createReqVO.getCfId()));
            if (!CollectionUtil.isEmpty(crks)) {
                //不为空开始查询是否有货位卡id
                crks.forEach(crk -> {
                    if (ObjectUtil.isEmpty(crk.getHwkId())) {
                        crk.setHwkId(hwk.getId());
                        crkxxMapper.updateById(crk);
                    }
                });
            }
            ///////粮情检测信息（一条）
            List<LqjcxxDO> lqjc = lqjcxxMapper.selectList(new QueryWrapper<LqjcxxDO>().eq("CF_ID", createReqVO.getCfId()));
            if (!CollectionUtil.isEmpty(lqjc)) {
                //不为空开始查询是否有货位卡id
                lqjc.forEach(lq -> {
                    if (ObjectUtil.isEmpty(lq.getHwkId())) {
                        lq.setHwkId(hwk.getId());
                        lqjcxxMapper.updateById(lq);
                    }
                });
            }
            //质检信息(多条)
            List<ZjxxDO> zjxxs = zjxxMapper.selectList(new QueryWrapper<ZjxxDO>().eq("CF_ID", createReqVO.getCfId()));
            if (!CollectionUtil.isEmpty(zjxxs)) {
                //不为空开始查询是否有货位卡id
                zjxxs.forEach(zjxx -> {
                    if (ObjectUtil.isEmpty(zjxx.getHwkId())) {
                        zjxx.setHwkId(hwk.getId());
                        zjxxMapper.updateById(zjxx);
                    }
                });
            }
            //损益信息(一条)
            List<SyxxDO> syxx = syxxMapper.selectList(new QueryWrapper<SyxxDO>().eq("CF_ID", createReqVO.getCfId()));
            if (!CollectionUtil.isEmpty(syxx)) {
                //不为空开始查询是否有货位卡id
                syxx.forEach(sy -> {
                    if (ObjectUtil.isEmpty(sy.getHwkId())) {
                        sy.setHwkId(hwk.getId());
                        syxxMapper.updateById(sy);
                    }
                });
            }
            //===============================
        } else {
            //更改
            hwkMapper.updateById(hwk);
        }
        // 返回
        return hwk.getId();
    }

    @Override
    public void updateHwk(HwkSaveReqVO updateReqVO) {
        // 校验存在
        validateHwkExists(updateReqVO.getId());
        // 更新
        HwkDO updateObj = BeanUtils.toBean(updateReqVO, HwkDO.class);
        hwkMapper.updateById(updateObj);
    }

    @Override
    public void deleteHwk(Long id) {
        // 校验存在
        validateHwkExists(id);
        // 删除
        hwkMapper.deleteById(id);
    }

    private void validateHwkExists(Long id) {
        if (hwkMapper.selectById(id) == null) {
            throw exception(HWK_NOT_EXISTS);
        }
    }

    @Override
    public HwkDO getHwk(Long id) {
        return hwkMapper.selectById(id);
    }

    @Override
    public PageResult<HwkDO> getHwkPage(HwkPageReqVO pageReqVO) {
        return hwkMapper.selectPage(pageReqVO);
    }

    @Override
    public HwkDO getHwkByCfId(Long cfId) {
        HwkDO hwkByCfId = hwkMapper.getHwkByCfId(cfId);
        return hwkByCfId;
    }

}