package com.artfess.yhxt.push.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.JsonUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.uc.exception.HotentHttpStatus;
import com.artfess.uc.manager.DemensionManager;
import com.artfess.uc.manager.OrgManager;
import com.artfess.uc.manager.UserManager;
import com.artfess.uc.model.Demension;
import com.artfess.uc.model.Org;
import com.artfess.uc.model.OrgParams;
import com.artfess.uc.model.User;
import com.artfess.uc.params.org.OrgUserVo;
import com.artfess.uc.params.org.OrgVo;
import com.artfess.uc.params.user.UserVo;
import com.artfess.yhxt.push.HttpUtil;
import com.artfess.yhxt.push.service.SynchronizationDataService;
import com.artfess.yhxt.push.vo.YhOrg;
import com.artfess.yhxt.push.vo.YhOrgVo;
import com.artfess.yhxt.push.vo.YhUserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhx
 * @create 2021/11/22
 */
@Service
public class SynchronizationDataServiceImpl implements SynchronizationDataService {
    @Resource
    private OrgManager orgManager;
    @Resource
    private DemensionManager demensionService;
    @Resource
    private UserManager userManager;
    @Override
    public void synchronizationOrg() throws Exception {

        //http://183.64.175.153:28880/user/org/findDeptByOrg?companyCode=10
        JsonNode dataList;
        while (true){
            String json = HttpUtil.get("http://183.64.175.153:28880/user/org/findDeptByOrg?companyCode=10", null, null, 50000, 50000, null);

            JsonNode jsonNode = JsonUtil.toJsonNode(json);
             dataList = jsonNode.get("data");
             if (!"null".equals(dataList)){
                 break;
             }
        }
        String x = dataList.toString();
        System.out.println(x);
        String s = trimEnd(trimStart(x, "["), "]");
        System.out.println(s);

        //养护检查
        YhOrgVo yhOrgVo = JsonUtil.toBean(s, YhOrgVo.class);
        System.out.println(yhOrgVo);

//最外层
        Integer grade = 1;
        Org org = this.getOrg(yhOrgVo.getCode());
        if (org == null) {
            org = new Org();
            //orgManager.saveOrg
            OrgVo orgVo = new OrgVo();
            //纬度ID
            orgVo.setDemId("1258608622670319616");
            //组织code
            orgVo.setCode(yhOrgVo.getCode());
            //等级
            orgVo.setGrade(String.valueOf(grade));
            //name
            orgVo.setName(yhOrgVo.getName());
            orgVo.setParentId("0");
            if (yhOrgVo.getType().equals("1")) {
                orgVo.setOrgKind("ogn");
            } else {
                orgVo.setOrgKind("dept");
            }
            orgManager.addOrg(orgVo);
        } else {
            OrgVo orgVo = new OrgVo();
            //纬度ID
            orgVo.setDemId("1258608622670319616");
            //组织code
            orgVo.setCode(yhOrgVo.getCode());
            //等级
            orgVo.setGrade(String.valueOf(grade));
            //name
            orgVo.setName(yhOrgVo.getName());
            orgVo.setParentId("0");
            if (yhOrgVo.getType().equals("1")) {
                orgVo.setOrgKind("ogn");
            } else {
                orgVo.setOrgKind("dept");
            }
            orgManager.updateOrg(orgVo);
        }
        List<YhOrgVo> children = yhOrgVo.getChildren();
        for (YhOrgVo child : children) {
            this.orgCode(child, grade);
        }

    }

    @Override
    public void synchronizationUser() throws Exception {
        Map<String, Object> params = new HashMap<>();
        Integer pageNo = 1;
        params.put("pageNo", pageNo);
        params.put("pageSize", 200);
        params.put("orgCode", 10);
//正式
        String json = HttpUtil.get("http://183.64.175.153:28880/user/user/page", params,  null, 50000, 50000, null);
//测试
        //        String json = HttpUtil.get("http://36.110.103.178:28881/user/user/page", params, null, 50000, 50000, null);
        JsonNode jsonNode = JsonUtil.toJsonNode(json);
        JsonNode dataList = jsonNode.get("data");
        //总页数
        JsonNode totalPage = dataList.get("totalPage");
        int total = totalPage.intValue();

        //当前页
        JsonNode currentPage = dataList.get("currentPage");
        int current = currentPage.intValue();

        JsonNode result = dataList.get("result");
        List<YhUserVo> yhUserVos = JSONUtil.toList(JSONUtil.parseArray(result.toString()), YhUserVo.class);
        //System.out.println(yhUserVos);
        for (YhUserVo yhUserVo : yhUserVos) {
            // System.out.println(yhUserVo);
            //根据账号去查询
            User user = this.userManager.getByAccount(yhUserVo.getUserCode());
            //查询出已有用户，则进行修改
            if (null != user) {
                UserVo userVo = new UserVo();

                //账号
                userVo.setAccount(yhUserVo.getUserCode());
                userVo.setId(user.getId());
                userVo.setFullname(yhUserVo.getName());
                userVo.setStatus(user.getStatus());
                userVo.setIsDelete("0");
                //密码未同步 todo
                //userVo.setPassword(user.getPassword());
                userVo.setUserType(user.getUserType());
                //修改接口
                this.userManager.updateUser(userVo);
            }
            //没有的用户
            if (null == user) {
                //新增接口
                UserVo userVo = new UserVo();
                userVo.setAccount(yhUserVo.getUserCode());
                userVo.setFullname(yhUserVo.getName());
                userVo.setPassword("P@ssw0rd");
                userVo.setStatus(1);
                userVo.setUserType(2);
                this.userManager.addUser(userVo);
                OrgUserVo orgUserVo = new OrgUserVo();
                orgUserVo.setAccount(yhUserVo.getUserCode());
                orgUserVo.setOrgCode(yhUserVo.getOrgCode());
                this.orgManager.addOrgUser(orgUserVo);
            }
        }

        for (int i = 0; i < total - current; i++) {
            pageNo += 1;
            params.put("pageNo",pageNo);
            json = HttpUtil.get("http://183.64.175.153:28880/user/user/page", params,  null, 50000, 50000, null);
             jsonNode = JsonUtil.toJsonNode(json);
             dataList = jsonNode.get("data");
             result = dataList.get("result");
            yhUserVos = JSONUtil.toList(JSONUtil.parseArray(result.toString()), YhUserVo.class);
             for (YhUserVo yhUserVo : yhUserVos) {
           // System.out.println(yhUserVo);
            //根据账号去查询
            User user = this.userManager.getByAccount(yhUserVo.getUserCode());
            //查询出已有用户，则进行修改
            if (null!=user){
                UserVo userVo = new UserVo();

                //账号
                userVo.setAccount(yhUserVo.getUserCode());
                userVo.setId(user.getId());
                userVo.setFullname(yhUserVo.getName());
                userVo.setStatus(user.getStatus());
                userVo.setIsDelete("0");
                //密码未同步 todo
                userVo.setPassword(user.getPassword());
                userVo.setUserType(user.getUserType());
                //修改接口
                this.userManager.updateUser(userVo);
            }
            //没有的用户
            if (null==user){
                //新增接口
                UserVo userVo = new UserVo();
                userVo.setAccount(yhUserVo.getUserCode());
                userVo.setFullname(yhUserVo.getName());
                userVo.setPassword("P@ssw0rd");
                userVo.setStatus(1);
                userVo.setUserType(2);
                this.userManager.addUser(userVo);
                OrgUserVo orgUserVo = new OrgUserVo();
                orgUserVo.setAccount(yhUserVo.getUserCode());
                orgUserVo.setOrgCode(yhUserVo.getOrgCode());
                this.orgManager.addOrgUser(orgUserVo);
            }
        }
        }


    }

    private void orgCode(YhOrgVo child, Integer grade) throws Exception {
        grade = grade + 1;
        Org org = this.getOrg(child.getCode());
        Org orgParent = this.getOrg(child.getParentCode());
        if (org==null){
            org = new Org();
            //orgManager.saveOrg
            OrgVo orgVo = new OrgVo();
            //纬度ID
            orgVo.setDemId("1258608622670319616");
            //组织code
            orgVo.setCode(child.getCode());
            //等级
            orgVo.setGrade(String.valueOf(grade));
            //name
            orgVo.setName(child.getName());
            orgVo.setParentId(orgParent.getId());
            if (child.getType().equals("1")) {
                orgVo.setOrgKind("ogn");
            } else {
                orgVo.setOrgKind("dept");
            }
            orgManager.addOrg(orgVo);
        } else {
            OrgVo orgVo = new OrgVo();
            //纬度ID
            orgVo.setDemId("1258608622670319616");
            //组织code
            orgVo.setCode(child.getCode());
            //等级
            orgVo.setGrade(String.valueOf(grade));
            //name
            orgVo.setName(child.getName());
            orgVo.setParentId(orgParent.getId());
            if (child.getType().equals("1")) {
                orgVo.setOrgKind("ogn");
            } else {
                orgVo.setOrgKind("dept");
            }
            orgManager.updateOrg(orgVo);
        }

        //子节点
        List<YhOrgVo> children = child.getChildren();
        if (null == children || children.size() == 0) {
            return;
        }
        for (YhOrgVo yhOrgVo : children) {
            this.orgCode(yhOrgVo, grade);
        }


    }

    /*
     * 删除开头字符串
     */
    public static String trimStart(String inStr, String prefix) {
        if (inStr.startsWith(prefix)) {
            return (inStr.substring(prefix.length()));
        }
        return inStr;
    }

    /*
     * 删除末尾字符串
     */
    public static String trimEnd(String inStr, String suffix) {
        if (inStr.endsWith(suffix)) {
            return (inStr.substring(0, inStr.length() - suffix.length()));
        }
        return inStr;
    }


    public Org getOrg(String code) throws Exception {
        if (StringUtils.isEmpty(code)) {
            throw new RuntimeException(HotentHttpStatus.REUIRED.description() + "：组织编码code必填！");
        }
        Org o = this.orgManager.getByCode(code);
        if (BeanUtils.isEmpty(o)) {
            return o;
        }
        o = this.orgManager.get(o.getId());
        String pId = o.getParentId();
        String demId = o.getDemId();
        Demension d = demensionService.get(demId);
        if (d != null && !StringUtil.isEmpty(d.getDemCode())) {
            o.setDemCode(d.getDemCode());
        }
        if ("0".equals(pId) || StringUtil.isEmpty(pId)) {
            o.setParentOrgName(d.getDemName());
        } else {
            o.setParentOrgName(this.orgManager.get(pId).getName());
        }
        List<OrgParams> params = this.orgManager.getOrgParams(o.getCode());
        if (BeanUtils.isNotEmpty(params)) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (OrgParams param : params) {
                map.put(param.getAlias(), param.getValue());
            }
            o.setParams(map);
        }
        return o;
    }
}
