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

import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.domain.space.Building;
import com.sky.ioc.entity.domain.space.Department;
import com.sky.ioc.mapper.space.BuildingMapper;
import com.sky.ioc.mapper.space.DepartmentMapper;
import com.sky.ioc.service.space.DepartmentService;
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 DepartmentServiceImpl implements DepartmentService {

    @Autowired
    RestTemplateConfig restTemplateConfig;

    @Autowired
    DepartmentMapper departmentMapper;

    final static  String BUILDING_URL="/api/space/SPACE/departmentOfficeArea/list";

    @Override
    public ReturnMsg getDepartmentData() {
        String url = restTemplateConfig.addBaseUrl(BUILDING_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){
                departmentMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    Department department = new Department();
                    department.setId((Integer) json.get("id"));
                    department.setName(String.valueOf(json.get("name")));
                    department.setFullName(String.valueOf(json.get("fullName")));
                    department.setSort(Integer.parseInt(String.valueOf(json.get("sort"))));
                    department.setOriId(String.valueOf(json.get("oriId")));
                    department.setParentId(String.valueOf(json.get("parentId")));
                    departmentMapper.insert(department);
                }
            }
            return ReturnMsg.ok();

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