package cn.gov.customs.demo.service.impl;

import cn.gov.customs.cacp.enhance.accessory.pojo.Accessory;
import cn.gov.customs.cacp.enhance.accessory.service.AccessoryService;
import cn.gov.customs.cacp.sdks.core.config.CacpAppProperties;
import cn.gov.customs.cacp.sdks.hgid.HgidGenerator;
import cn.gov.customs.demo.dao.OrderDao;
import cn.gov.customs.demo.pojo.OrderInfo;
import cn.gov.customs.demo.pojo.OrderQueryInfo;
import cn.gov.customs.demo.service.OrderService;

import java.time.LocalDateTime;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description TODO
 * @author sunxuewen
 * @since 2024/11/21 上午8:25
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

  private final OrderDao mapper;
  private final AccessoryService accessoryService;
  private final HgidGenerator idHelper;
  private final CacpAppProperties properties;

  @Override
  public OrderInfo get(String orderId) {
    OrderInfo info = this.mapper.get(orderId);

    List<Accessory> accessoryList = this.accessoryService.getPersistListByBizId(this.properties.getAppCode(), orderId);
    info.setAccessoryList(accessoryList);

    return info;
  }

  @Override
  public PageInfo<OrderInfo> getPageList(OrderQueryInfo query) {
    PageHelper.startPage(query.getPageIndex(), query.getPageSize());
    List<OrderInfo> list = this.mapper.getList(query.getKeyword(), query.getBeginDate(), query.getEndDate().plusDays(1));
    return PageInfo.of(list);
  }

  @Transactional(value = "demoTransactionManager", rollbackFor = Exception.class)
  @Override
  public int insert(OrderInfo info) {
    String orderId = this.idHelper.nextId();
    info.setOrderId(orderId);

    if (!CollectionUtils.isEmpty(info.getAccessoryList())) {
      info.getAccessoryList()
          .forEach(
              a -> {
                a.setBizId(orderId);
                a.setAppCode(this.properties.getAppCode());
              });
    }
    this.accessoryService.persistFiles(info.getAccessoryList());

    info.setCreateTime(LocalDateTime.now());
    return this.mapper.insert(info);
  }

  @Transactional(value = "demoTransactionManager", rollbackFor = Exception.class)
  @Override
  public int update(OrderInfo info) {
    info.getAccessoryList().forEach(a -> {
      a.setBizId(info.getOrderId());
      a.setAppCode(this.properties.getAppCode());
    });
    this.accessoryService.persistFiles(info.getAccessoryList());

    return this.mapper.update(info);
  }

  @Transactional(value = "demoTransactionManager", rollbackFor = Exception.class)
  @Override
  public int delete(String orderId) {
    this.accessoryService.deleteListByBizId(this.properties.getAppCode(), orderId);
    return this.mapper.delete(orderId);
  }
}
