/*
 * 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 vip.xiaonuo.biz.modular.depotLockBook.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotLockBook.entity.DepotLockBook;
import vip.xiaonuo.biz.modular.depotLockBook.mapper.DepotLockBookMapper;
import vip.xiaonuo.biz.modular.depotLockBook.param.DepotLockBookAddParam;
import vip.xiaonuo.biz.modular.depotLockBook.param.DepotLockBookEditParam;
import vip.xiaonuo.biz.modular.depotLockBook.param.DepotLockBookIdParam;
import vip.xiaonuo.biz.modular.depotLockBook.param.DepotLockBookPageParam;
import vip.xiaonuo.common.util.DatesUtil;

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

/**
 * 电子锁预约Service接口实现类
 *
 * @author xiang
 * @date 2023/09/14 09:44
 **/
@Service
public class DepotLockBookService extends ServiceImpl<DepotLockBookMapper, DepotLockBook> {

    @Resource
    DepotGrainService depotGrainService;

    public Page<DepotLockBook> page(DepotLockBookPageParam param) {
        QueryWrapper<DepotLockBook> wrapper = new QueryWrapper<>();
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotLockBook::getDepotId, depotIdLst);
        wrapper.and(Strings.isNotEmpty(param.getSearchKey()), w ->
                w.lambda().like(DepotLockBook::getShedName, param.getSearchKey())
                        .or().like(DepotLockBook::getLockName, param.getSearchKey())
                        .or().like(DepotLockBook::getRemark, param.getSearchKey()));
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotLockBook::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getShedName())) {
            wrapper.lambda().like(DepotLockBook::getShedName, param.getShedName());
        }
        if (ObjectUtil.isNotEmpty(param.getLockName())) {
            wrapper.lambda().like(DepotLockBook::getLockName, param.getLockName());
        }
        if (ObjectUtil.isNotEmpty(param.getRemark())) {
            wrapper.lambda().like(DepotLockBook::getRemark, param.getRemark());
        }
        if (Strings.isNotEmpty(param.getBankOpApprovalState()))
            if (param.getBankOpApprovalState().length() == 8)
                wrapper.gt("instr('" + param.getBankOpApprovalState() + "', bank_op_approval_state)", 0);
            else
                wrapper.lambda().eq(DepotLockBook::getBankOpApprovalState, param.getBankOpApprovalState());
        wrapper.lambda().like(Strings.isNotBlank(param.getBankOpApprovalRemark()), DepotLockBook::getBankOpApprovalRemark, param.getBankOpApprovalRemark());
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            wrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            wrapper.lambda().orderByDesc(DepotLockBook::getId);
        }

        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        return page;
    }

    public List<DepotLockBook> waitProcess(List<String> depotIdLst) {
        LambdaQueryWrapper<DepotLockBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotLockBook::getDepotId, depotIdLst);
        wrapper.eq(DepotLockBook::getBankOpApprovalState, BizStr.STATE_APPROVAL_N);
        return list(wrapper.orderByDesc(DepotLockBook::getId));
    }

    public void add(DepotLockBookAddParam depotLockBookAddParam) {
        DepotLockBook depotLockBook = BeanUtil.toBean(depotLockBookAddParam, DepotLockBook.class);
        this.save(depotLockBook);
    }

    public void edit(DepotLockBookEditParam param) {
        DepotLockBook depotLockBook = this.queryEntity(param.getId());
        if (Strings.isNotBlank(param.getBankOpApprovalState())
                && !param.getBankOpApprovalState().equals(depotLockBook.getBankOpApprovalState()))
            depotLockBook.setBankOpApprovalTime(DatesUtil.forDateTime());
        BeanUtil.copyProperties(param, depotLockBook);
        this.updateById(depotLockBook);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotLockBookIdParam> depotLockBookIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotLockBookIdParamList, DepotLockBookIdParam::getId));
    }

    public DepotLockBook detail(DepotLockBookIdParam depotLockBookIdParam) {
        return this.queryEntity(depotLockBookIdParam.getId());
    }

    public DepotLockBook queryEntity(String id) {
        DepotLockBook depotLockBook = this.getById(id);
        if (ObjectUtil.isEmpty(depotLockBook)) {
            throw new CommonException("电子锁预约不存在，id值为：{}", id);
        }
        return depotLockBook;
    }
}
