package com.dsk.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsk.biz.domain.*;
import com.dsk.biz.domain.bo.BusinessAddDto;
import com.dsk.biz.domain.bo.BusinessExcelDto;
import com.dsk.biz.domain.bo.BusinessListDto;
import com.dsk.biz.domain.bo.CustomerBusinessSearchDto;
import com.dsk.biz.domain.vo.*;
import com.dsk.common.annotation.DataColumn;
import com.dsk.common.annotation.DataPermission;
import com.dsk.jsk.service.EnterpriseService;
import com.dsk.biz.mapper.BusinessInfoMapper;
import com.dsk.biz.mapper.BusinessLabelMapper;
import com.dsk.biz.mapper.BusinessRelateCompanyMapper;
import com.dsk.biz.mapper.BusinessUserMapper;
import com.dsk.biz.service.IBusinessInfoService;
import com.dsk.biz.service.ICustomerService;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.exception.base.BaseException;
import com.dsk.common.helper.LoginHelper;
import com.dsk.common.utils.CheckUtils;
import com.dsk.common.utils.DskOpenApiUtil;
import com.dsk.common.utils.JsonUtils;
import com.dsk.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * 项目详情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;
    @Resource
    private BusinessRelateCompanyMapper relateCompanyMapper;
    @Resource
    private DskOpenApiUtil dskOpenApiUtil;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private EnterpriseService enterpriseService;


    /**
     * 查询项目详情
     *
     * @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 TableDataInfo<BusinessListVo> selectBusinessInfoList(BusinessListDto dto, PageQuery pageQuery) {
        dto.setUserId(LoginHelper.getUserId());
        TableDataInfo<BusinessListVo> result = TableDataInfo.build(businessInfoMapper.selectBusinessInfoList(pageQuery.build(), dto));
        if (!CollectionUtils.isEmpty(result.getRows()) && ObjectUtil.isNotEmpty(dto.getProjectName())) {
            for (BusinessListVo vo : result.getRows()) {
                vo.setProjectName(StringUtils.markInRed(vo.getProjectName(), dto.getProjectName()));
                vo.setOwnerCompany(StringUtils.markInRed(vo.getOwnerCompany(), dto.getProjectName()));
            }
        }
        return result;
    }


    @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 = LoginHelper.getUserId();
        if (userId == null) throw new BaseException("请登录");
        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 : JsonUtils.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(ShuZhiHuaConfig.getProfile() + businessId).size());
        return businessBrowseVo;
    }

    @Override
    public List<BusinessLikeProjectNameListVo> selectProjectName(BusinessListDto dto) {
//        List<BusinessLikeProjectNameListVo> vos = businessInfoMapper.selectProjectName(dto);
        List<BusinessLikeProjectNameListVo> vos = new ArrayList<>();
        try {
            Map<String, Object> result = dskOpenApiUtil.requestBody("/nationzj/jskBid/news/findByName", toRequestMap(dto));
            if (ObjectUtil.isNotEmpty(result.get("data"))) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) BeanUtil.beanToMap(result.get("data")).get("list");
                if (!CollectionUtils.isEmpty(list)) {
                    for (Map<String, Object> map : list) {
                        BusinessLikeProjectNameListVo vo = new BusinessLikeProjectNameListVo();
                        vo.setProjectName(StringUtils.markInRed(MapUtil.getStr(map, "projectName"), dto.getProjectName()));
                        vo.setCompanyName(MapUtil.getStr(map, "tenderee"));
                        if (null != map.get("projectContractAmount") && ObjectUtil.isNotEmpty(map.get("projectContractAmount"))) {
                            vo.setInvestmentAmount(MapUtil.getDouble(map, "projectContractAmount"));
                        }
//                        vo.setProjectType(MapUtil.getStr(map, "projectCategory"));
                        //项目阶段
                        vo.setProjectStage(MapUtil.getStr(map, "tenderStage"));
                        //项目类别
                        vo.setProjectCategory(MapUtil.getStr(map, "projectCategory"));
                        vos.add(vo);
                    }
                }
            }
        } catch (Exception e) {
            log.error("模糊查询项目名称调用失败！", e);
        }

        return vos;
    }

    private Map<String, Object> toRequestMap(BusinessListDto dto) {
        Map<String, Object> page = new HashMap<>();
        page.put("page", 1);
        page.put("limit", 20);
        Map<String, Object> map = new HashMap<>();
        map.put("keyword", dto.getProjectName());
        map.put("page", page);
        return map;
    }

    @Override
    public AjaxResult batchUpload(MultipartFile file) {
        //获取当前登录用户id
        Long userId = LoginHelper.getUserId();
        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, businessInfo.getOwnerCompany());
            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);
                try {
                    new BusinessInfoServiceImpl().insertBusinessInfo(businessAddDto);
                    rowSuccess++;
                }catch (Exception e){
                    errorCount++;
                }
            }
        }
        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 boolean insertBusinessInfo(BusinessAddDto dto) {
        //新增前查询是否已存在
        int count = businessInfoMapper.isRepetitionProjectName(dto.getProjectName(), dto.getUserId(), dto.getOwnerCompany());
        if (count > 0) throw new ServiceException("项目名称已存在");
        //判断资金Double类型的位数
        if (dto.getInvestmentAmount() != null) {
            int front = CheckUtils.checkIntegerPlaces(dto.getInvestmentAmount());
            int later = CheckUtils.checkDecimalPlaces(dto.getInvestmentAmount());
            if (front > 9) throw new ServiceException("小数点前最多支持9位");
            if (later > 6) throw new ServiceException("小数点后最多支持6位");
        }
        //新增项目主信息
        BusinessInfo businessInfo = new BusinessInfo();
        BeanUtil.copyProperties(dto, businessInfo);

        CustomerVo vo = new CustomerVo();
        if (ObjectUtil.isNotEmpty(dto.getCustomerId())) {
            vo = customerService.info(dto.getCustomerId());
        } else {
            Customer verifyCustomer = customerService.selectByCompanyNameAndUserId(dto.getOwnerCompany());
            if (ObjectUtil.isNotEmpty(verifyCustomer)) {
                BeanUtil.copyProperties(verifyCustomer, vo);
            } else {
                vo.setCompanyName(dto.getOwnerCompany());
                customerService.add(vo);
            }
            businessInfo.setCustomerId(vo.getCustomerId());
        }
        businessInfo.setConstructionUnit(vo.getCompanyName());
        businessInfo.setConstructionUnitUipId(vo.getUipId());
        businessInfo.setConstructionUnitCid(vo.getCompanyId());
        businessInfo.setConstructionPrincipal(vo.getLegalPerson());
        businessInfo.setTenantId(LoginHelper.getTenantId());
        int addBusiness = businessInfoMapper.insertBusinessInfo(businessInfo);
        if (addBusiness > 0) {
            //获取登陆用户的部门id
            //新增用户-项目关系信息
            int addbusinessUser = businessUserMapper.insertBusinessUser(new BusinessUser(businessInfo.getId(), LoginHelper.getDeptId(), dto.getUserId(), 1));
            if (addbusinessUser == 0) {
                throw new ServiceException("项目关系信息添加失败！");
            }
        }

        int i = relateCompanyMapper.insertBusinessRelateCompany(dealwithCustomer(businessInfo));
        if (i == 0) {
            throw new ServiceException("业主单位信息添加失败！");
        }
        return true;

    }

    /**
     * 修改项目详情
     *
     * @param businessInfo 项目详情
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBusinessInfo(BusinessInfo businessInfo) {
        if (ObjectUtil.isEmpty(businessInfo.getId())) {
            throw new BaseException("项目id不能为空！");
        }
        //判断资金Double类型的位数
        if (ObjectUtil.isNotEmpty(businessInfo.getInvestmentAmount())) {
            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", "请输入正确的电话号码");
        }
        //查询企业的城投id和建设库id
        BusinessRelateCompany relateCompany = relateCompanyMapper.selectByProprietor(businessInfo.getId());
        if (ObjectUtil.isNotEmpty(businessInfo.getConstructionUnit())) {
            Map<String, Object> map = enterpriseService.getCidAndUipIdByCompanyName(businessInfo.getConstructionUnit());
            businessInfo.setConstructionUnitUipId(MapUtils.getString(map, "uipId"));
            businessInfo.setConstructionUnitCid(MapUtils.getInteger(map, "companyId"));
            //相关企业
            if (ObjectUtil.isEmpty(relateCompany)) {
                relateCompanyMapper.insertBusinessRelateCompany(dealwithCustomer(businessInfo));
            }
            if (ObjectUtil.isNotEmpty(relateCompany) && !businessInfo.getConstructionUnit().equals(relateCompany.getCompanyName())) {
                relateCompany.setCompanyId(businessInfo.getConstructionUnitCid());
                relateCompany.setCompanyUipId(businessInfo.getConstructionUnitUipId());
                relateCompany.setCompanyName(businessInfo.getConstructionUnit());
                relateCompanyMapper.updateBusinessRelateCompany(relateCompany);
            }

        }
        if (ObjectUtil.isNotEmpty(relateCompany) &&
                (ObjectUtil.isNotEmpty(businessInfo.getConstructionPhone())
                        || ObjectUtil.isNotEmpty(businessInfo.getConstructionPrincipal()))) {
            relateCompany.setPhone(businessInfo.getConstructionPhone());
            relateCompany.setResponsiblePerson(businessInfo.getConstructionPrincipal());
            relateCompanyMapper.updateBusinessRelateCompany(relateCompany);
        }
        return businessInfoMapper.updateBusinessInfo(businessInfo);
    }

    /**
     * 批量删除项目
     * 项目关联的其他所有表数据一并删除
     *
     * @param ids 需要删除的项目详情主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBusinessInfoByIds(Long[] ids) {
        //删除项目详情，用户关联项目，项目工作代办，项目联系人，项目跟进记录，项目标签，项目相关企业
        int deleteBusiness = businessInfoMapper.deleteBusinessInfoByIds(ids);
        //删除项目上传的文件
//        for (Long id : ids) {
//            try {
//                FileUtils.delFolder(ShuZhiHuaConfig.getUploadPath() + id);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return deleteBusiness;
    }

    /**
     * 删除项目详情信息
     *
     * @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 TableDataInfo<CustomerBusinessListVo> selectCustomerBusinessList(CustomerBusinessSearchDto dto, PageQuery pageQuery) {
        return TableDataInfo.build(businessInfoMapper.selectCustomerBusinessList(pageQuery.build(), dto));
    }

    private BusinessRelateCompany dealwithCustomer(BusinessInfo bean) {
        BusinessRelateCompany relateCompany = new BusinessRelateCompany();
        relateCompany.setBusinessId(bean.getId());
        relateCompany.setCompanyId(bean.getConstructionUnitCid());
        relateCompany.setCompanyUipId(bean.getConstructionUnitUipId());
        relateCompany.setCompanyName(bean.getConstructionUnit());
        relateCompany.setPhone(bean.getConstructionPhone());
        relateCompany.setCompanyRole("招采单位");
        relateCompany.setResponsiblePerson(bean.getConstructionPrincipal());
        relateCompany.setIsProprietor(1);
        relateCompany.setRemark("业主单位");
        return relateCompany;
    }
}
