package com.aegis.resource.supplier.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aegis.common.exception.ServiceException;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.common.utils.StringUtils;
import com.aegis.resource.supplier.domain.Supplier;
import com.aegis.resource.supplier.domain.SupplierLicense;
import com.aegis.resource.supplier.mapper.ResourceSupplierMapper;
import com.aegis.resource.supplier.mapper.ResourceSupplierLicenseMapper;
import com.aegis.resource.supplier.service.IResourceSupplierService;

/**
 * 供应商Service业务层处理
 * 
 * @author aegis
 */
@Service
public class ResourceSupplierServiceImpl implements IResourceSupplierService {

    @Autowired
    private ResourceSupplierMapper supplierMapper;

    @Autowired
    private ResourceSupplierLicenseMapper licenseMapper;

    /**
     * 查询供应商列表
     * 
     * @param supplier 供应商信息
     * @return 供应商集合
     */
    @Override
    public List<Supplier> listSuppliers(Supplier supplier) {
        return supplierMapper.selectSupplierList(supplier);
    }

    /**
     * 根据ID查询供应商
     * 
     * @param id 供应商ID
     * @return 供应商信息
     */
    @Override
    public Supplier getSupplierById(Long id) {
        return supplierMapper.selectSupplierById(id);
    }

    /**
     * 校验供应商编码是否唯一
     * 
     * @param supplierCode 供应商编码
     * @param id 供应商ID（更新时排除自己）
     * @return 是否唯一
     */
    @Override
    public boolean isSupplierCodeUnique(String supplierCode, Long id) {
        if (StringUtils.isEmpty(supplierCode)) {
            return true; // 供应商编码为空时认为唯一（由前端校验非空）
        }
        Supplier info = supplierMapper.checkSupplierCodeUnique(supplierCode, id);
        return info == null;
    }

    /**
     * 新增供应商
     * 
     * @param supplier 供应商信息
     * @return 结果
     */
    @Override
    @Transactional
    public int createSupplier(Supplier supplier) {
        // 校验供应商编码唯一性（检查未删除的记录）
        if (!isSupplierCodeUnique(supplier.getSupplierCode(), supplier.getId())) {
            throw new ServiceException("新增供应商'" + supplier.getSupplierName() + "'失败，供应商编码已存在");
        }
        
        // 检查是否存在已删除的相同编码记录
        Supplier deletedSupplier = supplierMapper.selectDeletedSupplierByCode(supplier.getSupplierCode());
        if (deletedSupplier != null) {
            // 如果存在已删除的记录，则恢复并更新该记录
            String operator = SecurityUtils.getUsername();
            supplier.setId(deletedSupplier.getId());
            supplier.setCreateBy(deletedSupplier.getCreateBy()); // 保留原创建人
            supplier.setUpdateBy(operator);
            supplier.initializeDefaults(operator);
            return supplierMapper.restoreSupplier(supplier);
        }
        
        // 不存在已删除记录，正常插入新记录
        String operator = SecurityUtils.getUsername();
        supplier.setCreateBy(operator);
        supplier.initializeDefaults(operator);
        return supplierMapper.insertSupplier(supplier);
    }

    /**
     * 修改供应商
     * 
     * @param supplier 供应商信息
     * @return 结果
     */
    @Override
    @Transactional
    public int modifySupplier(Supplier supplier) {
        // 校验供应商是否存在（包括已删除的记录）
        Supplier oldSupplier = supplierMapper.selectSupplierById(supplier.getId());
        if (oldSupplier == null) {
            // 如果未删除的记录不存在，检查是否存在已删除的记录
            Supplier deletedSupplier = supplierMapper.selectDeletedSupplierByCode(supplier.getSupplierCode());
            if (deletedSupplier != null && deletedSupplier.getId().equals(supplier.getId())) {
                // 如果存在已删除的记录且ID匹配，则恢复并更新
                String operator = SecurityUtils.getUsername();
                supplier.setCreateBy(deletedSupplier.getCreateBy()); // 保留原创建人
                supplier.setUpdateBy(operator);
                supplier.initializeDefaults(operator);
                return supplierMapper.restoreSupplier(supplier);
            }
            throw new ServiceException("供应商不存在");
        }
        
        // 如果供应商编码发生变化，检查新供应商编码是否已被使用（包括已删除的记录）
        if (!oldSupplier.getSupplierCode().equals(supplier.getSupplierCode())) {
            // 校验新供应商编码唯一性（检查未删除的记录）
            if (!isSupplierCodeUnique(supplier.getSupplierCode(), supplier.getId())) {
                throw new ServiceException("修改供应商'" + supplier.getSupplierName() + "'失败，供应商编码已存在");
            }
            // 检查新供应商编码是否存在已删除的记录
            Supplier deletedSupplierWithNewCode = supplierMapper.selectDeletedSupplierByCode(supplier.getSupplierCode());
            if (deletedSupplierWithNewCode != null) {
                throw new ServiceException("修改供应商'" + supplier.getSupplierName() + "'失败，该供应商编码已被删除，请先恢复该记录");
            }
        }
        String operator = SecurityUtils.getUsername();
        
        // 使用领域方法更新字段
        if (!StringUtils.equals(oldSupplier.getSupplierName(), supplier.getSupplierName())) {
            oldSupplier.rename(supplier.getSupplierName(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getSupplierCode(), supplier.getSupplierCode())) {
            oldSupplier.changeCode(supplier.getSupplierCode(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getCategory(), supplier.getCategory())) {
            oldSupplier.changeCategory(supplier.getCategory(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getArea(), supplier.getArea())) {
            oldSupplier.changeArea(supplier.getArea(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getContactPerson(), supplier.getContactPerson()) ||
            !StringUtils.equals(oldSupplier.getContactPhone(), supplier.getContactPhone()) ||
            !StringUtils.equals(oldSupplier.getEmail(), supplier.getEmail())) {
            oldSupplier.changeContact(supplier.getContactPerson(), supplier.getContactPhone(), 
                supplier.getEmail(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getAddress(), supplier.getAddress())) {
            oldSupplier.changeAddress(supplier.getAddress(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getRemark(), supplier.getRemark())) {
            oldSupplier.changeRemark(supplier.getRemark(), operator);
        }
        if (!StringUtils.equals(oldSupplier.getStatus(), supplier.getStatus())) {
            // 状态变更使用专门的领域方法
            if ("active".equals(supplier.getStatus())) {
                oldSupplier.activate(operator);
            } else if ("inactive".equals(supplier.getStatus())) {
                oldSupplier.deactivate(operator);
            } else if ("blacklisted".equals(supplier.getStatus())) {
                oldSupplier.blacklist(operator);
            }
        }
        if (supplier.getRating() != null && !supplier.getRating().equals(oldSupplier.getRating())) {
            oldSupplier.updateRating(supplier.getRating(), operator);
        }
        
        // 更新其他字段
        oldSupplier.setCreditCode(supplier.getCreditCode());
        
        return supplierMapper.updateSupplier(oldSupplier);
    }

    /**
     * 批量删除供应商
     * 
     * @param ids 需要删除的供应商ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int removeSuppliers(Long[] ids) {
        String operator = SecurityUtils.getUsername();
        // 删除供应商时，同时删除关联的资质记录
        for (Long id : ids) {
            Supplier supplier = supplierMapper.selectSupplierById(id);
            if (supplier == null) {
                throw new ServiceException("供应商ID=" + id + "不存在或已被删除");
            }
            supplier.markDeleted(operator);
            supplierMapper.updateSupplier(supplier);
            // 级联删除关联的资质记录
            licenseMapper.deleteSupplierLicenseBySupplierId(id);
        }
        return ids.length;
    }

    /**
     * 删除供应商信息
     * 
     * @param id 供应商ID
     * @return 结果
     */
    @Override
    @Transactional
    public int removeSupplier(Long id) {
        Supplier supplier = supplierMapper.selectSupplierById(id);
        if (supplier == null) {
            throw new ServiceException("供应商不存在");
        }
        String operator = SecurityUtils.getUsername();
        supplier.markDeleted(operator);
        // 删除供应商时，同时删除关联的资质记录
        licenseMapper.deleteSupplierLicenseBySupplierId(id);
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 启用供应商
     * 
     * @param id 供应商ID
     * @return 结果
     */
    @Override
    @Transactional
    public int activateSupplier(Long id) {
        Supplier supplier = supplierMapper.selectSupplierById(id);
        if (supplier == null) {
            throw new ServiceException("供应商不存在");
        }
        String operator = SecurityUtils.getUsername();
        supplier.activate(operator);
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 停用供应商
     * 
     * @param id 供应商ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deactivateSupplier(Long id) {
        Supplier supplier = supplierMapper.selectSupplierById(id);
        if (supplier == null) {
            throw new ServiceException("供应商不存在");
        }
        String operator = SecurityUtils.getUsername();
        supplier.deactivate(operator);
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 加入黑名单
     * 
     * @param id 供应商ID
     * @return 结果
     */
    @Override
    @Transactional
    public int blacklistSupplier(Long id) {
        Supplier supplier = supplierMapper.selectSupplierById(id);
        if (supplier == null) {
            throw new ServiceException("供应商不存在");
        }
        String operator = SecurityUtils.getUsername();
        supplier.blacklist(operator);
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 更新供应商评分
     * 
     * @param id 供应商ID
     * @param rating 评分（1-5）
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSupplierRating(Long id, Integer rating) {
        Supplier supplier = supplierMapper.selectSupplierById(id);
        if (supplier == null) {
            throw new ServiceException("供应商不存在");
        }
        String operator = SecurityUtils.getUsername();
        supplier.updateRating(rating, operator);
        return supplierMapper.updateSupplier(supplier);
    }

    /**
     * 查询供应商资质列表
     * 
     * @param license 资质信息
     * @return 资质集合
     */
    @Override
    public List<SupplierLicense> listLicenses(SupplierLicense license) {
        return licenseMapper.selectSupplierLicenseList(license);
    }

    /**
     * 根据ID查询资质
     * 
     * @param id 资质ID
     * @return 资质信息
     */
    @Override
    public SupplierLicense getLicenseById(Long id) {
        return licenseMapper.selectSupplierLicenseById(id);
    }

    /**
     * 新增供应商资质
     * 
     * @param license 资质信息
     * @return 结果
     */
    @Override
    @Transactional
    public int createLicense(SupplierLicense license) {
        // 校验供应商是否存在
        Supplier supplier = supplierMapper.selectSupplierById(license.getSupplierId());
        if (supplier == null) {
            throw new ServiceException("供应商不存在");
        }
        license.setCreateBy(SecurityUtils.getUsername());
        return licenseMapper.insertSupplierLicense(license);
    }

    /**
     * 修改供应商资质
     * 
     * @param license 资质信息
     * @return 结果
     */
    @Override
    @Transactional
    public int modifyLicense(SupplierLicense license) {
        // 校验资质是否存在
        SupplierLicense oldLicense = licenseMapper.selectSupplierLicenseById(license.getId());
        if (oldLicense == null) {
            throw new ServiceException("资质不存在");
        }
        license.setUpdateBy(SecurityUtils.getUsername());
        return licenseMapper.updateSupplierLicense(license);
    }

    /**
     * 删除供应商资质
     * 
     * @param id 资质ID
     * @return 结果
     */
    @Override
    @Transactional
    public int removeLicense(Long id) {
        return licenseMapper.deleteSupplierLicenseById(id);
    }
}