package com.iformall.service.invest.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.iformall.common.ErrorCode;
import com.iformall.common.TableLog;
import com.iformall.domain.po.invest.InvestCustomerEntity;
import com.iformall.domain.vo.invest.InvestCustomerVo;
import com.iformall.enums.EnumCustomerType;
import com.iformall.enums.EnumInvestChannel;
import com.iformall.mapper.InvestCustomerMapper;
import com.iformall.service.WxBrandService;
import com.iformall.service.WxBusinessService;
import com.iformall.service.invest.InvestCustomerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import static com.iformall.service.invest.InvestHelper.isTrue;

@Service
public class InvestCustomerServiceImpl extends InvestBaseServiceImpl<InvestCustomerMapper, InvestCustomerEntity> implements InvestCustomerService {

	@Autowired
	private WxBrandService brandService;
	@Autowired
	private WxBusinessService businessService ;

	@Override
    public boolean save(InvestCustomerEntity entity) {
		return super.saveAction(entity, this::checkBeforeSaveOrUpdate);
    }

	@TableLog
	@Override
	public boolean update(InvestCustomerEntity entity, Wrapper<InvestCustomerEntity> updateWrapper) {
		return super.updateActon(entity, updateWrapper, this::checkBeforeSaveOrUpdate);
	}

	@TableLog
	@Override
	public boolean updateById(InvestCustomerEntity entity) {

		return super.updateByIdAction(entity, this::checkBeforeSaveOrUpdate);
	}


	private void checkBeforeSaveOrUpdate(InvestCustomerEntity entity) {
		checkBusiness(businessService, entity.getBusinessId());
		checkBrand(brandService, entity.getBrandId());
		//checkType(entity);
		if (Objects.isNull(entity.getBrandId())) {
			entity.setBrandId(0L);
		}
		if (StringUtils.isBlank(entity.getInvestChannel())) {
			entity.setInvestChannel(EnumInvestChannel.NONE.getInfo());
		}
	}

	/**
	 * 校验客户类型
	 * @param entity
	 */
	private void checkType(InvestCustomerEntity entity) {
		isTrue(Objects.nonNull(entity.getType()), ErrorCode.SYS_PARAMETER_NOT_NULL, "客户类型");
	}


	@Deprecated
	@Override
	public boolean saveOrUpdate(InvestCustomerEntity entity) {
		notSupport();
		return false ;
	}

	@Deprecated
	@Override
	public boolean update(Wrapper<InvestCustomerEntity> updateWrapper) {
		notSupport();
		return false ;
	}


	@Override
	public List<InvestCustomerVo> listByIds(Collection<? extends Serializable> idList, List<EnumCustomerType> type) {
		return super.baseMapper.listByIds(idList,type);
	}

	@Override
	public int countCustomerUnassigned(String tenantId) {
		return super.baseMapper.countCustomerUnassigned(tenantId);
	}
}
