package cn.iocoder.yudao.module.customer.service.businessopportunity;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.customer.controller.admin.info.vo.CustomerInfoRespVO;
import cn.iocoder.yudao.module.customer.service.info.CustomerInfoService;
import cn.iocoder.yudao.module.employee.api.EmployeeApi;
import cn.iocoder.yudao.module.employee.api.dto.EmployeeRespDTO;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.api.file.dto.FileDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.customer.controller.admin.businessopportunity.vo.*;
import cn.iocoder.yudao.module.customer.dal.dataobject.businessopportunity.CustomerBusinessOpportunityDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.customer.dal.mysql.businessopportunity.CustomerBusinessOpportunityMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.customer.enums.ErrorCodeConstants.CUSTOMER_BUSINESS_OPPORTUNITY_NOT_EXISTS;

/**
 * 客户商机 Service 实现类
 *
 * @author zhaopq
 */
@Service
@Validated
public class CustomerBusinessOpportunityServiceImpl implements CustomerBusinessOpportunityService {

    @Resource
    private CustomerBusinessOpportunityMapper businessOpportunityMapper;
    @Resource
    private FileApi fileApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private EmployeeApi employeeApi;
    @Resource
    private CustomerInfoService customerInfoService;

    @Override
    public Long createBusinessOpportunity(CustomerBusinessOpportunitySaveReqVO createReqVO) {
        // 获取用户信息和租户ID
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Long tenantId = user != null && user.getTenantId() != null ? user.getTenantId() : 0L;
        Long userId = user != null && user.getId() != null ? user.getId() : 0L;
        createReqVO.setTenantId(tenantId);
        // 通过用户ID获取登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(userId);
        // 创建人信息
        if (loginEmployee != null) {
            createReqVO.setCreatorEmployeeId(loginEmployee.getId());
            createReqVO.setCreatorEmployeeName(loginEmployee.getName());
            createReqVO.setDeptId(loginEmployee.getDeptId());
        }
        // 插入
        String infoId = IdUtil.fastSimpleUUID();
        createReqVO.setOpportunityId(infoId);
        CustomerBusinessOpportunityDO businessOpportunity = BeanUtils.toBean(createReqVO, CustomerBusinessOpportunityDO.class);
        businessOpportunityMapper.insert(businessOpportunity);
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(createReqVO.getFileIdList(), infoId);
        // 返回
        return businessOpportunity.getId();
    }

    @Override
    public void updateBusinessOpportunity(CustomerBusinessOpportunitySaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessOpportunityExists(updateReqVO.getId());
        // 保存业务uuid到附件中
        fileApi.updateFileBiz(updateReqVO.getFileIdList(), updateReqVO.getOpportunityId());
        // 获取用户信息和租户ID
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Long tenantId = user != null && user.getTenantId() != null ? user.getTenantId() : 0L;
        Long userId = user != null && user.getId() != null ? user.getId() : 0L;
        // 通过用户ID获取登录员工信息
        EmployeeRespDTO loginEmployee = employeeApi.getEmployeeByUserId(userId);
        // 创建人信息
        if (loginEmployee != null) {
            updateReqVO.setCreatorEmployeeId(loginEmployee.getId());
            updateReqVO.setCreatorEmployeeName(loginEmployee.getName());
            updateReqVO.setDeptId(loginEmployee.getDeptId());
        }
        // 更新
        CustomerBusinessOpportunityDO updateObj = BeanUtils.toBean(updateReqVO, CustomerBusinessOpportunityDO.class);
        businessOpportunityMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessOpportunity(Long id) {
        // 校验存在
        validateBusinessOpportunityExists(id);
        // 删除
        businessOpportunityMapper.deleteById(id);
    }

    private void validateBusinessOpportunityExists(Long id) {
        if (businessOpportunityMapper.selectById(id) == null) {
            throw exception(CUSTOMER_BUSINESS_OPPORTUNITY_NOT_EXISTS);
        }
    }

    @Override
    public CustomerBusinessOpportunityDO getBusinessOpportunity(Long id) {
        return businessOpportunityMapper.selectById(id);
    }

    @Override
    @TenantIgnore
    public CustomerBusinessOpportunityRespVO getById(Long id) {
        // 第一步：检查ID是否为空
        if (id == null) {
            throw new IllegalArgumentException("ID cannot be null");
        }
        // 第二步：从数据库获取数据
        CustomerBusinessOpportunityDO opportunityDO = businessOpportunityMapper.selectById(id);
        if (opportunityDO == null) {
            throw exception(CUSTOMER_BUSINESS_OPPORTUNITY_NOT_EXISTS);
        }
        // 第三步：将DO对象转换为VO对象
        CustomerBusinessOpportunityRespVO respVO = BeanUtils.toBean(opportunityDO, CustomerBusinessOpportunityRespVO.class);
        if (respVO == null) {
            // 理论上BeanUtils.toBean不应该返回null，但为了安全起见，还是检查一下
            throw new RuntimeException("Failed to convert DO to VO");
        }
        // 第四步：获取附件列表
        List<FileDTO> fileList = fileApi.getFileDTOListByBiz(opportunityDO.getOpportunityId());
        if (fileList != null) {
            // 如果fileList不为null，则设置到VO对象中
            respVO.setFileList(fileList);
            List<Long> fileIdList = fileList.stream().map(FileDTO::getId).collect(Collectors.toList());
            respVO.setFileIdList(fileIdList);
        }
        // 部门
        if (opportunityDO.getDeptId() != null) {
            DeptRespDTO dept = deptApi.getDept(opportunityDO.getDeptId());
            respVO.setDeptName(dept.getName());
            if (dept != null && StringUtils.isNotBlank(dept.getName())) {
                respVO.setDeptName(dept.getName());
            }
        }
        // 客户
        if (opportunityDO.getCustomerId() != null) {
            CustomerInfoRespVO infoRespVO = customerInfoService.getById(opportunityDO.getCustomerId());
            if (infoRespVO != null && StringUtils.isNotBlank(infoRespVO.getCustomerName())) {
                respVO.setCustomerName(infoRespVO.getCustomerName());
            }
        }
        // 第五步：返回VO对象
        return respVO;
    }

    @Override
    public PageResult<CustomerBusinessOpportunityDO> getBusinessOpportunityPage(CustomerBusinessOpportunityPageReqVO pageReqVO) {
        return businessOpportunityMapper.selectPage(pageReqVO);
    }

    @Override
    public String getOpportunityCode() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String format = formatter.format(LocalDateTime.now());
        return format + IdUtil.fastSimpleUUID();
    }

}