package com.netwisd.base.main;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.dozermapper.core.Mapper;
import com.netwisd.base.main.dto.HbMdmOrgDto;
import com.netwisd.base.main.dto.MdmHbytOrgDto;
import com.netwisd.base.main.entity.Dept;
import com.netwisd.base.main.service.DeptService;
import com.netwisd.base.main.service.HbMdmOrgService;
import com.netwisd.common.core.exception.IncloudException;
import com.netwisd.common.core.util.DozerUtils;
import com.netwisd.pojo.mdm.constants.OrgTypeEnum;
import com.netwisd.pojo.mdm.dto.MdmOrgDto;
import com.netwisd.util.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SpringBootTest
@Slf4j
public class OrgSyncDataTest {

    private HttpClient httpClient = HttpClientBuilder.create().build();

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    private HbMdmOrgService mdmOrgService;

    @Autowired
    private DeptService deptService;

    @Test
    public void doTest() {
        syncHbytOrgInfoByDb();
    }

    /**
     * 读取数据库信息，同步组织信息
     */
    public void syncHbytOrgInfoByDb() {
        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        List<Dept> orgList = deptService.getBaseMapper().selectList(queryWrapper);
        Map<String, List<Dept>> orgMap = orgList.stream().collect(Collectors.groupingBy(Dept::getParentCode));
        HbMdmOrgDto mdmOrgDto = new HbMdmOrgDto();
        mdmOrgDto.setOrgId(0L);
        mdmOrgDto.setOrgCode("0");
        mdmOrgDto.setOrgName("root");
        mdmOrgDto.setParentId(-1L);
        mdmOrgDto.setParentName("root");
        mdmOrgDto.setOrgType(OrgTypeEnum.ORG.getCode());
        loopOrgInfoByDb(mdmOrgDto, orgMap, "0");
        //saveOrg(mdmOrgDto); //保存数据前org表中要内置一条root
        log.debug("同步机构信息完成！");
    }

    public static void loopOrgInfoByDb(HbMdmOrgDto mdmOrgDto, Map<String, List<Dept>> orgMap, String parentCode) {
        if (StringUtils.isNotEmpty(parentCode)) {
            List<Dept> tempList = orgMap.get(parentCode);
            if (CollectionUtil.isNotEmpty(tempList)) {
                List<MdmOrgDto> childList = new ArrayList<>();
                for (Dept dept : tempList) {
                    HbMdmOrgDto childOrgDto = new HbMdmOrgDto();
                    Long orgId = IdGenerator.getIdGenerator();
                    childOrgDto.setId(orgId);
                    childOrgDto.setOrgId(orgId);
                    childOrgDto.setOrgCode(dept.getOrgCode());
                    childOrgDto.setOrgName(dept.getDeptName());
                    childOrgDto.setOrgType(OrgTypeEnum.ORG.code);
                    childOrgDto.setOrgLevel(dept.getOrgLevel());
                    childOrgDto.setParentId(mdmOrgDto.getOrgId());
                    childOrgDto.setParentName(mdmOrgDto.getOrgName());
                    childOrgDto.setInstitutionId(orgId);
                    childOrgDto.setInstitutionName(dept.getDeptName());
                    childOrgDto.setIsDirectlyUnder(dept.getJiguanFlag());
                    childOrgDto.setLevel2Code(dept.getLevel2Code());
                    childOrgDto.setLevel3Code(dept.getLevel3Code());
                    childOrgDto.setSort(Integer.valueOf(dept.getOrderNum()));
                    loopOrgInfoByDb(childOrgDto, orgMap, childOrgDto.getOrgCode());
                    childList.add(childOrgDto);
                }
                mdmOrgDto.setChildList(childList);
            }
        }
    }

    //按照层级 递归 保存机构信息
    public void saveOrg(HbMdmOrgDto mdmOrgDto) {
        if (ObjectUtil.isNotEmpty(mdmOrgDto.getChildList())) {
            //机构会引用处理DTO,并修改其中内容，所以重新cp一个，进行保存
            List<HbMdmOrgDto> childList = DozerUtils.mapList(dozerMapper, mdmOrgDto.getChildList(), HbMdmOrgDto.class);
            for (HbMdmOrgDto childDto : childList) {
                addOrUpdateOrg(childDto);
            }

        }
    }

    private void addOrUpdateOrg(HbMdmOrgDto mdmOrgDto) {

    }


    //用json同步组织信息
    public void syncJsonOrgInfo() {
        String path = JsonTest.class.getClassLoader().getResource("zuzhi.json").getPath();
        String s = readJsonFile(path);
        JSONObject jobj11 = JSON.parseObject(s);
        try {
            // 判断返回状态是否为200
            if (ObjectUtil.isNotEmpty(jobj11)) { //  true
                JSONArray datas = jobj11.getJSONArray("data");
                List<MdmHbytOrgDto> list = JSONObject.parseArray(datas.toJSONString(), MdmHbytOrgDto.class);
                Map<String, List<MdmHbytOrgDto>> orgMap = list.stream().collect(Collectors.groupingBy(MdmHbytOrgDto::getParentCode));
                HbMdmOrgDto mdmOrgDto = new HbMdmOrgDto();
                mdmOrgDto.setOrgId(0L);
                mdmOrgDto.setOrgCode("0");
                mdmOrgDto.setOrgName("root");
                mdmOrgDto.setParentId(-1L);
                mdmOrgDto.setParentName("root");
                mdmOrgDto.setOrgType(1);
                loopOrgInfo(mdmOrgDto, orgMap, "0");
                saveOrg(mdmOrgDto); //保存数据前org表中要内置一条root
                log.debug("同步机构信息完成！");
            } else {
                log.error("同步机构数据失败，错误代码：{}");
                throw new IncloudException("同步机构数据失败！");
            }
        } catch (Exception e) {
            log.error("错误:{}", e);
            throw new IncloudException("同步机构数据失败!" + e.getMessage());
        }
    }


    //递归封装机构部门
    public static void loopOrgInfo(MdmOrgDto mdmOrgDto, Map<String, List<MdmHbytOrgDto>> orgMap, String parentCode) {
        if (StringUtils.isNotEmpty(parentCode)) {
            List<MdmHbytOrgDto> tempList = orgMap.get(parentCode);
            if (CollectionUtil.isNotEmpty(tempList)) {
                List<MdmOrgDto> childList = new ArrayList<>();
                for (MdmHbytOrgDto hbytOrgDto : tempList) {
                    MdmOrgDto childOrgDto = new MdmOrgDto();
                    childOrgDto.setId(IdGenerator.getIdGenerator());
                    childOrgDto.setOrgId(Long.valueOf(hbytOrgDto.getOrgCode()));
                    //组织编码
                    childOrgDto.setOrgCode(hbytOrgDto.getOrgCode());
                    //组织名称
                    childOrgDto.setOrgName(hbytOrgDto.getDeptName());
                    //组织节点类型 1组织 2部门  用户这边1生产单位
                    childOrgDto.setOrgType(OrgTypeEnum.DEPT.code);
                    //父级id
                    childOrgDto.setParentId(mdmOrgDto.getOrgId());
                    //父级名称
                    childOrgDto.setParentName(mdmOrgDto.getOrgName());
                    //机构id
                    //_mdmOrgDto.setInstitutionId();
                    //机构名称
                    //_mdmOrgDto.setInstitutionName();
                    //排序字段
                    childOrgDto.setSort(Integer.valueOf(hbytOrgDto.getOrderNum()));
                    log.info("解析到的部门信息：{}", childOrgDto);
                    childList.add(childOrgDto);
                    loopOrgInfo(childOrgDto, orgMap, hbytOrgDto.getOrgCode());
                }
                mdmOrgDto.setChildList(childList);
            }
        }
    }


    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            log.error("错误:{}", e);
            return null;
        }
    }
}
