package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.dsk.common.config.RuoYiConfig;
import com.dsk.common.constant.HttpStatus;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.core.domain.entity.BusinessInfo;
import com.dsk.common.core.domain.entity.BusinessLabel;
import com.dsk.common.core.domain.entity.BusinessUser;
import com.dsk.common.exception.base.BaseException;
import com.dsk.common.utils.CheckUtils;
import com.dsk.common.utils.DateUtils;
import com.dsk.common.utils.SecurityUtils;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.file.FileUtils;
import com.dsk.system.domain.BusinessAddDto;
import com.dsk.system.domain.BusinessExcelDto;
import com.dsk.system.domain.BusinessListDto;
import com.dsk.system.domain.customer.dto.CustomerBusinessSearchDto;
import com.dsk.system.domain.customer.vo.CustomerBusinessListVo;
import com.dsk.system.domain.vo.BusinessBrowseVo;
import com.dsk.system.domain.vo.BusinessListVo;
import com.dsk.system.mapper.BusinessInfoMapper;
import com.dsk.system.mapper.BusinessLabelMapper;
import com.dsk.system.mapper.BusinessRelateCompanyMapper;
import com.dsk.system.mapper.BusinessUserMapper;
import com.dsk.system.service.IBusinessInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目详情Service业务层处理
 *
 * @author lxl
 * @date 2023-05-17
 */
@Service
@Slf4j
public class BusinessInfoServiceImpl implements IBusinessInfoService {
    @Resource
    private BusinessInfoMapper businessInfoMapper;
    @Resource
    private BusinessUserMapper businessUserMapper;
    @Resource
    private BusinessRelateCompanyMapper businessRelateCompanyMapper;
    @Resource
    private BusinessLabelMapper businessLabelMapper;
    @Resource
    private ReadBusinessInfoExcel readBusinessInfoExcel;

    /**
     * 查询项目详情
     *
     * @param id 项目详情主键
     * @return 项目详情
     */
    @Override
    public BusinessInfo selectBusinessInfoById(Integer id) {
        return businessInfoMapper.selectBusinessInfoById(id);
    }

    @Override
    public BusinessInfo getConstruction(Integer id) {
        return businessInfoMapper.getConstruction(id);
    }

    /**
     * 查询项目详情列表
     *
     * @param dto 项目详情
     * @return 项目详情
     */
    @Override
    public List<BusinessListVo> selectBusinessInfoList(BusinessListDto dto) {
        //userId不传值，就查询全部门项目
        if (dto.getUserId() == null) {
            Long deptId = SecurityUtils.getLoginUser().getDeptId();
            if (deptId == null) throw new BaseException("请登录");
            dto.setDeptId(deptId.intValue());
        }
        return businessInfoMapper.selectBusinessInfoList(dto);
    }

    @Override
    public BusinessBrowseVo browse(Integer businessId) {
        BusinessBrowseVo businessBrowseVo = new BusinessBrowseVo();
        //查询项目基本信息
        BusinessInfo businessInfo = businessInfoMapper.selectBusinessInfoById(businessId);
        BeanUtil.copyProperties(businessInfo, businessBrowseVo);
        //商务团队
        businessBrowseVo.setTeam(businessUserMapper.selectCreatorByBusinessId(businessId));
        //查询项目标签
        businessBrowseVo.setLabelList(businessLabelMapper.selectBusinessLabelList(new BusinessLabel(businessId)).stream().map(p -> p.getLabel()).collect(Collectors.toList()));
        //相关数据统计
        BusinessBrowseVo total = businessInfoMapper.selectTotal(businessId);
        businessBrowseVo.setBacklogCount(total.getBacklogCount());
        businessBrowseVo.setContactsCount(total.getContactsCount());
        businessBrowseVo.setFollowRecordCount(total.getFollowRecordCount());
        businessBrowseVo.setRelateCompanyCount(total.getRelateCompanyCount());
        //资料文档统计
        businessBrowseVo.setFileCount(FileUtils.getAllFileNames(RuoYiConfig.getProfile()+businessId).size());
        return businessBrowseVo;
    }

    @Override
    public List<String> selectProjectName(BusinessListDto dto) {
        return businessInfoMapper.selectProjectName(dto);
    }

    @Override
    public AjaxResult batchUpload(MultipartFile file) {
        //获取当前登录用户id
        Long userId = SecurityUtils.getLoginUser().getUserId();
//        Long userId = 103L;
        if (userId == null) return AjaxResult.error("请登录");
        int row = 3;//起始行数
        int rowSuccess = 0;//成功条数
        Integer errorCount = 0;//失败条数
        List<String> result = new LinkedList();//导入结果汇总
        List<BusinessExcelDto> businessInfoList = readBusinessInfoExcel.getExcelInfo(file);
        for (BusinessExcelDto businessInfo : businessInfoList) {
            //查询已有的项目名称
            Integer count = businessInfoMapper.isRepetitionProjectName(businessInfo.getProjectName(), userId.intValue());
            row++;
            if (count > 0) {
                //如果存在，跳过该项目，不保存
                result.add("第" + row + "行的" + businessInfo.getProjectName() + "的项目已存在,跳过该项目，保存下一条");
                errorCount++;
            } else {
                //保存到数据库
                BusinessAddDto businessAddDto = new BusinessAddDto();
                BeanUtil.copyProperties(businessInfo, businessAddDto);
                businessAddDto.setUserId(userId.intValue());
                businessAddDto.setCompanyId(0);
                AjaxResult add = insertBusinessInfo(businessAddDto);
                if (add.get("code").equals(HttpStatus.SUCCESS)) rowSuccess++;
            }
        }
        result.add("导入项目成功条数" + rowSuccess);
        result.add("导入项目失败条数" + errorCount);
        return errorCount == businessInfoList.size() ? AjaxResult.error(String.join(",", result)) : AjaxResult.success(String.join(",", result));
    }

    /**
     * 新增项目详情
     *
     * @param dto 项目详情
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertBusinessInfo(BusinessAddDto dto) {
        //新增前查询是否已存在
        int count = businessInfoMapper.isRepetitionProjectName(dto.getProjectName(), dto.getUserId());
        if (count > 0) return AjaxResult.error("项目名称已存在");
        //新增项目主信息
        BusinessInfo businessInfo = new BusinessInfo();
        BeanUtil.copyProperties(dto, businessInfo);
        businessInfo.setConstructionUnit(dto.getOwnerCompany());
        int addBusiness = businessInfoMapper.insertBusinessInfo(businessInfo);
        if (addBusiness > 0) {
            //获取登陆用户的部门id
            Long deptId = SecurityUtils.getLoginUser().getDeptId();
//            Long deptId = 100l;
            //新增用户-项目关系信息
            int addbusinessUser = businessUserMapper.insertBusinessUser(new BusinessUser(businessInfo.getId(), deptId.intValue(), dto.getUserId(), 1));
            return addbusinessUser > 0 ? AjaxResult.success() : AjaxResult.error();
        }
        return AjaxResult.error();

    }

    /**
     * 修改项目详情
     *
     * @param businessInfo 项目详情
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBusinessInfo(BusinessInfo businessInfo) {
        if (StringUtils.isNotEmpty(businessInfo.getConstructionPhone()) && StringUtils.isNotEmpty(businessInfo.getSupervisorPhone())) {
            if (!CheckUtils.isPhone(businessInfo.getConstructionPhone()) || !CheckUtils.isPhone(businessInfo.getSupervisorPhone()))
                throw new BaseException("500", "请输入正确的手机号码");
        }
        businessInfo.setUpdateTime(DateUtils.getNowDate());
        return businessInfoMapper.updateBusinessInfo(businessInfo);
    }

    /**
     * 批量删除项目详情
     *
     * @param ids 需要删除的项目详情主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBusinessInfoByIds(Long[] ids) {
        return businessInfoMapper.deleteBusinessInfoByIds(ids);
    }

    /**
     * 删除项目详情信息
     *
     * @param id 项目详情主键
     * @return 结果
     */
    @Override
    public int deleteBusinessInfoById(Long id) {
        return businessInfoMapper.deleteBusinessInfoById(id);
    }

    /**
     * 查询项目数量
     *
     * @param status     项目状态
     * @param customerId 客户id
     * @return 项目数量
     */
    @Override
    public int selectCountByStatusAndCustomerId(Integer status, String customerId) {
        return businessInfoMapper.selectCountByStatusAndCustomerId(status, customerId);
    }

    @Override
    public List<CustomerBusinessListVo> selectCustomerBusinessList(CustomerBusinessSearchDto dto) {
        return businessInfoMapper.selectCustomerBusinessList(dto);
    }
}
