package com.ruoyi.web.modules.trading.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.trading.domain.BizDistributor;
import com.ruoyi.web.modules.trading.mapper.BizDistributorMapper;
import com.ruoyi.web.modules.trading.service.IBizDistributorService;
import com.ruoyi.web.modules.trading.support.DistributorCodeGenerator;
import com.ruoyi.web.modules.trading.support.DistributorReferenceChecker;
import com.ruoyi.web.modules.trading.support.DistributorRules;
import com.ruoyi.web.modules.trading.support.DistributorValidation;
import com.ruoyi.web.modules.trading.support.TradePartnerAccountAssigner;
import com.ruoyi.web.modules.trading.support.TradePartnerAccountRules;

/**
 * 承销商管理服务实现。
 */
@Service
public class BizDistributorServiceImpl implements IBizDistributorService
{
    @Autowired
    private BizDistributorMapper bizDistributorMapper;

    @Autowired
    private DistributorCodeGenerator distributorCodeGenerator;

    @Autowired
    private DistributorReferenceChecker referenceChecker;

    @Autowired
    private TradePartnerAccountAssigner accountAssigner;

    @Override
    public BizDistributor selectBizDistributorById(Long id)
    {
        BizDistributor row = bizDistributorMapper.selectBizDistributorById(id);
        enrichRow(row);
        return row;
    }

    @Override
    public List<BizDistributor> selectBizDistributorList(BizDistributor query)
    {
        List<BizDistributor> list = bizDistributorMapper.selectBizDistributorList(query);
        if (list != null)
        {
            for (BizDistributor row : list)
            {
                enrichRow(row);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizDistributor(BizDistributor row)
    {
        row.setDistributorCode(null);
        DistributorValidation.validateRowForSave(row);
        assertDistributorNameUnique(row.getDistributorName(), null);
        assertIdentityNoUnique(row.getIdentityNo(), null);
        row.setDistributorCode(distributorCodeGenerator.allocateNextCode());
        row.setDelFlag(DistributorRules.DEL_FLAG_NORMAL);
        row.setAccountAssigned(TradePartnerAccountRules.ACCOUNT_ASSIGNED_NO);
        row.setSysUserId(null);
        row.setAssignedLoginName(null);
        return bizDistributorMapper.insertBizDistributor(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizDistributor(BizDistributor row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        BizDistributor db = requireActiveRow(row.getId());
        if (StringUtils.isNotEmpty(row.getDistributorCode())
                && !row.getDistributorCode().equals(db.getDistributorCode()))
        {
            throw new ServiceException("承销商编号不可修改");
        }
        row.setDistributorCode(db.getDistributorCode());
        DistributorValidation.validateRowForSave(row);
        assertDistributorNameUnique(row.getDistributorName(), row.getId());
        assertIdentityNoUnique(row.getIdentityNo(), row.getId());
        row.setDelFlag(DistributorRules.DEL_FLAG_NORMAL);
        row.setAccountAssigned(db.getAccountAssigned());
        row.setSysUserId(db.getSysUserId());
        row.setAssignedLoginName(db.getAssignedLoginName());
        return bizDistributorMapper.updateBizDistributor(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizDistributorByIds(Long[] ids, String updateBy)
    {
        if (ids == null || ids.length == 0)
        {
            return 0;
        }
        List<Long> cleaned = new ArrayList<>();
        for (Long id : ids)
        {
            if (id != null)
            {
                cleaned.add(id);
            }
        }
        if (cleaned.isEmpty())
        {
            return 0;
        }
        for (Long id : cleaned)
        {
            BizDistributor row = bizDistributorMapper.selectBizDistributorByIdAny(id);
            if (row == null || DistributorRules.DEL_FLAG_DELETED.equals(row.getDelFlag()))
            {
                continue;
            }
            if (referenceChecker.hasUnpaidOrder(id))
            {
                throw new ServiceException(DistributorRules.MSG_DELETE_UNPAID_ORDER);
            }
            accountAssigner.deleteLinkedAccount(row.getAccountAssigned(), row.getSysUserId());
        }
        return bizDistributorMapper.logicDeleteBizDistributorByIds(cleaned.toArray(new Long[0]), updateBy);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int assignAccount(Long id, String operator)
    {
        BizDistributor row = requireActiveRow(id);
        DistributorValidation.validateForAssignAccount(row);
        SysUser user = accountAssigner.createAccount(
                row.getDistributorName(), row.getContactPhone(), row.getId(),
                TradePartnerAccountRules.ROLE_KEY_DISTRIBUTOR, operator);
        row.setAccountAssigned(TradePartnerAccountRules.ACCOUNT_ASSIGNED_YES);
        row.setSysUserId(user.getUserId());
        row.setAssignedLoginName(user.getUserName());
        return bizDistributorMapper.updateBizDistributor(row);
    }

    private void assertDistributorNameUnique(String distributorName, Long excludeId)
    {
        if (bizDistributorMapper.countBizDistributorByNameExcludeId(distributorName, excludeId) > 0)
        {
            throw new ServiceException("承销商名称已存在");
        }
    }

    private void assertIdentityNoUnique(String identityNo, Long excludeId)
    {
        if (bizDistributorMapper.countBizDistributorByIdentityNoExcludeId(identityNo, excludeId) > 0)
        {
            throw new ServiceException("该身份识别号已登记");
        }
    }

    private BizDistributor requireActiveRow(Long id)
    {
        BizDistributor row = bizDistributorMapper.selectBizDistributorById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在或已删除");
        }
        return row;
    }

    private static void enrichRow(BizDistributor row)
    {
        if (row == null)
        {
            return;
        }
        row.setDistributorTypeName(DistributorRules.distributorTypeName(row.getDistributorType()));
        row.setSalesDestinationName(DistributorRules.salesDestinationName(row.getSalesDestination()));
    }
}
