package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.common.core.domain.R;
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.CustomerBusinessSearchDto;
import com.dsk.system.domain.customer.dto.CustomerSearchDto;
import com.dsk.system.domain.customer.vo.CustomerBusinessListVo;
import com.dsk.system.domain.customer.vo.CustomerListVo;
import com.dsk.system.domain.customer.vo.CustomerVo;
import com.dsk.system.dskService.EnterpriseService;
import com.dsk.system.mapper.CustomerMapper;
import com.dsk.system.mapper.CustomerUserMapper;
import com.dsk.system.service.IBusinessInfoService;
import com.dsk.system.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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
 */
@Slf4j
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Resource
    private CustomerMapper baseMapper;
    @Resource
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private EnterpriseService enterpriseService;

    @Override
    public List<CustomerListVo> selectList(CustomerSearchDto dto) {
        dto.setUserId(SecurityUtils.getUserId());
        List<CustomerListVo> vos = baseMapper.selectList(dto);
        vos.parallelStream().forEach(vo -> {
            //合作项目
            vo.setCooperationProject(businessInfoService.selectCountByStatusAndCustomerId(2, vo.getCustomerId()));
            //跟进项目
            vo.setFollowProject(businessInfoService.selectCountByStatusAndCustomerId(1, vo.getCustomerId()));
            //储备项目
            vo.setReserveProject(businessInfoService.selectCountByStatusAndCustomerId(0, vo.getCustomerId()));
        });
        return vos;
    }

    @Override
    public CustomerVo info(String customerId) {
        CustomerVo vo = new CustomerVo();
        BeanUtil.copyProperties(baseMapper.selectById(customerId), vo);
        CustomerUser customerUser = customerUserMapper.selectOne(Wrappers.<CustomerUser>lambdaQuery()
                .eq(CustomerUser::getCustomerId, customerId));
        vo.setUserId(customerUser.getUserId());
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(Customer customer) {
        try {
            R res = enterpriseService.getUipId(customer.getCompanyName());
            if (!ObjectUtils.isEmpty(res.getData())) {
                customer.setUipId(MapUtil.getStr(BeanUtil.beanToMap(res.getData()), "uipId"));
            }
        } catch (Exception e) {
            log.error("获取城投平台企业id错误！error：{}", e.getMessage());
        }

        Long userId = SecurityUtils.getUserId();
        customer.setCreateId(userId);
        customer.setUpdateId(userId);
        //查重
        Customer verifyCustomer = baseMapper.selectByCompanyNameAndUserId(customer.getCompanyName(), userId);
        if (!ObjectUtils.isEmpty(verifyCustomer)) {
            throw new ServiceException("当前客户信息已存在，请勿重复添加！");
        }

        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;
    }

    @Override
    public List<Customer> selectUserList() {
        return baseMapper.selectUserList(SecurityUtils.getUserId());
    }

    @Override
    public List<CustomerBusinessListVo> selectBusinessList(CustomerBusinessSearchDto dto) {
        if (ObjectUtils.isEmpty(dto.getCustomerId())) throw new BeanException("客户id不能为空");
        dto.setUserId(SecurityUtils.getUserId());
        return businessInfoService.selectCustomerBusinessList(dto);
    }

}
