package com.sky.ioc.service.space.impl;

import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.domain.space.Company;
import com.sky.ioc.entity.domain.space.Department;
import com.sky.ioc.mapper.space.CompanyMapper;
import com.sky.ioc.mapper.space.DepartmentMapper;
import com.sky.ioc.service.space.CompanyService;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    RestTemplateConfig restTemplateConfig;

    @Autowired
    CompanyMapper companyMapper;

    final static  String COMPANY_URL="/api/space/SPACE/siteArea/list";
    @Override
    public ReturnMsg getCompanyData() {
        String url = restTemplateConfig.addBaseUrl(COMPANY_URL)+"?pageNum=1&pageSize=1000";
        // 创建RestTemplate
        RestTemplate restTemplate = restTemplateConfig.build();
        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        // 获取响应对象里的 body 对象
        Map<String, Object> body = responseEntity.getBody();
        // 获取状态码
        Integer code = (Integer)body.get("code");
        // 获取响应信息
        String message = (String)body.get("msg");
        if(code==200){
            ThreadLocalRandom random = ThreadLocalRandom.current();
            ArrayList list = (ArrayList) body.get("rows");
            if(list!=null&&list.size()>0){
                companyMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    Company company = new Company();
                    company.setId((Integer) json.get("id"));
                    company.setCompanyName(String.valueOf(json.get("name")));
                    company.setRegisteredAddress(String.valueOf(json.get("address")));
                    company.setAreaId(Integer.parseInt(String.valueOf(json.get("areaId"))));
                    company.setOfficeId(Integer.parseInt(String.valueOf(json.get("officeId"))));
                    companyMapper.insert(company);
                }
            }
            return ReturnMsg.ok();

        }else{
            log.info("获取项目数据："+message);
            return  ReturnMsg.fail(message);
        }
    }
}
