/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.huimv.modular.basepigpen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.core.consts.CommonConstant;
import com.huimv.core.context.login.LoginContextHolder;
import com.huimv.core.enums.CommonStatusEnum;
import com.huimv.core.exception.DemoException;
import com.huimv.core.exception.RequestMethodException;
import com.huimv.core.exception.ServiceException;
import com.huimv.core.factory.PageFactory;
import com.huimv.core.pojo.page.PageResult;
import com.huimv.core.pojo.response.ErrorResponseData;
import com.huimv.core.pojo.response.ResponseData;
import com.huimv.core.pojo.response.SuccessResponseData;
import com.huimv.core.util.PoiUtil;
import com.huimv.modular.basepigpen.entity.BasePigpen;
import com.huimv.modular.basepigpen.enums.BasePigpenExceptionEnum;
import com.huimv.modular.basepigpen.mapper.BasePigpenMapper;
import com.huimv.modular.basepigpen.param.BasePigpenParam;
import com.huimv.modular.basepigpen.service.BasePigpenService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;

/**
 * 栋舍表service接口实现类
 *
 * @author yinhao
 * @date 2021-08-17 14:00:42
 */
@Service
public class BasePigpenServiceImpl extends ServiceImpl<BasePigpenMapper, BasePigpen> implements BasePigpenService {

    @Override
    public PageResult<BasePigpen> page(BasePigpenParam basePigpenParam) {
        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(basePigpenParam)) {
            Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();

            queryWrapper.lambda().eq(BasePigpen::getOrgId,sysLoginUserOrgId);
            // 根据栋舍名称 查询
            if (ObjectUtil.isNotEmpty(basePigpenParam.getPigpenName())) {
                queryWrapper.lambda().like(BasePigpen::getPigpenName, basePigpenParam.getPigpenName());
            }
            // 根据时间 查询
            if (ObjectUtil.isNotEmpty(basePigpenParam.getCreatTime())) {
                queryWrapper.lambda().eq(BasePigpen::getCreatTime, basePigpenParam.getCreatTime());
            }
            // 根据阶段 查询
            if (ObjectUtil.isNotEmpty(basePigpenParam.getStage())) {
                queryWrapper.lambda().like(BasePigpen::getStage, basePigpenParam.getStage());
            }

        }
        queryWrapper.lambda().eq(BasePigpen::getType, 1);
        PageResult<BasePigpen> basePigpenPageResult = new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
        List<BasePigpen> rows = basePigpenPageResult.getRows();
        for (BasePigpen row : rows) {

            queryWrapper.clear();
            queryWrapper.eq("parent_id",row.getId());
            row.setChildren(this.list(queryWrapper));
        }
        return basePigpenPageResult;
    }

    @Override
    public List<BasePigpen> list(BasePigpenParam basePigpenParam) {
        return this.list();
    }

    @Override
    public void add(BasePigpenParam basePigpenParam) {
        BasePigpen basePigpen = new BasePigpen();
        BeanUtil.copyProperties(basePigpenParam, basePigpen);
        this.save(basePigpen);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseData delete(List<Integer> basePigpenParamList) {

        for (Integer basePigpenParam : basePigpenParamList) {
            QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
            basePigpenQueryWrapper.eq("parent_id",basePigpenParam);
            int count = this.count(basePigpenQueryWrapper);
            if (count > 0){
                return  new ErrorResponseData("该栋舍下有单元为清理");
            }
        }
        basePigpenParamList.forEach(this::removeById);
        return new SuccessResponseData();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BasePigpenParam basePigpenParam) {
        BasePigpen basePigpen = this.queryBasePigpen(basePigpenParam);
        BeanUtil.copyProperties(basePigpenParam, basePigpen);

        if ( basePigpen.getType() == 1){
            QueryWrapper<BasePigpen> basePigpenQueryWrapper = new QueryWrapper<>();
            basePigpenQueryWrapper.eq("parent_id",basePigpen.getId());
            BasePigpen pigpen = new BasePigpen();
            pigpen.setStage(basePigpen.getStage());
            this.update(pigpen,basePigpenQueryWrapper);
        }
        this.updateById(basePigpen);
    }

    @Override
    public BasePigpen detail(BasePigpenParam basePigpenParam) {
        return this.queryBasePigpen(basePigpenParam);
    }

    /**
     * 获取栋舍表
     *
     * @author yinhao
     * @date 2021-08-17 14:00:42
     */
    private BasePigpen queryBasePigpen(BasePigpenParam basePigpenParam) {
        BasePigpen basePigpen = this.getById(basePigpenParam.getId());
        if (ObjectUtil.isNull(basePigpen)) {
            throw new ServiceException(BasePigpenExceptionEnum.NOT_EXIST);
        }
        return basePigpen;
    }


    @Override
    public List<BasePigpen> listPigpen() {
        Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
        return this.list(new QueryWrapper<BasePigpen>().eq("type",1).eq("org_id",sysLoginUserOrgId));
    }

    @Override
    public List<BasePigpen> listUnit(Integer id) {
        Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
        return this.list(new QueryWrapper<BasePigpen>().eq("parent_id",id).eq("org_id",sysLoginUserOrgId));

    }
}
