package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanException;
import com.dsk.common.core.domain.model.LoginUser;
import com.dsk.common.utils.SecurityUtils;
import com.dsk.system.domain.customer.ContactInfo;
import com.dsk.system.domain.customer.dto.ContactInfoSearchDto;
import com.dsk.system.domain.customer.vo.ContactInfoListVo;
import com.dsk.system.dskService.EnterpriseService;
import com.dsk.system.mapper.ContactInfoMapper;
import com.dsk.system.service.IContactInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 用户联系人(CustomerContact)表服务实现类
 *
 * @author makejava
 * @since 2023-07-25 17:18:04
 */
@Slf4j
@Service
public class ContactInfoServiceImpl implements IContactInfoService {

    @Resource
    private ContactInfoMapper baseMapper;

    @Autowired
    private EnterpriseService enterpriseService;

//    @Resource
//    private ICustomerService customerService;

    @Override
    public List<ContactInfoListVo> selectList(ContactInfoSearchDto dto) {
        return baseMapper.selectPageList(dto);
    }

    @Override
    public ContactInfo selectById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean insert(ContactInfo bean) {
        verifyParameter(bean);
        bean.setCreateBy(bean.getUpdateBy());
        return baseMapper.insert(bean) > 0;
    }

    @Override
    public boolean update(ContactInfo bean) {
        if (ObjectUtils.isEmpty(bean.getId())) throw new BeanException("id不能为空！");
        verifyParameter(bean);
        return baseMapper.updateById(bean) > 0;
    }

    @Override
    public boolean deleteById(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 参数验证
     */
    private void verifyParameter(ContactInfo bean) {
        if (!ObjectUtils.isEmpty(bean.getCompanyName())) {
            Map<String, Object> map = enterpriseService.getCidAndUipIdByCompanyName(bean.getCompanyName());
            bean.setCompanyId(MapUtils.getInteger(map, "companyId"));
            bean.setUipId(MapUtils.getString(map, "uipId"));
        }
//        if (!ObjectUtils.isEmpty(bean.getCustomerId()) && ObjectUtils.isEmpty(bean.getId())) {
//            CustomerVo info = customerService.info(bean.getCustomerId());
//            bean.setCompanyName(info.getCompanyName());
//            bean.setCompanyId(info.getCompanyId());
//            bean.setUipId(info.getUipId());
//        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        bean.setUpdateId(loginUser.getUserId());
        bean.setUpdateBy(loginUser.getUser().getNickName());
    }
}
