package com.yueqian.xingyun.basedata.impl.shop;

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.event.DataChangeEventBuilder;
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.basedata.entity.Shop;
import com.yueqian.xingyun.basedata.enums.BaseDataOpLogType;
import com.yueqian.xingyun.basedata.events.DeleteShopEvent;
import com.yueqian.xingyun.basedata.mappers.ShopMapper;
import com.yueqian.xingyun.basedata.service.shop.ShopService;
import com.yueqian.xingyun.basedata.vo.shop.CreateShopVo;
import com.yueqian.xingyun.basedata.vo.shop.QueryShopVo;
import com.yueqian.xingyun.basedata.vo.shop.UpdateShopVo;
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 ShopServiceImpl extends BaseMpServiceImpl<ShopMapper, Shop> implements ShopService {

  @Override
  public PageResult<Shop> query(Integer pageIndex, Integer pageSize, QueryShopVo vo) {

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

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

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

  @Override
  public List<Shop> query(QueryShopVo vo) {

    return getBaseMapper().query(vo);
  }

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

    return getBaseMapper().selectById(id);
  }

  @OpLog(type = BaseDataOpLogType.class, name = "删除门店，ID：{}", params = {"#id"})
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void deleteById(String id) {

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

    Shop record = this.findById(id);

    DataChangeEventBuilder.publishLogicDelete(this, DeleteShopEvent.class, record);
  }

  @OpLog(type = BaseDataOpLogType.class, name = "新增门店，ID：{}", params = {"#id"})
  @Transactional(rollbackFor = Exception.class)
  @Override
  public String create(CreateShopVo vo) {

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

    Shop data = new Shop();
    data.setId(IdUtil.getId());
    data.setCode(vo.getCode());
    data.setName(vo.getName());
    if (!StringUtil.isBlank(vo.getDeptId())) {
      data.setDeptId(vo.getDeptId());
    }
    if (vo.getLng() != null) {
      data.setLng(vo.getLng());
    }
    if (vo.getLat() != null) {
      data.setLat(vo.getLat());
    }
    if (!StringUtil.isBlank(vo.getDescription())) {
      data.setDescription(vo.getDescription());
    }

    data.setAvailable(Boolean.TRUE);

    getBaseMapper().insert(data);

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

    return data.getId();
  }

  @OpLog(type = BaseDataOpLogType.class, name = "修改门店，ID：{}", params = {"#id"})
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void update(UpdateShopVo vo) {

    Shop data = getBaseMapper().selectById(vo.getId());
    if (ObjectUtil.isNull(data)) {
      throw new DefaultClientException("门店不存在！");
    }

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

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

    getBaseMapper().update(updateWrapper);

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

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

  }
}
