package cn.iocoder.yudao.module.asset.service.customer;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.asset.controller.admin.customer.vo.CustomerPageReqVO;
import cn.iocoder.yudao.module.asset.controller.admin.customer.vo.CustomerSaveReqVO;
import cn.iocoder.yudao.module.asset.convert.customer.CustomerConvert;
import cn.iocoder.yudao.module.asset.dal.dataobject.customer.CustomerBusinessManagerDO;
import cn.iocoder.yudao.module.asset.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.asset.dal.mysql.customer.CustomerBusinessManagerMapper;
import cn.iocoder.yudao.module.asset.dal.mysql.customer.CustomerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.asset.enums.ErrorCodeConstants.CUSTOMER_NOT_EXISTS;

/**
 * 客户信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private CustomerBusinessManagerMapper customerBusinessManagerMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCustomer(CustomerSaveReqVO createReqVO) {
        // 转换并插入
        CustomerDO customer = CustomerConvert.INSTANCE.convert(createReqVO);

        // 生成客户编号
        if (customer.getCustomerCode() == null) {
            customer.setCustomerCode(generateCustomerCode());
        }

        customerMapper.insert(customer);

        // 保存业务负责人
        saveBusinessManagers(customer.getId(), createReqVO.getBusinessManagers());

        return customer.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCustomer(CustomerSaveReqVO updateReqVO) {
        // 校验存在
        validateCustomerExists(updateReqVO.getId());

        // 转换并更新
        CustomerDO updateObj = CustomerConvert.INSTANCE.convert(updateReqVO);
        customerMapper.updateById(updateObj);

        // 更新业务负责人：先删除旧的，再插入新的
        customerBusinessManagerMapper.deleteByCustomerId(updateReqVO.getId());
        saveBusinessManagers(updateReqVO.getId(), updateReqVO.getBusinessManagers());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCustomer(Long id) {
        // 校验存在
        validateCustomerExists(id);

        // 删除业务负责人
        customerBusinessManagerMapper.deleteByCustomerId(id);

        // 删除客户
        customerMapper.deleteById(id);
    }

    private void validateCustomerExists(Long id) {
        if (customerMapper.selectById(id) == null) {
            throw exception(CUSTOMER_NOT_EXISTS);
        }
    }

    @Override
    public CustomerDO getCustomer(Long id) {
        return customerMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerDO> getCustomerPage(CustomerPageReqVO pageReqVO) {
        return customerMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CustomerDO> getCustomerSimpleList() {
        return customerMapper.selectList();
    }

    /**
     * 生成客户编号
     */
    private String generateCustomerCode() {
        // 查询最大ID
        Long maxId = customerMapper.selectCount();
        return String.format("KH-%04d-%03d", java.time.Year.now().getValue(), maxId + 1);
    }

    /**
     * 保存业务负责人
     */
    private void saveBusinessManagers(Long customerId, List<String> businessManagers) {
        if (businessManagers == null || businessManagers.isEmpty()) {
            return;
        }

        for (String managerName : businessManagers) {
            if (managerName != null && !managerName.trim().isEmpty()) {
                CustomerBusinessManagerDO managerDO = CustomerBusinessManagerDO.builder()
                        .customerId(customerId)
                        .businessManagerName(managerName.trim())
                        .build();
                customerBusinessManagerMapper.insert(managerDO);
            }
        }
    }

}
