package com.dsk.jsk.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dsk.common.core.domain.R;
import com.dsk.system.utils.DskOpenApiUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业相关通用服务
 *
 * @author lcl
 * @create 2023/8/30
 */
@Service
public class EnterpriseCommonService {

    private static final Logger log = LoggerFactory.getLogger(EnterpriseCommonService.class);

    @Autowired
    private DskOpenApiUtil dskOpenApiUtil;

    public R getUipId(String companyName) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("companyName", companyName);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/enterprise/getUipId", params);
        return BeanUtil.toBean(map, R.class);
    }

    public R getUipIdByCid(List<Integer> body) throws Exception {
        if (CollectionUtils.isEmpty(body)) return R.ok();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("ids", body);
        Map<String, Object> map = dskOpenApiUtil.requestBody("/operate/enterprise/getUipIdByCid", paramMap);
        return BeanUtil.toBean(map, R.class);
    }

    //企业uipId
    public String getUipIdByCompanyNameOrCompanyId(String companyName, Integer companyId) {
        try {
            String uipId = null;
            if (!ObjectUtil.isEmpty(companyId)) {
                R res = this.getUipIdByCid(Collections.singletonList(companyId));
                if (!ObjectUtils.isEmpty(res.getData())) {
                    List<Map<String, Object>> data = (List<Map<String, Object>>) res.getData();
                    uipId = MapUtil.getStr(BeanUtil.beanToMap(data.get((0))), "uipId");
                }
            }
            if (ObjectUtil.isEmpty(uipId)) {
                R res = this.getUipId(companyName);
                if (!ObjectUtils.isEmpty(res.getData())) {
                    uipId = MapUtil.getStr(BeanUtil.beanToMap(res.getData()), "uipId");
                }
            }
            return uipId;
        } catch (Exception e) {
            log.debug("获取企业uipId错误！error：{}", e.getMessage());
        }
        return null;
    }
}
