package com.dsk.jsk.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.dsk.common.constant.CacheConstants;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.core.domain.R;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.DskOpenApiUtil;
import com.dsk.common.utils.JsonUtils;
import com.dsk.common.utils.StringUtils;
import com.dsk.jsk.domain.JskCombineBidPageDto;
import com.dsk.jsk.domain.JskCombineCertificateDto;
import com.dsk.jsk.domain.JskCombineCountDto;
import com.dsk.jsk.domain.JskCombineSearchDto;
import com.dsk.jsk.domain.vo.JskCombineBidProjectExportVo;
import com.dsk.jsk.domain.vo.JskCombineWinBidProjectExportVo;
import com.dsk.jsk.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lcl
 * @create 2023/8/7
 */
@Slf4j
@Service
public class JskCombineInfoService {

    @Autowired
    private DskOpenApiUtil dskOpenApiUtil;
    @Autowired
    private EnterpriseService enterpriseService;

    @Resource
    private RedisCache redisCache;

    public TableDataInfo memberList(JskCombineSearchDto dto) throws Exception {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/combine/memberList", BeanUtil.beanToMap(dto, false, false));
        return dskOpenApiUtil.responsePage(map);
    }


    public R groupMemberCount(JskCombineSearchDto dto) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/combine/group/memberCount", BeanUtil.beanToMap(dto, false, false));
        return BeanUtil.toBean(map, R.class);
    }

    public TableDataInfo businessList(JskCombineSearchDto dto) throws Exception {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/project/combine/projectList", BeanUtil.beanToMap(dto, false, false));
        if (!ObjectUtils.isEmpty(map.get("data"))) {
            Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
            if (!ObjectUtils.isEmpty(data.get("list"))) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
                list.parallelStream().forEach(res -> {
                    Integer companyId = MapUtils.getInteger(res, "companyId");
                    String companyName = MapUtils.getString(res, "companyName");
                    res.put("uipId", enterpriseService.getUipIdByCompanyNameOrCompanyId(companyName, companyId));
                    Integer projectUnitId = MapUtils.getInteger(res, "projectUnitId");
                    String projectUnit = MapUtils.getString(res, "projectUnit");
                    res.put("projectUnitUipId", enterpriseService.getUipIdByCompanyNameOrCompanyId(projectUnit, projectUnitId));
                });
            }
        }
        return dskOpenApiUtil.responsePage(map);
    }

    public TableDataInfo certificateList(JskCombineSearchDto dto) throws Exception {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/combine/certificateList", BeanUtil.beanToMap(dto, false, false));
        return dskOpenApiUtil.responsePage(map);
    }

    public TableDataInfo menberCertificateList(JskCombineCertificateDto dto) throws Exception {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/combine/member/certificateList", BeanUtil.beanToMap(dto, false, false));
        return dskOpenApiUtil.responsePage(map);
    }

    public R groupCertificateCount(JskCombineSearchDto dto) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/combine/group/certificateCount", BeanUtil.beanToMap(dto, false, false));
        return BeanUtil.toBean(map, R.class);
    }

    public AjaxResult index(Map<String,Object> object) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/groupCompany", object);
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprse() {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse", new JSONObject());
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprseChild() {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse/child", new JSONObject());
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprseChildPage(Map<String,Object> object) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse/child/page", object);
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprseLocal(Map<String,Object> object) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse/local", object);
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprseLocalPage(Map<String,Object> object) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse/local/page", object);
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprseSocial() {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse/social", new JSONObject());
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public AjaxResult centralEnterprseSocialPage(Map<String,Object> object) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/enterprice/centralEnterprse/social/page", object);
        return BeanUtil.toBean(map, AjaxResult.class);
    }

    public List<JskCombineWinBidProjectExportVo> exportWinBid(JskCombineSearchDto dto) {
        if (ObjectUtils.isEmpty(dto.getPageSize())) throw new ServiceException("导出条数不能为空！");
        if (dto.getPageSize() > 2000) dto.setPageSize(2000);
        dto.setPageNum(1);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/project/combine/projectList", BeanUtil.beanToMap(dto, false, false));
        if (ObjectUtils.isEmpty(map.get("data"))) throw new ServiceException("导出失败，系统错误！");
        Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
        if (ObjectUtils.isEmpty(data.get("list"))) throw new ServiceException("导出失败，系统错误！");

        List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
        if (ObjectUtils.isEmpty(list)) throw new ServiceException("导出失败，无数据导出！");
        List<JskCombineWinBidProjectExportVo> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JskCombineWinBidProjectExportVo vo = new JskCombineWinBidProjectExportVo();
            vo.setId(i + 1);
            vo.setBidTime(MapUtil.getDate(list.get(i),"bidTime"));
            if(ObjectUtils.isEmpty(dto.getSearchValue())){
                vo.setCompanyName(MapUtil.getStr(list.get(i),"companyName"));
                vo.setProjectName(MapUtil.getStr(list.get(i),"projectName"));
            }else {
                vo.setCompanyName(StringUtils.removeRed(MapUtil.getStr(list.get(i),"companyName")));
                vo.setProjectName(StringUtils.removeRed(MapUtil.getStr(list.get(i),"projectName")));
            }
            vo.setStockPercent(MapUtil.getDouble(list.get(i),"stockPercent"));
            vo.setMemberLevel(MapUtil.getStr(list.get(i),"memberLevel"));
            vo.setBidAmount(MapUtil.getDouble(list.get(i),"bidAmount"));
            vo.setAddress(MapUtil.getStr(list.get(i),"address"));
            vo.setBoundType(MapUtil.getStr(list.get(i),"boundType"));
            vo.setProjectType(MapUtil.getStr(list.get(i),"projectType"));
            vo.setProjectUnit(MapUtil.getStr(list.get(i),"projectUnit"));
            result.add(vo);
        }
        return result;
    }


    public List<JskCombineBidProjectExportVo> exportBid(JskCombineBidPageDto dto) {
        if (ObjectUtils.isEmpty(dto.getPageSize())) throw new ServiceException("导出条数不能为空！");
        if (dto.getPageSize() > 2000) dto.setPageSize(2000);
        dto.setPageNum(1);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/project/combine/tenderList", BeanUtil.beanToMap(dto, false, false));
        if (ObjectUtils.isEmpty(map.get("data"))) throw new ServiceException("导出失败，系统错误！");
        Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
        if (ObjectUtils.isEmpty(data.get("list"))) throw new ServiceException("导出失败，系统错误！");

        List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
        if (ObjectUtils.isEmpty(list)) throw new ServiceException("导出失败，无数据导出！");
        List<JskCombineBidProjectExportVo> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JskCombineBidProjectExportVo vo = new JskCombineBidProjectExportVo();
            vo.setId(i + 1);
            vo.setIssueTime(MapUtil.getDate(list.get(i),"issueTime"));
            if(ObjectUtils.isEmpty(dto.getKeys())){
                vo.setTenderee(MapUtil.getStr(list.get(i),"tenderee"));
                vo.setProjectName(MapUtil.getStr(list.get(i),"projectName"));
                vo.setAgency(MapUtil.getStr(list.get(i),"agency"));
            }else {
                vo.setTenderee(StringUtils.removeRed(MapUtil.getStr(list.get(i),"tenderee")));
                vo.setProjectName(StringUtils.removeRed(MapUtil.getStr(list.get(i),"projectName")));
                vo.setAgency(StringUtils.removeRed(MapUtil.getStr(list.get(i),"agency")));
            }
            vo.setStockPercent(MapUtil.getDouble(list.get(i),"stockPercent"));
            vo.setMemberLevel(MapUtil.getStr(list.get(i),"memberLevel"));
            vo.setBidAmount(MapUtil.getDouble(list.get(i),"bidAmount"));
            vo.setAddress(MapUtil.getStr(list.get(i),"address"));
            vo.setSubjectMatter(MapUtil.getStr(list.get(i),"subjectMatter"));
            vo.setProjectType(MapUtil.getStr(list.get(i),"projectType"));

            result.add(vo);
        }
        return result;
    }

    public TableDataInfo bidPage(JskCombineBidPageDto dto) throws Exception {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/nationzj/project/combine/tenderList", BeanUtil.beanToMap(dto, false, false));
        if (ObjectUtil.isNotEmpty(map.get("data"))) {
            Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
            if (!ObjectUtils.isEmpty(data.get("list"))) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
                list.parallelStream().forEach(res -> {
                    //招标企业
                    Integer tendereeId = MapUtils.getInteger(res, "tendereeId");
                    String tenderee = MapUtils.getString(res, "tenderee");
                    // 代理机构名称
                    Integer agencyId = MapUtils.getInteger(res, "agencyId");
                    String agency = MapUtils.getString(res, "agency");
                    res.put("tendereeUipId", enterpriseService.getUipIdByCompanyNameOrCompanyId(tenderee, tendereeId));
                    res.put("agencyUipId", enterpriseService.getUipIdByCompanyNameOrCompanyId(agency, agencyId));
                });
            }
        }
        return dskOpenApiUtil.responsePage(map);
    }

    /***
     *@Description: 获取集团logo
     *@Param:
     *@return: com.dsk.common.core.domain.R
     *@Author: Dgm
     *@date: 2023/9/12 16:05
     */
    public R combineMemberLogo(Map<String,Object> object) {
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/enterprise/combineMemberLogo", object);
        return BeanUtil.toBean(map, R.class);
    }

    /***
     *@Description: 集团统计展示调用允许
     *@Param:
     *@return: com.dsk.common.core.domain.R
     *@Author: Dgm
     *@date: 2023/9/12 16:05
     */
    public R memberCount(JskCombineCountDto dto) {
        String redisKey = CacheConstants.DATA_COMBINE + dto.getCombineId();
        if (ObjectUtil.isNotEmpty(redisKey)) {
            Map<String, Object> cacheMap = JsonUtils.parseObject(redisCache.getCacheObject(redisKey), Map.class);
            if (MapUtils.isNotEmpty(cacheMap)) {
                return R.ok(cacheMap);
            }
        }
        dto.setQualificationType(209);
        dto.setEndTime(DateUtil.formatDate(new Date()));
        Map<String, Object> paramsMap = BeanUtil.beanToMap(dto, false, false);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/combine/memberCount", paramsMap);
        if (ObjectUtil.isNotEmpty(map.get("data"))) {
            Map<String, Object> data = BeanUtil.beanToMap(map.get("data"));
            data.put("performance", businessCount(paramsMap));
            map.put("data", data);
            redisCache.setCacheObject(redisKey, JsonUtils.toJsonString(data), 24, TimeUnit.HOURS);
        }
        return BeanUtil.toBean(map, R.class);
    }

    public Integer businessCount(Map<String, Object> paramsMap) {
        Integer performance = 0;
        Map<String, Object> resMap = dskOpenApiUtil.requestBody("/nationzj/project/combine/projectList", paramsMap);
        Integer code = MapUtils.getInteger(resMap, "code", 300);
        Map data = MapUtils.getMap(resMap, "data", null);
        if (code.equals(HttpStatus.OK.value())) {
            performance = MapUtils.getInteger(data, "totalCount", 0);
        }
        return performance;
    }
}
