package com.dcsoft.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.DateUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.domain.SysPeople;
import com.dcsoft.system.domain.SysUserPost;
import com.dcsoft.system.domain.vo.JjDivisionVo;
import com.dcsoft.system.domain.vo.JjStationVo;
import com.dcsoft.system.domain.vo.JjserInfoVo;
import com.dcsoft.system.domain.vo.TreeSelect;
import com.dcsoft.system.domain.vo.TreeSelectVo;
import com.dcsoft.system.service.ISysSyncRuleService;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.dcsoft.system.mapper.SysBranchMapper;
import com.dcsoft.system.domain.SysBranch;
import com.dcsoft.system.service.ISysBranchService;
import com.dcsoft.common.datascope.annotation.DataScope;

/**
 * 部门管理Service业务层处理
 *
 * @author dcsoft
 * @date 2023-03-07
 */
@Slf4j
@Service
public class SysBranchServiceImpl implements ISysBranchService
{
    @Autowired
    private SysBranchMapper sysBranchMapper;

    @Autowired
    private ISysSyncRuleService syncRuleService;

    @Value("${artemis.url}")
    public String url;
    @Value("${artemis.appKey}")
    public String appKey;
    @Value("${artemis.appSecret}")
    public String appSecret;

    private static final String ARTEMIS_PATH = "/artemis";

    /**
     * 查询部门管理
     *
     * @param id 部门管理主键
     * @return 部门管理
     */
    @Override
    public SysBranch selectSysBranchById(String id)
    {
        return sysBranchMapper.selectSysBranchById(id);
    }

    /**
     * 查询部门管理列表
     *
     * @param sysBranch 部门管理
     * @return 部门管理
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysBranch> selectSysBranchList(SysBranch sysBranch)
    {
        return sysBranchMapper.selectSysBranchList(sysBranch);
    }

    /**
     * 新增部门管理
     *
     * @param sysBranch 部门管理
     * @return 结果
     */
    @Override
    public int insertSysBranch(SysBranch sysBranch)
    {
        sysBranch.setCreateTime(DateUtils.getNowDate());
        int i=sysBranchMapper.insertSysBranch(sysBranch);
        //部门增量同步
        //syncRuleService.addDept(sysBranch,"add");
        sysBranch=hkCreateBrach(sysBranch);
        return i;
    }

    private SysBranch hkCreateBrach(SysBranch sysBranch) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/org/batch/add";
        JSONArray list=new JSONArray();
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("clientId",123456789);
        paramMaps.put("orgIndexCode", sysBranch.getId());
        paramMaps.put("orgName", sysBranch.getName() );
        paramMaps.put("parentIndexCode", sysBranch.getParentId() );
        list.add(paramMaps);
        String body = JSON.toJSON(list).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        JSONArray list1= (JSONArray) jsons1.get("successes");
        if(list1.size()>0){
            JSONObject objs= (JSONObject)list1.get(0);
            sysBranch.setId(objs.get("orgIndexCode")+"");
        }
        return sysBranch;

    }

    private SysBranch hkUpdateBrach(SysBranch sysBranch) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/org/single/update";
        JSONArray list=new JSONArray();
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("orgName", sysBranch.getName() );
        paramMaps.put("orgIndexCode", sysBranch.getId() );
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        return sysBranch;

    }

    private String hkDelBrach(String id) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/org/batch/delete";
        JSONArray list=new JSONArray();
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        String[] indexCode=new String[]{id};
        paramMaps.put("indexCodes",indexCode);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);


        return id;

    }

    /**
     * 修改部门管理
     *
     * @param sysBranch 部门管理
     * @return 结果
     */
    @Override
    public int updateSysBranch(SysBranch sysBranch)
    {
        sysBranch.setUpdateTime(DateUtils.getNowDate());
        //部门增量同步
       // syncRuleService.addDept(sysBranch,"update");
        hkUpdateBrach(sysBranch);
        return sysBranchMapper.updateSysBranch(sysBranch);
    }

    /**
     * 批量删除部门管理
     *
     * @param ids 需要删除的部门管理主键
     * @return 结果
     */
    @Override
    public int deleteSysBranchByIds(String[] ids)
    {
        for(String id:ids){
            hkDelBrach(id);
        }
        return sysBranchMapper.deleteSysBranchByIds(ids);
    }

    /**
     * 删除部门管理信息
     *
     * @param id 部门管理主键
     * @return 结果
     */
    @Override
    public int deleteSysBranchById(String id)
    {
        hkDelBrach(id);
        return sysBranchMapper.deleteSysBranchById(id);
    }


    /**
     * 查询部门树结构信息
     *
     * @param sysBranch 部门信息
     * @return 部门树信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<TreeSelectVo> selectBranchTreeList(SysBranch sysBranch)
    {
        List<SysBranch> branchs = sysBranchMapper.selectSysBranchList(sysBranch);
        return buildBranchTreeSelect(branchs);
    }

    @Override
    public List<TreeSelectVo> queryBranchTree(SysBranch space) {
        List<SysBranch> branchs = sysBranchMapper.queryBranchTree();
        return buildBranchTreeSelect(branchs);
    }

    /**
     * 同步部门
     */
    @Override
    public void saveBranchTree(SysBranch space) {
        HttpResponse response;
        if(Constants.ZERO.equals(space.getType())) {
            response = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getOrganization")
                    .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                    .execute();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            response = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getOrganization?ts=" + sdf.format(new Date()))
                    .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                    .execute();
        }
        String body = response.body();
        JSONObject object = JSONObject.parseObject(body);
        List<JjDivisionVo> data = JSONObject.parseArray(object.get("data").toString(), JjDivisionVo.class);
        log.info("部门接口返回数据：" + object);
        if(!"200".equals(object.get("code").toString())) {
            throw new ServiceException("部门接口请求异常");
        }
        for (JjDivisionVo datum : data) {
            if("ROOT".equals(datum.getParentcode())) {
                datum.setParentcode("0");
            }
        }
        sysBranchMapper.saveBranchTree(data);
    }

    /**
     * 同步人员（锦江）
     */
    @Override
    public void saveUserInfo(List<JjserInfoVo> data) {
        sysBranchMapper.saveUserInfo(data);
    }

    /**
     * 同步岗位（锦江）
     */
    @Override
    public void saveStation(SysBranch space) {
        HttpResponse response;
        if(Constants.ZERO.equals(space.getType())) {
            response = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getPosts")
                    .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                    .execute();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            response = HttpUtil.createGet("http://192.168.255.135:5566/api/ulYcRBiE/dhr/getPosts?ts=" + sdf.format(new Date()))
                    .header("access_token", "f23c34a3200f1994d85de4daf1f15d")
                    .execute();
        }
        String body = response.body();
        JSONObject object = JSONObject.parseObject(body);
        if(!"200".equals(object.get("code").toString())) {
            throw new ServiceException("岗位接口请求异常");
        }
        List<JjStationVo> data = JSONObject.parseArray(object.get("data").toString(), JjStationVo.class);
        sysBranchMapper.saveStation(data);

    }

    @Override
    public int deleteSysBranchByBranchId(String id) {
        return sysBranchMapper.deleteSysBranchByBranchId(id);
    }

    @Override
    public int updateSysBranchs(SysBranch sysBranch) {
        return sysBranchMapper.updateSysBranch(sysBranch);
    }

    @Override
    public int insertSysBranchs(SysBranch sysBranch) {
        return sysBranchMapper.insertSysBranch(sysBranch);
    }

    /**
     *  查询部门树
     */
    @Override
    public List<TreeSelectVo> queryDeptInfo(SysBranch paramVo) {
        List<SysBranch> branchs = sysBranchMapper.selectSysBranchList(new SysBranch());
        return buildBranchTreeSelect(branchs);
    }


    /**
     * 构建前端所需要树结构
     *
     * @param branchs 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysBranch> buildBranchTree(List<SysBranch> branchs)
    {
        List<SysBranch> returnList = new ArrayList<SysBranch>();
        List<String> tempList = branchs.stream().map(SysBranch::getId).collect(Collectors.toList());
        for (SysBranch branch : branchs)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(branch.getParentId()))
            {
                recursionFn(branchs, branch);
                returnList.add(branch);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = branchs;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param branchs 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectVo> buildBranchTreeSelect(List<SysBranch> branchs)
    {
        List<SysBranch> branchTrees = buildBranchTree(branchs);
        return branchTrees.stream().map(TreeSelectVo::new).collect(Collectors.toList());
    }



    /**
     * 递归列表
     */
    private void recursionFn(List<SysBranch> list, SysBranch t)
    {
        // 得到子节点列表
        List<SysBranch> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysBranch tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysBranch> getChildList(List<SysBranch> list, SysBranch t)
    {
        List<SysBranch> tlist = new ArrayList<SysBranch>();
        Iterator<SysBranch> it = list.iterator();
        while (it.hasNext())
        {
            SysBranch n = (SysBranch) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysBranch> list, SysBranch t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }


    @Override
    public SysBranch selectSysBranchByDeptId(Long deptId) {
        return sysBranchMapper.selectSysBranchByDeptId(deptId);
    }




}
