/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.statisticalReport.info.modular.grainReserveInspection.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.common.util.RandomListElement;
import com.unis.statisticalReport.info.modular.grainReserveInspectionItem.entity.GrainReserveInspectionItem;
import com.unis.statisticalReport.info.modular.grainReserveInspectionItem.mapper.GrainReserveInspectionItemMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.statisticalReport.info.modular.grainReserveInspection.entity.GrainReserveInspection;
import com.unis.statisticalReport.info.modular.grainReserveInspection.mapper.GrainReserveInspectionMapper;
import com.unis.statisticalReport.info.modular.grainReserveInspection.param.GrainReserveInspectionAddParam;
import com.unis.statisticalReport.info.modular.grainReserveInspection.param.GrainReserveInspectionEditParam;
import com.unis.statisticalReport.info.modular.grainReserveInspection.param.GrainReserveInspectionIdParam;
import com.unis.statisticalReport.info.modular.grainReserveInspection.param.GrainReserveInspectionPageParam;
import com.unis.statisticalReport.info.modular.grainReserveInspection.service.GrainReserveInspectionService;

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

/**
 * 储备粮验收检查Service接口实现类
 *
 * @author QSHan
 * @date 2024/06/03 11:11
 **/
@Service
public class GrainReserveInspectionServiceImpl extends ServiceImpl<GrainReserveInspectionMapper, GrainReserveInspection> implements GrainReserveInspectionService {
    @Resource
    private GrainReserveInspectionMapper grainReserveInspectionMapper;
    @Resource
    private GrainReserveInspectionItemMapper grainReserveInspectionItemMapper;

    @Override
    public Page<GrainReserveInspection> page(GrainReserveInspectionPageParam param) {
        QueryWrapper<GrainReserveInspection> wrapper = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(param.getStorehouseName()))
            wrapper.eq("bs.storehouse_name", param.getStorehouseName());
        if (ObjectUtils.isNotEmpty(param.getWarehouseName()))
            wrapper.eq("bw.warehouse_name", param.getWarehouseName());
        wrapper.lambda().orderByDesc(GrainReserveInspection::getId);
        return grainReserveInspectionMapper.page(new Page<>(param.getCurrent(), param.getSize()), wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(GrainReserveInspectionAddParam grainReserveInspectionAddParam) {
        GrainReserveInspection grainReserveInspection = BeanUtil.toBean(grainReserveInspectionAddParam, GrainReserveInspection.class);
        this.save(grainReserveInspection);
        // 保存子表
        if (CollectionUtils.isNotEmpty(grainReserveInspectionAddParam.getGranItem())) {
            grainReserveInspectionAddParam.getGranItem().forEach(item -> {
                item.setIpadGrainReserveInspectionId(grainReserveInspection.getId());
                grainReserveInspectionItemMapper.insert(item);
            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(GrainReserveInspectionEditParam grainReserveInspectionEditParam) {
        GrainReserveInspection grainReserveInspection = this.queryEntity(grainReserveInspectionEditParam.getId());
        BeanUtil.copyProperties(grainReserveInspectionEditParam, grainReserveInspection);
        this.updateById(grainReserveInspection);
        // 更新子表
        // 先删除
        QueryWrapper<GrainReserveInspectionItem> wrapper = new QueryWrapper<>();
        wrapper.eq("ipad_grain_reserve_inspection_id", grainReserveInspectionEditParam.getId());
        if (CollectionUtils.isNotEmpty(grainReserveInspectionEditParam.getGranItem())) {
            grainReserveInspectionItemMapper.delete(wrapper);
            grainReserveInspectionEditParam.getGranItem().forEach(item -> {
                item.setIpadGrainReserveInspectionId(grainReserveInspection.getId());
                // 在新增
                grainReserveInspectionItemMapper.insert(item);
            });
        } else { // 为空全部删除
            grainReserveInspectionItemMapper.delete(wrapper);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<GrainReserveInspectionIdParam> grainReserveInspectionIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(grainReserveInspectionIdParamList, GrainReserveInspectionIdParam::getId));
        // 删除子表
        grainReserveInspectionIdParamList.forEach(param -> {
            QueryWrapper<GrainReserveInspectionItem> wrapper = new QueryWrapper<>();
            wrapper.eq("ipad_grain_reserve_inspection_id", param.getId());
            grainReserveInspectionItemMapper.delete(wrapper);
        });
    }

    @Override
    public GrainReserveInspection detail(GrainReserveInspectionIdParam grainReserveInspectionIdParam) {
        GrainReserveInspection grainReserveInspection = this.queryEntity(grainReserveInspectionIdParam.getId());
        // 查询子表
        QueryWrapper<GrainReserveInspectionItem> wrapper = new QueryWrapper<>();
        wrapper.eq("ipad_grain_reserve_inspection_id", grainReserveInspectionIdParam.getId());
        List<GrainReserveInspectionItem> grainReserveInspectionItems = grainReserveInspectionItemMapper.selectChinaList(wrapper);
        if (CollectionUtils.isNotEmpty(grainReserveInspectionItems))
            grainReserveInspection.setGranItem(grainReserveInspectionItems);
        return grainReserveInspection;
    }

    @Override
    public GrainReserveInspection queryEntity(String id) {
        GrainReserveInspection grainReserveInspection = this.getById(id);
        if (ObjectUtil.isEmpty(grainReserveInspection)) {
            throw new CommonException("储备粮验收检查不存在，id值为：{}", id);
        }
        return grainReserveInspection;
    }

    @Override
    public Map<String, Object> getOrgInfoOnly() {
        List<Map<String, Object>> orgInfoList = grainReserveInspectionMapper.getOrgInfoOnly();
        Map<String, Object> randomElement = RandomListElement.getRandomElement(orgInfoList);
        if (randomElement == null)
            return Collections.emptyMap();
        return randomElement;
    }

    @Override
    public List<Map<String, Object>> getStorehouseOrWarehouse(Integer orgId, Integer storeHouseId) {

        List<Map<String, Object>> list;
        if (ObjectUtils.isEmpty(storeHouseId)) {
            list = grainReserveInspectionMapper.getStorehouse(orgId);
        } else {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("orgId", orgId);
            paramMap.put("storeHouseId", storeHouseId);
            list = grainReserveInspectionMapper.getWarehouse(paramMap);
        }
        return list;
    }

    @Override
    public String getCd(Integer orgId, Integer storeHouseId, Integer warehouseId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orgId", orgId);
        paramMap.put("storeHouseId", storeHouseId);
        paramMap.put("warehouseId", warehouseId);
        return grainReserveInspectionMapper.getCd(paramMap);
    }

}
