package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanException;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.SecurityUtils;
import com.dsk.system.domain.customer.Customer;
import com.dsk.system.domain.customer.CustomerUser;
import com.dsk.system.domain.customer.dto.CustomerSearchDto;
import com.dsk.system.domain.customer.vo.CustomerListVo;
import com.dsk.system.mapper.CustomerMapper;
import com.dsk.system.mapper.CustomerUserMapper;
import com.dsk.system.service.ICustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

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

/**
 * 客户信息表(Customer)表服务实现类
 *
 * @author makejava
 * @since 2023-05-16 09:27:57
 */
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Resource
    private CustomerMapper baseMapper;
    @Resource
    private CustomerUserMapper customerUserMapper;

    @Override
    public List<CustomerListVo> selectList(CustomerSearchDto dto) {
        dto.setUserId(SecurityUtils.getUserId());
        List<CustomerListVo> vos = baseMapper.selectList(dto);
        for (CustomerListVo vo : vos) {
            //TODO 客户项目相关统计
            //合作项目
            vo.setCooperationProject(1);
            //跟进项目
            vo.setFollowProject(1);
            //储备项目
            vo.setReserveProject(1);
        }
        return vos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getCompanyName())) throw new BeanException("企业名称不能为空");
        final Long userId = SecurityUtils.getUserId();
        customer.setCreateId(userId);
        customer.setUpdateId(userId);
        //TODO 查询企业id
        customer.setCompanyId(0);

        int i = baseMapper.insert(customer);
        if (i == 0) throw new ServiceException("客户信息添加错误！");

        int ui = customerUserMapper.insert(new CustomerUser(customer.getCustomerId(), userId));
        if (ui == 0) throw new ServiceException("客户跟进人信息添加错误！");

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getCustomerId())) throw new BeanException("客户id不能为空");
        customer.setUpdateId(SecurityUtils.getUserId());
        int u = baseMapper.updateById(customer);
        return u != 0;
    }
}
