package com.dsk.biz.service.impl;

import cn.hutool.core.bean.BeanException;
import com.dsk.biz.domain.ContactInfo;
import com.dsk.biz.domain.bo.ContactInfoSearchDto;
import com.dsk.biz.domain.vo.ContactInfoListVo;
import com.dsk.biz.dskService.EnterpriseService;
import com.dsk.biz.mapper.ContactInfoMapper;
import com.dsk.biz.service.IContactInfoService;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.domain.model.LoginUser;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.helper.LoginHelper;
import com.google.api.client.util.SecurityUtils;
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 TableDataInfo<ContactInfoListVo> selectList(ContactInfoSearchDto dto, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.selectPageList(pageQuery.build(), 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"));
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        bean.setUpdateId(loginUser.getUserId());
        bean.setUpdateBy(loginUser.getNickname());
    }
}
