package com.crm.custom.service.impl;

import com.crm.custom.dao.repository.AccountApplyAssetManagementRepository;
import com.crm.custom.service.AccountApplyAssetManagementService;
import com.crm.custom.service.CustomInfoService;
import com.crm.custom.service.CustomLoginAssetManagementService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.CustomConstant;
import com.crm.rely.backend.core.constant.StatusConstants;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.constant.CustomConstants;
import com.crm.rely.backend.model.entity.account.apply.asset.management.AccountApplyAssetManagementAddEntity;
import com.crm.rely.backend.model.pojo.table.AccountApplyAssetManagementTable;
import com.crm.rely.backend.util.GetRandom;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountApplyAssetManagementServiceImpl implements AccountApplyAssetManagementService {

    @Autowired
    private AccountApplyAssetManagementRepository repository;
    @Autowired
    private CustomLoginAssetManagementService offerService;
    @Autowired
    private CustomInfoService customInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAccountApply(AccountApplyAssetManagementAddEntity entity) throws ServiceException {

        if (entity.getSourceLogin() == null) {
             /*
            验证是否有未完成的申请
         */
            boolean exists = repository.existsByCustomIdAndStatus(entity.getCustomId(), StatusConstants.APPLY_STATUS);
            if (exists) {
                throw new ServiceException(Constants.APPLY_EXISTS);
            }
            exists = offerService.existAssetManagementStatus(entity.getCustomId());
            if (exists) {
                throw new ServiceException(Constants.NOT_PERMIT);
            }
        }

        /*
            保存信息
         */
        AccountApplyAssetManagementTable table = new AccountApplyAssetManagementTable();
        BeanUtils.copyProperties(entity, table);
        table.setMasterPassword(null);
        table.setStatus(StatusConstants.APPLY_STATUS);
        table.setSerial(getSerial());
        table.setAccountStatus(null);
        table.setGroupCode(null);
        table.setLogin(null);
        repository.save(table);

        if (entity.getSourceLogin() == null) {
            customInfoService.updatePosition(table.getCustomId(), CustomConstants.POSITION4);
        }

    }

    private String getSerial() {
        String orderNo = GetRandom.getOrderNo(CustomConstant.ACCOUNT_FIRM_OFFER_HEAD);
        return orderNo;
    }
}
