package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
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.BusinessLabelVo;
import com.dsk.system.domain.vo.BusinessListVo;
import com.dsk.system.mapper.BusinessInfoMapper;
import com.dsk.system.mapper.BusinessLabelMapper;
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.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 项目详情Service业务层处理
 *
 * @author lxl
 * @date 2023-05-17
 */
@Service
@Slf4j
public class BusinessInfoServiceImpl implements IBusinessInfoService {
    @Resource
    private BusinessInfoMapper businessInfoMapper;
    @Resource
    private BusinessUserMapper businessUserMapper;
    @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) {
        BusinessInfo businessInfo =businessInfoMapper.getConstruction(id);
        return ObjectUtil.isEmpty(businessInfo) ? new BusinessInfo() : businessInfo;
    }

    /**
     * 查询项目详情列表
     *
     * @param dto 项目详情
     * @return 项目详情
     */
    @Override
    public List<BusinessListVo> selectBusinessInfoList(BusinessListDto dto) {
        List<BusinessListVo> othersList = new ArrayList<>();
        //userId不传值，就查询全部他人可见项目+自己的
        if (dto.getUserId() == null) {
            Long userId = SecurityUtils.getLoginUser().getUserId();
            if (userId == null) throw new BaseException("请登录");
            dto.setOthers(userId.intValue());
            //查询他人可见项目
            othersList = businessInfoMapper.selectBusinessInfoList(dto);
        }
        dto.setOthers(null);
        //查询自己参与的项目
        List<BusinessListVo> businessList = businessInfoMapper.selectBusinessInfoList(dto);
        businessList.addAll(othersList);
        return businessList;
    }

    @Override
    public BusinessBrowseVo browse(Integer businessId) {
        BusinessBrowseVo businessBrowseVo = new BusinessBrowseVo();
        //查询项目基本信息
        BusinessInfo businessInfo = businessInfoMapper.selectBusinessInfoById(businessId);
        if(ObjectUtil.isNotEmpty(businessInfo)) BeanUtil.copyProperties(businessInfo, businessBrowseVo);
        //商务团队
        businessBrowseVo.setTeam(businessUserMapper.selectCreatorByBusinessId(businessId));
        //查询是否是项目创建人
//        Long userId = SecurityUtils.getLoginUser().getUserId();
//        if (userId == null) throw new BaseException("请登录");
        Long userId = 103l;
        Integer founder = businessUserMapper.selectFounder(businessId, userId);
        businessBrowseVo.setIsFounder(founder == null ? 0 : founder);
        //查询项目标签
        List<BusinessLabel> labels = businessLabelMapper.selectBusinessLabelList(new BusinessLabel(businessId));
        String labelList = CollectionUtil.isEmpty(labels) ? null : JSONObject.toJSONString(BeanUtil.copyToList(labels, BusinessLabelVo.class));
        businessBrowseVo.setLabelList(labelList);
        //相关数据统计
        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);
        if(CollectionUtil.isEmpty(businessInfoList))return AjaxResult.error("文档中无项目信息,请按照模板文档格式上传");
        for (BusinessExcelDto businessInfo : businessInfoList) {
            //查询已有的项目名称
            Integer count = businessInfoMapper.isRepetitionProjectName(businessInfo.getProjectName(), userId.intValue());
            row++;
            if (count > 0) {
                //如果存在，跳过该项目，不保存
//                result.add("第" + row + "行的" + businessInfo.getProjectName() + "的项目已存在,跳过该项目，保存下一条");
                log.info("第" + 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);
        AjaxResult success = AjaxResult.success(String.join(",", result));
        success.put("successCount",rowSuccess);
        return success;
    }

    /**
     * 新增项目详情
     *
     * @param dto 项目详情
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertBusinessInfo(BusinessAddDto dto) {
        //新增前查询是否已存在
        int count = businessInfoMapper.isRepetitionProjectName(dto.getProjectName(), dto.getUserId());
        if (count > 0) return AjaxResult.error("项目名称已存在");
        //判断资金Double类型的位数
        if (dto.getInvestmentAmount() != null) {
            int front = CheckUtils.checkIntegerPlaces(dto.getInvestmentAmount());
            int later = CheckUtils.checkDecimalPlaces(dto.getInvestmentAmount());
            if (front > 9) return AjaxResult.error("小数点前最多支持9位");
            if (later > 6) return AjaxResult.error("小数点后最多支持6位");
        }
        //新增项目主信息
        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) {
        //判断资金Double类型的位数
        if (businessInfo.getInvestmentAmount() != null) {
            int front = CheckUtils.checkIntegerPlaces(businessInfo.getInvestmentAmount());
            int later = CheckUtils.checkDecimalPlaces(businessInfo.getInvestmentAmount());
            if (front > 9) throw new BaseException("500", "小数点前最多支持9位");
            if (later > 6) throw new BaseException("500", "小数点后最多支持6位");
        }
        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);
    }
}
