package com.dsk.search.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson2.JSONObject;
import com.dsk.acc.openapi.client.util.CommonUtils;
import com.dsk.biz.utils.ExcelUtils;
import com.dsk.common.constant.Constants;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.system.utils.DskOpenApiUtil;
import com.dsk.component.UploadComponent;
import com.dsk.jsk.domain.EnterpriseUipSearchBody;
import com.dsk.jsk.domain.JskCombineSearchDto;
import com.dsk.jsk.domain.bo.UrbanInvestmentPlatformDto;
import com.dsk.jsk.domain.vo.UrbanInvestmentExportVo;
import com.dsk.system.domain.SysUserFileRecord;
import com.dsk.system.service.ISysUserFileRecordService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lc
 * @date 2023/11/20 15:21
 */
@Service
public class ExportService {

    @Autowired
    private ISysUserFileRecordService sysUserFileRecordService;
    @Value("${dsk.exportBackUrl}")
    private String EXPORT_BACK_URL;
    @Autowired
    private DskOpenApiUtil dskOpenApiUtil;
    @Autowired
    private UploadComponent uploadComponent;

    //企业基本信息导出
    public AjaxResult enterpriseInfoExport(JSONObject object) {
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setFileName(object.get("exportExeclName").toString().concat(Constants.SUFFIX_XLSX));
        fileRecord.setType(1);
        //生成中
        fileRecord.setStatus(2);
        fileRecord.setRemark("企业基本信息导出");
        Long fileId = sysUserFileRecordService.exportAdd(fileRecord);
        object.put("exportUniqueCode",fileId);
        //回调函数
        object.put("exportBackUrl",EXPORT_BACK_URL);
        dskOpenApiUtil.requestBody("/operate/export/enterprise", object);
        return AjaxResult.success();
    }

    //企业资质导出
    public AjaxResult enterpriseAptitudeExport(JSONObject object) {
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setFileName(object.get("exportExeclName").toString().concat(Constants.SUFFIX_XLSX));
        fileRecord.setType(1);
        //生成中
        fileRecord.setStatus(2);
        fileRecord.setRemark("企业资质信息导出");
        Long fileId = sysUserFileRecordService.exportAdd(fileRecord);
        object.put("exportUniqueCode",fileId);
        //回调函数
        object.put("exportBackUrl",EXPORT_BACK_URL);
        dskOpenApiUtil.requestBody("/operate/export/aptitude", object);
        return AjaxResult.success();
    }

    //重点项目清单
    public AjaxResult importantExport(JSONObject object) {
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setFileName(object.get("exportExeclName").toString().concat(Constants.SUFFIX_XLSX));
        fileRecord.setType(1);
        //生成中
        fileRecord.setStatus(2);
        fileRecord.setRemark("重点项目清单导出");
        Long fileId = sysUserFileRecordService.exportAdd(fileRecord);
        object.put("exportUniqueCode",fileId);
        //回调函数
        object.put("exportBackUrl",EXPORT_BACK_URL);
        dskOpenApiUtil.requestBody("/operate/export/important", object);
        return AjaxResult.success();
    }

    //集团成员导出
    public AjaxResult memberListExport(JskCombineSearchDto dto) {
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setFileName(dto.getExportExeclName().concat(Constants.SUFFIX_XLSX));
        fileRecord.setType(1);
        //生成中
        fileRecord.setStatus(2);
        fileRecord.setRemark("集团成员列表导出");
        Long fileId = sysUserFileRecordService.exportAdd(fileRecord);
        dto.setExportUniqueCode(fileId.toString());
        //回调函数
        dto.setExportBackUrl(EXPORT_BACK_URL);
        dskOpenApiUtil.requestBody("/operate/export/member", BeanUtil.beanToMap(dto, false, false));
        return AjaxResult.success();
    }

    //集团中标业绩导出
    public AjaxResult exportWinBid(JskCombineSearchDto dto) {
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setFileName(dto.getExportExeclName().concat(Constants.SUFFIX_XLSX));
        fileRecord.setType(1);
        //生成中
        fileRecord.setStatus(2);
        fileRecord.setRemark("集团中标业绩导出");
        Long fileId = sysUserFileRecordService.exportAdd(fileRecord);
        dto.setExportUniqueCode(fileId.toString());
        //回调函数
        dto.setExportBackUrl(EXPORT_BACK_URL);
        dskOpenApiUtil.requestBody("/operate/export/combineBid", BeanUtil.beanToMap(dto, false, false));
        return AjaxResult.success();
    }

    //集团招标业绩
    public AjaxResult exportBid(JskCombineSearchDto dto) {
        SysUserFileRecord fileRecord = new SysUserFileRecord();
        fileRecord.setFileName(dto.getExportExeclName().concat(Constants.SUFFIX_XLSX));
        fileRecord.setType(1);
        //生成中
        fileRecord.setStatus(2);
        fileRecord.setRemark("集团招标业绩导出");
        Long fileId = sysUserFileRecordService.exportAdd(fileRecord);
        dto.setExportUniqueCode(fileId.toString());
        //回调函数
        dto.setExportBackUrl(EXPORT_BACK_URL);
        dskOpenApiUtil.requestBody("/operate/export/combine/tender", BeanUtil.beanToMap(dto, false, false));
        return AjaxResult.success();
    }

    public AjaxResult uipSerachExport(EnterpriseUipSearchBody pageDto) {
        // 分页参数
        pageDto.setPageNum(1);
        if (null==pageDto.getPageSize()||pageDto.getPageSize()>=2000){
            pageDto.setPageSize(2000);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/export/search/urbanInvestment", BeanUtil.beanToMap(pageDto, false, false));
        Integer code = MapUtils.getInteger(map, "code", 300);
        if (HttpStatus.OK.value() != code) {
            throw new RuntimeException();
        }
        List<Object> list = CommonUtils.assertAsArray(MapUtils.getObject(map, "data", ""));
        int i = 1;
        List<UrbanInvestmentExportVo> resultList = new ArrayList<>();
        for (Object obj : list) {
            UrbanInvestmentExportVo vo = new UrbanInvestmentExportVo();
            Map<String, Object> dataMap = CommonUtils.assertAsMap(obj);
            vo.setId(i++);
            vo.setCompanyName(MapUtil.getStr(dataMap, "companyName"));

            StringBuilder domicile = new StringBuilder();
            if (null != dataMap.get("province")) {
                domicile.append(MapUtil.getStr(dataMap,"province"));
            }
            if (null != dataMap.get("city")) {
                domicile.append(MapUtil.getStr(dataMap,"city"));
            }
            if (null != dataMap.get("area")) {
                domicile.append(MapUtil.getStr(dataMap,"area"));
            }
            if (domicile.length()>0){
                vo.setDomicile(domicile.toString());
            }
            //招标数量
            vo.setBiddingCount(MapUtil.getInt(dataMap, "biddingCount"));
            //城投拿地
            vo.setLandInfoCount(MapUtil.getInt(dataMap, "landInfoCount"));
            //供应商
            vo.setSupplierCount(MapUtil.getInt(dataMap, "supplierCount"));
            //债卷余额
            vo.setCreditBalance(MapUtil.getDouble(dataMap, "creditBalance"));
            //主体评级
            vo.setBratingSubjectLevel(MapUtil.getStr(dataMap, "bratingSubjectLevel"));
            //行政级别
            vo.setUipExecutiveLevel(MapUtil.getStr(dataMap, "uipExecutiveLevel"));
            //股东背景
            vo.setShareholderBg(MapUtil.getStr(dataMap, "shareholderBg"));
            //股权关系
            vo.setEquityRelationship(MapUtil.getStr(dataMap, "equityRelationship"));
            //平台重要性
            vo.setPlatformImportance(MapUtil.getStr(dataMap, "platformImportance"));
            //城投业务类型
            vo.setUipBusinessType(MapUtil.getStr(dataMap, "uipBusinessType"));
            //实控人
            vo.setActualController(MapUtil.getStr(dataMap, "actualController"));
            //最新报告期
            vo.setLatestReportPeriod(MapUtil.getDate(dataMap, "latestReportPeriod"));
            //总资产
            vo.setTotalAssets(MapUtil.getDouble(dataMap, "totalAssets"));
            //归母净资产
            vo.setBelongNetAssets(MapUtil.getDouble(dataMap, "belongNetAssets"));
            resultList.add(vo);
        }
        String title = "查城投平台导出明细";
        if (null!=pageDto.getExportExeclName()){
            title = pageDto.getExportExeclName();
        }
        ExcelUtils<UrbanInvestmentExportVo> util = new ExcelUtils<>(UrbanInvestmentExportVo.class);
        ByteArrayOutputStream ba = util.exportExcel(resultList, "查城投平台", title, true);
        uploadComponent.upload(title, ba, Constants.SUFFIX_XLSX, Constants.CONTENT_TYPE_XLSX);
        return AjaxResult.success();
    }

    public AjaxResult export(UrbanInvestmentPlatformDto pageDto) {
        // 分页参数
        pageDto.setPageNum(1);

        if (null==pageDto.getPageSize()||pageDto.getPageSize()>=2000){
            pageDto.setPageSize(2000);
        }
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/export/urbanInvestment", BeanUtil.beanToMap(pageDto, false, false));
        Integer code = MapUtils.getInteger(map, "code", 300);
        if (HttpStatus.OK.value() != code) {
            throw new RuntimeException();
        }
        List<Object> list = CommonUtils.assertAsArray(MapUtils.getObject(map, "data", ""));
        int i = 1;
        List<UrbanInvestmentExportVo> resultList = new ArrayList<>();
        for (Object obj : list) {
            UrbanInvestmentExportVo vo = new UrbanInvestmentExportVo();
            Map<String, Object> dataMap = CommonUtils.assertAsMap(obj);
            vo.setId(i++);
            vo.setCompanyName(MapUtil.getStr(dataMap, "companyName"));

            StringBuilder domicile = new StringBuilder();
            if (null != dataMap.get("province")) {
                domicile.append(MapUtil.getStr(dataMap,"province"));
            }
            if (null != dataMap.get("city")) {
                domicile.append(MapUtil.getStr(dataMap,"city"));
            }
            if (null != dataMap.get("area")) {
                domicile.append(MapUtil.getStr(dataMap,"area"));
            }
            if (domicile.length()>0){
                vo.setDomicile(domicile.toString());
            }
            //招标数量
            vo.setBiddingCount(MapUtil.getInt(dataMap, "biddingCount"));
            //城投拿地
            vo.setLandInfoCount(MapUtil.getInt(dataMap, "landInfoCount"));
            //供应商
            vo.setSupplierCount(MapUtil.getInt(dataMap, "supplierCount"));
            //债卷余额
            vo.setCreditBalance(MapUtil.getDouble(dataMap, "bondBalance"));
            //主体评级
            vo.setBratingSubjectLevel(MapUtil.getStr(dataMap, "bratingSubjectLevel"));
            //行政级别
            vo.setUipExecutiveLevel(MapUtil.getStr(dataMap, "uipExecutiveLevel"));
            //股东背景
            vo.setShareholderBg(MapUtil.getStr(dataMap, "shareholderBg"));
            //股权关系
            vo.setEquityRelationship(MapUtil.getStr(dataMap, "equityRelationship"));
            //平台重要性
            vo.setPlatformImportance(MapUtil.getStr(dataMap, "platformImportance"));
            //城投业务类型
            vo.setUipBusinessType(MapUtil.getStr(dataMap, "uipBusinessType"));
            //实控人
            vo.setActualController(MapUtil.getStr(dataMap, "actualController"));
            //最新报告期
            vo.setLatestReportPeriod(MapUtil.getDate(dataMap, "latestReportPeriod"));
            //总资产
            vo.setTotalAssets(MapUtil.getDouble(dataMap, "totalAssets"));
            //归母净资产
            vo.setBelongNetAssets(MapUtil.getDouble(dataMap, "belongNetAssets"));
            resultList.add(vo);
        }
        String title = "城投平台导出明细";
        if (null!=pageDto.getExportExeclName()){
            title = pageDto.getExportExeclName();
        }
        ExcelUtils<UrbanInvestmentExportVo> util = new ExcelUtils<>(UrbanInvestmentExportVo.class);
        ByteArrayOutputStream ba = util.exportExcel(resultList, "城投平台", title, true);
        uploadComponent.upload(title, ba, Constants.SUFFIX_XLSX, Constants.CONTENT_TYPE_XLSX);
        return AjaxResult.success();
    }
}
