package com.dsk.system.service.impl;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.BusinessRelateCompany;
import com.dsk.common.core.domain.entity.BusinessUser;
import com.dsk.common.exception.base.BaseException;
import com.dsk.common.utils.DateUtils;
import com.dsk.common.utils.SecurityUtils;
import com.dsk.system.domain.BusinessExcelDto;
import com.dsk.system.domain.BusinessAddDto;
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 lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目详情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) {
        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.setLabelList(businessLabelMapper.selectBusinessLabelList(new BusinessLabel(businessId)).stream().map(p -> p.getLabel()).collect(Collectors.toList()));
        //查询关键企业
        businessBrowseVo.setRelateCompany(businessRelateCompanyMapper.selectBusinessRelateCompanyList(new BusinessRelateCompany(businessId)));
        BusinessBrowseVo total = businessInfoMapper.selectTotal(businessId);
        businessBrowseVo.setBacklogCount(total.getBacklogCount());
        businessBrowseVo.setContactsCount(total.getContactsCount());
        businessBrowseVo.setFollowRecordCount(total.getFollowRecordCount());
        businessBrowseVo.setRelateCompanyCount(total.getRelateCompanyCount());
        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);
        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));
            //新增项目-关联企业信息
            int addRelateCompany = businessRelateCompanyMapper.insertBusinessRelateCompany(new BusinessRelateCompany(businessInfo.getId(), dto.getCompanyId(), dto.getOwnerCompany(), "业主"));
            return addbusinessUser > 0 && addRelateCompany > 0 ? AjaxResult.success() : AjaxResult.error();
        }
        return AjaxResult.error();

    }

    /**
     * 修改项目详情
     *
     * @param businessInfo 项目详情
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBusinessInfo(BusinessInfo businessInfo) {
        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);
    }
}
