package com.erp.purchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.purchase.dto.SupplierDTO;
import com.erp.purchase.entity.Supplier;
import com.erp.purchase.enums.SupplierStatus;
import com.erp.purchase.exception.BusinessException;
import com.erp.purchase.mapper.SupplierMapper;
import com.erp.purchase.service.SupplierService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
@Service
@RequiredArgsConstructor
public class SupplierServiceImpl implements SupplierService {

    private final SupplierMapper supplierMapper;
    private static final AtomicLong CODE_COUNTER = new AtomicLong(System.currentTimeMillis() % 100000);

    @Override
    public IPage<Supplier> listPage(SupplierDTO.QueryRequest query) {
        Page<Supplier> page = new Page<>(query.getPage(), query.getLimit());
        return supplierMapper.selectPageList(page, query.getKeyword(), query.getStatus());
    }

    @Override
    public Supplier getById(Long id) {
        Supplier supplier = supplierMapper.selectById(id);
        if (supplier == null) throw new BusinessException("供应商不存在");
        return supplier;
    }

    @Override
    public Supplier getByCode(String supplierCode) {
        return supplierMapper.findByCode(supplierCode);
    }

    @Override
    @Transactional
    public Supplier create(SupplierDTO.CreateRequest request, Long operatorId) {
        if (supplierMapper.findByCode(request.getSupplierCode()) != null) {
            throw new BusinessException("供应商编码已存在: " + request.getSupplierCode());
        }

        String code = request.getSupplierCode();
        if (code == null || code.isBlank()) {
            code = generateCode();
        }

        Supplier supplier = Supplier.builder()
                .supplierCode(code)
                .name(request.getName())
                .contact(request.getContact())
                .phone(request.getPhone())
                .email(request.getEmail())
                .address(request.getAddress())
                .status(request.getStatus() != null ? request.getStatus() : SupplierStatus.ACTIVE.getCode())
                .taxRate(request.getTaxRate())
                .paymentMethod(request.getPaymentMethod())
                .paymentPeriod(request.getPaymentPeriod())
                .bankName(request.getBankName())
                .bankAccount(request.getBankAccount())
                .bankBranch(request.getBankBranch())
                .creditCode(request.getCreditCode())
                .remark(request.getRemark())
                .createBy(operatorId)
                .createTime(LocalDateTime.now())
                .updateBy(operatorId)
                .updateTime(LocalDateTime.now())
                .deleted(0)
                .build();

        supplierMapper.insert(supplier);
        log.info("创建供应商: id={}, name={}, code={}", supplier.getId(), supplier.getName(), code);
        return supplier;
    }

    @Override
    @Transactional
    public Supplier update(SupplierDTO.UpdateRequest request, Long operatorId) {
        Supplier supplier = supplierMapper.selectById(request.getId());
        if (supplier == null) throw new BusinessException("供应商不存在");

        if (request.getName() != null) supplier.setName(request.getName());
        if (request.getContact() != null) supplier.setContact(request.getContact());
        if (request.getPhone() != null) supplier.setPhone(request.getPhone());
        if (request.getEmail() != null) supplier.setEmail(request.getEmail());
        if (request.getAddress() != null) supplier.setAddress(request.getAddress());
        if (request.getStatus() != null) supplier.setStatus(request.getStatus());
        if (request.getTaxRate() != null) supplier.setTaxRate(request.getTaxRate());
        if (request.getPaymentMethod() != null) supplier.setPaymentMethod(request.getPaymentMethod());
        if (request.getPaymentPeriod() != null) supplier.setPaymentPeriod(request.getPaymentPeriod());
        if (request.getBankName() != null) supplier.setBankName(request.getBankName());
        if (request.getBankAccount() != null) supplier.setBankAccount(request.getBankAccount());
        if (request.getBankBranch() != null) supplier.setBankBranch(request.getBankBranch());
        if (request.getCreditCode() != null) supplier.setCreditCode(request.getCreditCode());
        if (request.getRemark() != null) supplier.setRemark(request.getRemark());

        supplier.setUpdateBy(operatorId);
        supplier.setUpdateTime(LocalDateTime.now());
        supplierMapper.updateById(supplier);

        log.info("更新供应商: id={}, name={}", supplier.getId(), supplier.getName());
        return supplier;
    }

    @Override
    @Transactional
    public void delete(Long id, Long operatorId) {
        Supplier supplier = supplierMapper.selectById(id);
        if (supplier == null) throw new BusinessException("供应商不存在");
        supplier.setUpdateBy(operatorId);
        supplier.setUpdateTime(LocalDateTime.now());
        supplierMapper.deleteById(id);
        log.info("删除供应商: id={}, name={}", id, supplier.getName());
    }

    @Override
    @Transactional
    public void updateStatus(Long id, String status, Long operatorId) {
        Supplier supplier = supplierMapper.selectById(id);
        if (supplier == null) throw new BusinessException("供应商不存在");
        supplier.setStatus(status);
        supplier.setUpdateBy(operatorId);
        supplier.setUpdateTime(LocalDateTime.now());
        supplierMapper.updateById(supplier);
        log.info("更新供应商状态: id={}, status={}", id, status);
    }

    private String generateCode() {
        return "SUP" + String.format("%06d", CODE_COUNTER.incrementAndGet());
    }
}
