package com.dsk.system.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.alibaba.fastjson2.JSONObject;
import com.dsk.acc.openapi.client.util.CommonUtils;
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.BusinessRelateCompany;
import com.dsk.common.core.domain.entity.BusinessUser;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.exception.base.BaseException;
import com.dsk.common.utils.*;
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.Customer;
import com.dsk.system.domain.customer.dto.CustomerBusinessSearchDto;
import com.dsk.system.domain.customer.vo.CustomerBusinessListVo;
import com.dsk.system.domain.customer.vo.CustomerVo;
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.BusinessRelateCompanyMapper;
import com.dsk.system.mapper.BusinessUserMapper;
import com.dsk.system.service.IBusinessInfoService;
import com.dsk.system.service.IBusinessRelateCompanyService;
import com.dsk.system.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 项目详情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;


    /**
     * 查询项目详情
     *
     * @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) {
        if (StringUtils.isEmpty(dto.getMinAmount())) dto.setMinAmount("0");
        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("请登录");
        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();
        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);
            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);
                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);

        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());

        int addBusiness = businessInfoMapper.insertBusinessInfo(businessInfo);
        if (addBusiness > 0) {
            //获取登陆用户的部门id
            //新增用户-项目关系信息
            int addbusinessUser = businessUserMapper.insertBusinessUser(new BusinessUser(businessInfo.getId(), SecurityUtils.getDeptId(), dto.getUserId(), 1));
            if (addbusinessUser == 0) {
                throw new ServiceException("项目关系信息添加失败！");
            }
        }

        BusinessRelateCompany relateCompany = dealwithCustomer(vo);
        relateCompany.setBusinessId(businessInfo.getId());
        int i = relateCompanyMapper.insertBusinessRelateCompany(relateCompany);
        if (i == 0) {
            throw new ServiceException("业主单位信息添加失败！");
        }
        return AjaxResult.success();

    }

    /**
     * 修改项目详情
     *
     * @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", "请输入正确的电话号码");
        }
        //查询企业的城投id和建设库id
        Map map = queryUipIdOrCid(businessInfo.getConstructionUnit());
        if (map.containsKey("jskEid")) {
            businessInfo.setConstructionUnitCid(MapUtils.getInteger(map, "jskEid", null));
        } else {
            businessInfo.setConstructionUnitUipId(MapUtils.getString(map, "uipId", null));
            businessInfo.setConstructionUnitCid(MapUtils.getInteger(map, "companyId", null));
        }
        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(RuoYiConfig.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 List<CustomerBusinessListVo> selectCustomerBusinessList(CustomerBusinessSearchDto dto) {
        return businessInfoMapper.selectCustomerBusinessList(dto);
    }

    @Override
    public Map queryUipIdOrCid(String companyName) {
        Map<Object, Object> map = MapUtil.builder().build();
        if (StringUtils.isEmpty(companyName)) return map;
        //查询城投企业
        Map<String, Object> paramMap = MapUtil.<String, Object>builder().put("companyName", companyName).build();
        Map<String, Object> resultMap = dskOpenApiUtil.requestBody("/urbanInvestment/detailsByCompanyName", paramMap);
        Integer code = MapUtils.getInteger(resultMap, "code", 300);
        if (code == HttpStatus.SUCCESS) {
            Map data = MapUtils.getMap(resultMap, "data", null);
            if (data != null) {
                map.put("uipId", MapUtils.getString(data, "uipId", null));
                map.put("companyId", MapUtils.getInteger(data, "companyId", null));
            }
        }
        if (MapUtil.isEmpty(map)) {
            //查村建设库企业
            Map<String, Object> jskParamMap = MapUtil.<String, Object>builder()
                    .put("keyword", companyName)
                    .put("page", MapUtil.<String, Object>builder().put("page", 1).put("limit", 10).build())
                    .build();
            Map<String, Object> jskResultMap = dskOpenApiUtil.requestBody("/enterprise/index", jskParamMap);
            if (MapUtils.getInteger(resultMap, "code", 300).equals(HttpStatus.SUCCESS)) {
                Map data = MapUtils.getMap(jskResultMap, "data", null);
                if (data != null) {
                    List<Object> list = CommonUtils.assertAsArray(MapUtils.getObject(data, "list", ""));
                    if (CollectionUtil.isNotEmpty(list)) {
                        for (Object obj : list) {
                            map.put("jskEid", MapUtils.getInteger(BeanUtil.beanToMap(obj, false, false), "jskEid", null));
                        }
                    }
                }
            }
        }
        return map;
    }


    private BusinessRelateCompany dealwithCustomer(Customer bean) {
        BusinessRelateCompany relateCompany = new BusinessRelateCompany();
        relateCompany.setCompanyId(bean.getCompanyId());
        relateCompany.setCompanyUipId(bean.getUipId());
        relateCompany.setCompanyName(bean.getCompanyName());
        relateCompany.setCompanyRole("业主");
        relateCompany.setResponsiblePerson(bean.getLegalPerson());
        relateCompany.setCompanyType("业主单位");
        return relateCompany;
    }
}
