package com.yueqian.xingyun.settle.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.lframework.starter.common.constants.StringPool;
import com.lframework.starter.common.exceptions.impl.DefaultClientException;
import com.lframework.starter.common.utils.Assert;
import com.lframework.starter.common.utils.ObjectUtil;
import com.lframework.starter.common.utils.StringUtil;
import com.lframework.starter.web.core.annotations.oplog.OpLog;
import com.lframework.starter.web.core.components.resp.PageResult;
import com.lframework.starter.web.core.impl.BaseMpServiceImpl;
import com.lframework.starter.web.core.utils.IdUtil;
import com.lframework.starter.web.core.utils.OpLogUtil;
import com.lframework.starter.web.core.utils.PageHelperUtil;
import com.lframework.starter.web.core.utils.PageResultUtil;
import com.yueqian.xingyun.settle.entity.SettleInItem;
import com.yueqian.xingyun.settle.enums.SettleOpLogType;
import com.yueqian.xingyun.settle.mappers.SettleInItemMapper;
import com.yueqian.xingyun.settle.service.SettleInItemService;
import com.yueqian.xingyun.settle.vo.item.in.CreateSettleInItemVo;
import com.yueqian.xingyun.settle.vo.item.in.QuerySettleInItemVo;
import com.yueqian.xingyun.settle.vo.item.in.SettleInItemSelectorVo;
import com.yueqian.xingyun.settle.vo.item.in.UpdateSettleInItemVo;
import java.io.Serializable;
import java.util.List;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SettleInItemServiceImpl extends BaseMpServiceImpl<SettleInItemMapper, SettleInItem>
    implements SettleInItemService {

  @Override
  public PageResult<SettleInItem> query(Integer pageIndex, Integer pageSize,
      QuerySettleInItemVo vo) {

    Assert.greaterThanZero(pageIndex);
    Assert.greaterThanZero(pageSize);

    PageHelperUtil.startPage(pageIndex, pageSize);
    List<SettleInItem> datas = this.query(vo);

    return PageResultUtil.convert(new PageInfo<>(datas));
  }

  @Override
  public List<SettleInItem> query(QuerySettleInItemVo vo) {

    return getBaseMapper().query(vo);
  }

  @Override
  public PageResult<SettleInItem> selector(Integer pageIndex, Integer pageSize,
      SettleInItemSelectorVo vo) {

    Assert.greaterThanZero(pageIndex);
    Assert.greaterThanZero(pageSize);

    PageHelperUtil.startPage(pageIndex, pageSize);
    List<SettleInItem> datas = getBaseMapper().selector(vo);

    return PageResultUtil.convert(new PageInfo<>(datas));
  }

  @Cacheable(value = SettleInItem.CACHE_NAME, key = "@cacheVariables.tenantId() + #id", unless = "#result == null")
  @Override
  public SettleInItem findById(String id) {

    return getBaseMapper().selectById(id);
  }

  @OpLog(type = SettleOpLogType.class, name = "删除收入项目，ID：{}", params = "#id")
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void deleteById(String id) {

    Wrapper<SettleInItem> updateWrapper = Wrappers.lambdaUpdate(SettleInItem.class)
        .set(SettleInItem::getAvailable, Boolean.FALSE).eq(SettleInItem::getId, id);
    getBaseMapper().update(updateWrapper);
  }

  @OpLog(type = SettleOpLogType.class, name = "新增收入项目，ID：{}, 编号：{}", params = {"#id",
      "#code"})
  @Transactional(rollbackFor = Exception.class)
  @Override
  public String create(CreateSettleInItemVo vo) {

    Wrapper<SettleInItem> checkWrapper = Wrappers.lambdaQuery(SettleInItem.class)
        .eq(SettleInItem::getCode, vo.getCode()).eq(SettleInItem::getAvailable, Boolean.TRUE);
    if (getBaseMapper().selectCount(checkWrapper) > 0) {
      throw new DefaultClientException("编号重复，请重新输入！");
    }

    SettleInItem data = new SettleInItem();
    data.setId(IdUtil.getId());
    data.setCode(vo.getCode());
    data.setName(vo.getName());
    data.setAvailable(Boolean.TRUE);
    data.setDescription(
        StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR : vo.getDescription());

    getBaseMapper().insert(data);

    OpLogUtil.setVariable("id", data.getId());
    OpLogUtil.setVariable("code", vo.getCode());
    OpLogUtil.setExtra(vo);

    return data.getId();
  }

  @OpLog(type = SettleOpLogType.class, name = "修改收入项目，ID：{}, 编号：{}", params = {"#id",
      "#code"})
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void update(UpdateSettleInItemVo vo) {

    SettleInItem data = getBaseMapper().selectById(vo.getId());
    if (ObjectUtil.isNull(data)) {
      throw new DefaultClientException("收入项目不存在！");
    }

    Wrapper<SettleInItem> checkWrapper = Wrappers.lambdaQuery(SettleInItem.class)
        .eq(SettleInItem::getCode, vo.getCode()).eq(SettleInItem::getAvailable, Boolean.TRUE)
        .ne(SettleInItem::getId, vo.getId());
    if (getBaseMapper().selectCount(checkWrapper) > 0) {
      throw new DefaultClientException("编号重复，请重新输入！");
    }

    LambdaUpdateWrapper<SettleInItem> updateWrapper = Wrappers.lambdaUpdate(SettleInItem.class)
        .set(SettleInItem::getCode, vo.getCode()).set(SettleInItem::getName, vo.getName())
        .set(SettleInItem::getDescription,
            StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR : vo.getDescription())
        .eq(SettleInItem::getId, vo.getId());

    getBaseMapper().update(updateWrapper);

    OpLogUtil.setVariable("id", data.getId());
    OpLogUtil.setVariable("code", vo.getCode());
    OpLogUtil.setExtra(vo);
  }

  @CacheEvict(value = SettleInItem.CACHE_NAME, key = "@cacheVariables.tenantId() + #key")
  @Override
  public void cleanCacheByKey(Serializable key) {

  }
}
