package com.testor.module.ZLOA.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.model.dto.TSysPostParam;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.role.model.domain.SysRole;
import com.testor.biz.sys.role.service.SysRoleService;
import com.testor.biz.sys.user.controller.SysUserController;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.model.dto.SysUserRoleRequest;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.ZLOA.ZlPath;
import com.testor.module.ZLOA.dto.OASysOrg;
import com.testor.module.ZLOA.dto.ZOrg;
import com.testor.module.ZLOA.dto.ZPerson;
import com.testor.module.ZLOA.sysOrgOA.model.domain.TSysOrgOa;
import com.testor.module.ZLOA.sysOrgOA.service.TSysOrgOaService;
import com.testor.module.ZLOA.sysUserOA.model.domain.TSysUserOa;
import com.testor.module.ZLOA.sysUserOA.service.TSysUserOaService;
import com.testor.module.duty.model.dto.Person;
import com.testor.module.duty.util.PoiExcelUtils;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(value = "zhongliang", tags = "中粮OA数据")
@RequestMapping("/zlmy")
@Slf4j
public class ZhongLiangData {

    @Autowired
    private TSysOrgOaService tSysOrgOaService;

    @Autowired
    private TSysUserOaService tSysUserOaService;
    @Autowired
    private ZlPath zlPath;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private TSysPostService tSysPostService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserController sysUserController;

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/token")
    @ApiOperation(value = "获取token", notes = "")
    public String getToken() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "oaRest");
        map.put("password", "21b8501e-c499-49cb-9ce0-0bc1fd8d7a38");
        String s = JSON.toJSONString(map);
        String post = "";
        try {
            post = HttpUtil.post(zlPath.getUrl() + "/seeyon/rest/token", s);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("第三方接口异常");
        }
        String token = JSON.parseObject(post).getString("id");
        return token;
    }

    @GetMapping("/getAllOrg")
    @ApiOperation(value = "获取所有单位信息", notes = "")
    public String getAllOrg() throws Exception {
        String post = "";
        try {
                post = HttpRequest.get(zlPath.getUrl() + "/seeyon/rest/orgAccounts?token="+getToken())
                .execute().body();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("第三方接口异常");
        }
        JSONArray list = JSONArray.parseArray(post);
        // 所有企业信息
        List<ZOrg> zOrgs = new ArrayList<>();
        list.stream().forEach(item -> {
            ZOrg zOrg = JSON.parseObject(JSON.toJSONString(item), ZOrg.class);
            zOrgs.add(zOrg);
        });
        List<ZOrg> treeList = recursiveMethod(zOrgs);
        // 部门同步
        List<TSysOrgOa> sysOrgOas = new ArrayList<>();
        for (ZOrg zOrg : treeList) {
            TSysOrgOa tSysOrgOa = BeanHelper.beanToBean(zOrg, TSysOrgOa.class);
            sysOrgOas.add(tSysOrgOa);
            // 设置部门信息
            // 企业id
            String orgId = tSysOrgOa.getOrgId();
            TSysOrgOa byId = tSysOrgOaService.getById(orgId);
            // 企业下的部门
            List deparments = getDeparments(orgId);
            List<ZOrg> arrayList = new ArrayList<>();
            if (ObjectHelper.isNotEmpty(deparments)) {
                deparments.stream().forEach(item -> {
                    ZOrg org = JSON.parseObject(JSON.toJSONString(item), ZOrg.class);
                    arrayList.add(org);
                });
                List<TSysOrgOa> tSysOrgOas = new ArrayList<>();
                for (ZOrg org : arrayList) {
                    TSysOrgOa tSysOrgOa1 = BeanHelper.beanToBean(org, TSysOrgOa.class);
                    tSysOrgOa1.setOrgId(org.getId());
                    tSysOrgOa1.setOrgName(org.getName());
                    tSysOrgOa1.setParentId(orgId);
                    tSysOrgOa1.setIsDept("1");
                    if (org.getIsDeleted()) {
                        tSysOrgOa1.setStatus("1");
                    } else {
                        tSysOrgOa1.setStatus("0");
                    }
                    tSysOrgOa1.setParentIds(byId.getParentIds() + "," + tSysOrgOa1.getOrgId());
                    tSysOrgOas.add(tSysOrgOa1);
                }
                tSysOrgOaService.saveOrUpdateBatch(tSysOrgOas);
            }
        }

        // 同步人员信息
        synchronizedPerson(sysOrgOas);
        return post;
    }

    /**
     * 根据企业查询人员并保存
     * @param sysOrgOas 每一个企业
     */
    @GetMapping("/savePersonOA")
    private void synchronizedPerson(List<TSysOrgOa> sysOrgOas) throws Exception{
        // 所有人员信息
        List<TSysUserOa> tSysUserOas = new ArrayList<>();
        for (TSysOrgOa sysOrgOa : sysOrgOas) {
            // 根据单位id获取人员
            List orgPerson = getOrgPerson(sysOrgOa.getOrgId());
            if (ObjectHelper.isNotEmpty(orgPerson)) {
                for (Object person : orgPerson) {
                    ZPerson zPerson = JSON.parseObject(JSON.toJSONString(person), ZPerson.class);
                    TSysUserOa tSysUserOa = BeanHelper.beanToBean(zPerson, TSysUserOa.class);
                    if (zPerson.getIsDeleted()) {
                        tSysUserOa.setStatus("1");
                    } else {
                        tSysUserOa.setStatus("0");
                    }
                    tSysUserOa.setUserId(zPerson.getId());
                    tSysUserOa.setOrgId(zPerson.getOrgAccountId());
                    tSysUserOa.setLoginName(zPerson.getLoginName());
                    tSysUserOa.setUserName(zPerson.getName());
                    tSysUserOa.setDeptId(zPerson.getOrgDepartmentId());
                    tSysUserOa.setPostId(zPerson.getOrgPostId());
                    tSysUserOa.setPhoneNo(zPerson.getTelNumber());
                    tSysUserOas.add(tSysUserOa);
                }
                tSysUserOaService.saveOrUpdateBatch(tSysUserOas);
            }
        }
    }


    /**
     * 递归转换树
     *
     * @param zOrgs 全部企业信息
     * @return
     */
    private List<ZOrg> recursiveMethod(List<ZOrg> zOrgs) {
        List<ZOrg> orgs = new ArrayList<>();
        for (ZOrg zOrg : zOrgs) {
            if ("-1".equals(zOrg.getSuperior()) && zOrg.getIsGroup()) {
                TSysOrgOa tSysOrgOa = BeanHelper.beanToBean(zOrg, TSysOrgOa.class);
                tSysOrgOa.setOrgId(zOrg.getOrgAccountId());
                tSysOrgOa.setParentId("0");
                tSysOrgOa.setParentIds("0");
                tSysOrgOa.setOrgName(zOrg.getName());
                tSysOrgOa.setTreeLevel(1l);
                tSysOrgOa.setIsDept("0");
                tSysOrgOa.setTreeSort(zOrg.getSortId());
                tSysOrgOa.setOrgCode(zOrg.getCode());
                tSysOrgOa.setCreateDate(zOrg.getCreateTime());
                tSysOrgOa.setUpdateDate(zOrg.getUpdateTime());
                if (zOrg.getIsDeleted()) {
                    tSysOrgOa.setStatus("1");
                } else {
                    tSysOrgOa.setStatus("0");
                }
                // 获取地址 邮件信息
                String properties = zOrg.getProperties();
                tSysOrgOa.setAddress(JSON.parseObject(properties).getString("address"));
                tSysOrgOa.setZipCode(JSON.parseObject(properties).getString("zipCode"));
                tSysOrgOa.setLeader(JSON.parseObject(properties).getString("chiefLeader"));
                tSysOrgOa.setPhoneNo(JSON.parseObject(properties).getString("telephone"));
                tSysOrgOa.setFax(JSON.parseObject(properties).getString("fax"));
                tSysOrgOa.setEmail(JSON.parseObject(properties).getString("zipCode"));
                tSysOrgOa.setRemarks(zOrg.getDescription());
                tSysOrgOaService.saveOrUpdate(tSysOrgOa);
                getChildren(tSysOrgOa, zOrgs);
            }
        }
        return zOrgs;
    }

    /**
     * @param zOrg  父节点对象
     * @param zOrgs 所有企业信息
     * @return
     */
    private TSysOrgOa getChildren(TSysOrgOa zOrg, List<ZOrg> zOrgs) {
        for (ZOrg org : zOrgs) {
            if (zOrg.getOrgId().equals(org.getSuperior())) {
                TSysOrgOa tSysOrgOa = BeanHelper.beanToBean(org, TSysOrgOa.class);
                tSysOrgOa.setOrgId(org.getOrgAccountId());
                tSysOrgOa.setOrgName(org.getName());
                tSysOrgOa.setParentId(zOrg.getOrgId());
                tSysOrgOa.setIsDept("0");
                tSysOrgOa.setTreeSort(org.getSortId());
                tSysOrgOa.setOrgCode(org.getCode());
                tSysOrgOa.setCreateDate(org.getCreateTime());
                tSysOrgOa.setUpdateDate(org.getUpdateTime());
                if (org.getIsDeleted()) {
                    tSysOrgOa.setStatus("1");
                } else {
                    tSysOrgOa.setStatus("0");
                }
                tSysOrgOa.setParentIds(zOrg.getParentIds() + "," + tSysOrgOa.getOrgId());
                tSysOrgOa.setTreeLevel(Integer.toUnsignedLong(tSysOrgOa.getParentIds().split(",").length));
                // 获取地址 邮件信息
                String properties = org.getProperties();
                String zipCode = JSON.parseObject(properties).getString("ldapOu");
                System.out.println(zipCode);
                tSysOrgOa.setAddress(JSON.parseObject(properties).getString("address"));
                tSysOrgOa.setZipCode(JSON.parseObject(properties).getString("zipCode"));
                tSysOrgOa.setLeader(JSON.parseObject(properties).getString("chiefLeader"));
                tSysOrgOa.setPhoneNo(JSON.parseObject(properties).getString("telephone"));
                tSysOrgOa.setFax(JSON.parseObject(properties).getString("fax"));
                tSysOrgOa.setEmail(JSON.parseObject(properties).getString("zipCode"));
                tSysOrgOa.setRemarks(org.getDescription());
                tSysOrgOaService.saveOrUpdate(tSysOrgOa);
                getChildren(tSysOrgOa, zOrgs);
            }
        }
        return zOrg;
    }

    @GetMapping("/getOrgPerson")
    @ApiOperation(value = "获取指定单位所有人员", notes = "accountId 单位id")
    public List getOrgPerson(String accountId) throws Exception {
//        accountId = "-1730833917365171641";
        String post = "";
        try {
            post = HttpRequest.get(zlPath.getUrl() + "/seeyon/rest/orgMembers/" + accountId+"?token="+getToken())
//                    .header("token", getToken())
                    .execute().body();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("第三方接口异常");
        }
        System.out.println(post);
        JSONArray list = JSONArray.parseArray(post);
        return list;
    }


    @GetMapping("/getDeparments")
    @ApiOperation(value = "获取部门信息接口", notes = "unitId 单位id")
    public List getDeparments(String unitId) throws Exception {
        String post = "";
        try {
            post = HttpRequest.get(zlPath.getUrl() + "/seeyon/rest/getDeparments/all/" + unitId+"?token="+getToken())
//                    .header("token", getToken())
                    .execute().body();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("第三方接口异常");
        }
        String data = JSON.parseObject(post).getString("data");
        JSONArray list = JSONArray.parseArray(data);

        return list;
    }

    //===========================测试===========================
    public String feg() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("loginname", "admin");
        map.put("password", "123456");
        String s = JSON.toJSONString(map);
        String post = "";
        try {
            post = HttpUtil.post("http://localhost:18083/auth/login", s);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("第三方接口异常");
        }
        String data = JSON.parseObject(post).getString("data");
        String token = JSON.parseObject(data).getString("token");
        return token;
    }

    @GetMapping("/gege")
    @ApiOperation(value = "获取所有单位信息", notes = "")
    public List<TSysOrgOa> gege() throws Exception {
        String post = "";
        try {
            post = HttpRequest.get("http://localhost:18083/org/getOrgList")
                    .header("Authorization", feg())
                    .execute().body();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("第三方接口异常");
        }
        String data = JSON.parseObject(post).getString("data");
        JSONArray jsonArray = JSONArray.parseArray(data);
        List list = JSON.parseObject(data, ArrayList.class);
        List<TSysOrgOa> tSysOrgOas = new ArrayList<>();
        list.forEach(item -> {
            TSysOrgOa tSysOrgOa = JSON.parseObject(JSON.toJSONString(item), TSysOrgOa.class);
            tSysOrgOas.add(tSysOrgOa);
        });

        List<TSysOrgOa> treeList = recursiveMethod1(tSysOrgOas);

        return treeList;
    }

    private List<TSysOrgOa> recursiveMethod1(List<TSysOrgOa> zOrgs) {
        List<TSysOrgOa> orgs = new ArrayList<>();
        for (TSysOrgOa zOrg : zOrgs) {
            if ("0".equals(zOrg.getParentId())) {
                tSysOrgOaService.saveOrUpdate(zOrg);
                getChildren1(zOrg, zOrgs);
            }
        }
        return orgs;
    }

    private TSysOrgOa getChildren1(TSysOrgOa zOrg, List<TSysOrgOa> zOrgs) {
        for (TSysOrgOa org : zOrgs) {
            if (zOrg.getOrgId().equals(org.getParentId())) {
                tSysOrgOaService.saveOrUpdate(org);
                getChildren1(org, zOrgs);
            }
        }
        return zOrg;
    }

    @ApiOperation(value = "批量导入企业信息", notes = "")
    @PostMapping("/importOrg")
    public BaseResponse<List<SysOrg>> importOrg(@RequestParam("file") MultipartFile file) throws Exception {
        BaseResponse<List<SysOrg>> baseResponse = new BaseResponse<>();
        Workbook workbook = null;
        InputStream inputStream = null;
        List<Person> people = new ArrayList<>();
        try {
            inputStream = file.getInputStream();
            // 读取Excel⽂件⼯作表
            workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
            //取得第⼀个⼯作表
            Sheet sheet = workbook.getSheetAt(0);
            //报表上传的每条数据
            List<Map<Integer, Object>> list = PoiExcelUtils.getBody(sheet, 8, 1);
            //  获取企业数据
            getSysOrgList(list);


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baseResponse;
    }

    @ApiOperation(value = "批量导入人员信息", notes = "")
    @PostMapping("/importPersonOA")
    public BaseResponse<List<SysOrg>> importPersonOA(@RequestParam("file") MultipartFile file) throws Exception {
        BaseResponse<List<SysOrg>> baseResponse = new BaseResponse<>();
        Workbook workbook = null;
        InputStream inputStream = null;
        List<Person> people = new ArrayList<>();
        try {
            inputStream = file.getInputStream();
            // 读取Excel⽂件⼯作表
            workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
            //取得第⼀个⼯作表
            Sheet sheet = workbook.getSheetAt(0);
            //报表上传的每条数据
            List<Map<Integer, Object>> list = PoiExcelUtils.getBody(sheet, 12, 1);
            // 获取人员数据
            getPersonExcel(list);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baseResponse;
    }

    /**
     * 获取excel中人员数据
     * @param list
     */
    private void getPersonExcel(List<Map<Integer, Object>> list) {
        // 存储人员角色关系
        List<SysUserRoleRequest> userRoles = new ArrayList<>();
        // 存储人员数据
        List<SysUser> users = new ArrayList<>();
        for (Map<Integer, Object> map : list) {
            // 企业名称
            String orgName = map.get(0).toString().trim();
            // 企业编码
            String orgCode = map.get(1).toString().trim();
            // 获取企业信息
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_NAME, orgName).eq(SysOrg.ORG_CODE, orgCode));
            // 部门名称
            String deptName = map.get(4).toString().trim();
            // 获取部门信息
            SysOrg dept = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_NAME, deptName).eq(SysOrg.PARENT_ID, one.getOrgId()));
            // 主岗位
            String post = map.get(5).toString().trim();
            // 副岗位
            String duptyPost = map.get(6).toString().trim();
            // 获取主岗
            TSysPost sysPost = tSysPostService.getOne(new QueryWrapper<TSysPost>().eq(TSysPost.DEPT_ID, dept.getOrgId()).eq(TSysPost.POST_NAME, post));
            //获取副岗
            TSysPost duptyPosts = tSysPostService.getOne(new QueryWrapper<TSysPost>().eq(TSysPost.DEPT_ID, dept.getOrgId()).eq(TSysPost.POST_NAME, duptyPost));
            // 角色名称
            String role = map.get(11).toString().trim();
            // 获取角色
            SysRole sysRole = sysRoleService.getOne(new QueryWrapper<SysRole>().eq(SysRole.ROLE_NAME, role));

            SysUser sysUser = new SysUser();
            String userId = IdHelper.getId32bit();
            sysUser.setUserId(userId).setOrgId(one.getOrgId()).setUserName(map.get(2).toString())
                    .setSex(map.get(3).toString()).setOrgName(dept.getOrgName()).setDeptId(dept.getOrgId())
                    .setPostName(sysPost.getPostName()).setPostId(sysPost.getId())
//                    .setDeputyPostId(duptyPosts.getId())
                    .setPhoneNo(map.get(7).toString()).setEmail(map.get(8).toString()).setLoginName(map.get(10).toString());
            users.add(sysUser);

            // 角色
            SysUserRoleRequest sysUserRoleRequest = new SysUserRoleRequest();
            List<String> arrayList = new ArrayList<>();
//            arrayList.add(sysRole.getRoleId());
            String[] roleIds = new String[]{sysRole.getRoleId()};
            sysUserRoleRequest.setRoleId(roleIds);
            sysUserRoleRequest.setUserId(userId);
            userRoles.add(sysUserRoleRequest);
        }
        // 存储人员信息
        sysUserService.saveOrUpdateBatch(users);
        // 存储人员角色关系
        for (SysUserRoleRequest userRole : userRoles) {
            sysUserController.assignEntity(userRole);
        }
    }

    /**
     * 获得企业数据集合
     * @param list
     */
    private void getSysOrgList(List<Map<Integer, Object>> list) throws Exception {
        List<OASysOrg> sysOrgList = new ArrayList<>();
        for (Map<Integer, Object> objectMap : list) {
            OASysOrg oaSysOrg = new OASysOrg();
            //子级公司名称
            String LK = objectMap.get(0).toString();
            oaSysOrg.setGrainDepot(LK);
            // 子级公司编号
            String LKBM = objectMap.get(1).toString();
            oaSysOrg.setGrainNumber(LKBM);
            // 单位属性 (基层单位 ， 粮库， 总部)
            String JCDY = objectMap.get(2).toString();
            oaSysOrg.setUnitProperty(JCDY);
            // 上级公司
            String QYGS = objectMap.get(3).toString();
            oaSysOrg.setParentCompany(QYGS);
            // 上级公司编号
            String QUGSBH = objectMap.get(4).toString();
            oaSysOrg.setParentNumber(QUGSBH);
            // 省
            String SHEN = objectMap.get(5).toString();
            oaSysOrg.setProvince(SHEN);
            // 市
            String SHI = objectMap.get(6).toString();
            oaSysOrg.setCity(SHI);
            // 县
            String XIAN = objectMap.get(7).toString();
            oaSysOrg.setConuty(XIAN);

//            oaSysOrg.setParentId(areaId);
            // 子级公司id
            String grainId = IdHelper.getId32bit();
            oaSysOrg.setGrainId(grainId);
            sysOrgList.add(oaSysOrg);
        }
        // 分层级
        tierOrgOA(sysOrgList);
    }

    /**
     * 分层级
     * @param sysOrgList
     */
    private void tierOrgOA(List<OASysOrg> sysOrgList) throws Exception {
        // 按照上级公司分组
        Map<String, List<OASysOrg>> collect = sysOrgList.stream().collect(Collectors.groupingBy(item -> item.getParentCompany() +"-"+ item.getParentNumber() ));
        SysOrg sysOrg = new SysOrg();
        for (String obj : collect.keySet()) {
            // 获取上级公司对应的所有下级公司
            List<OASysOrg> sysOrgs = collect.get(obj);
            String[] strings = obj.split("-");
            SysOrg org = new SysOrg();
            // 上级公司id
            String areaId = IdHelper.getId32bit();
            org.setOrgId(areaId);
            org.setOrgName(strings[0]);
            org.setOrgCode(strings[1]);
            // 父子关系层级保存
            saveOrgOA(org, sysOrgs);
        }
    }

    /**
     * 父子关系层级保存
     * @param org
     * @param sysOrgs
     */
    private void saveOrgOA(SysOrg org, List<OASysOrg> sysOrgs) throws Exception {
        // 获取跟
        SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, "0"));
        org.setParentId(one.getOrgId());
        org.setParentIds(one.getParentIds() +","+ org.getParentId());
        org.setIsDept("0");
        //处理层级
        String[] split = org.getParentIds().split(",");
        org.setTreeLevel(BigDecimal.valueOf(split.length));
        // 上级机构部门
        SysOrg sysOrg2 = new SysOrg();
        sysOrg2.setOrgName("安全环保部");
        String dept = IdHelper.getId32bit();
        sysOrg2.setOrgId(dept);
        sysOrg2.setParentId(org.getOrgId());
        sysOrg2.setParentIds(org.getParentIds() +","+ sysOrg2.getParentId());
        sysOrg2.setIsDept("1");
        // 岗位
        TSysPostParam tSysPostParam = new TSysPostParam();
        tSysPostParam.setDeptId(dept);
        List<TSysPost> posts = new ArrayList<>();
        TSysPost tSysPost = new TSysPost();
        tSysPost.setPostName("安全生产岗");
        posts.add(tSysPost);
        tSysPostParam.setTSysPosts(posts);
        tSysPostService.addEntity(tSysPostParam);

        List<SysOrg> orgs = new ArrayList<>();
        for (OASysOrg sysOrg : sysOrgs) {
            SysOrg sysOrg1 = new SysOrg();
            sysOrg1.setOrgCode(sysOrg.getGrainNumber());
            sysOrg1.setOrgId(sysOrg.getGrainId());
            sysOrg1.setOrgName(sysOrg.getGrainDepot());
            sysOrg1.setProvince(sysOrg.getProvince());
            sysOrg1.setCity(sysOrg.getCity());
            sysOrg1.setCounty(sysOrg.getConuty());
            sysOrg1.setParentId(org.getOrgId());
            sysOrg1.setParentIds(org.getParentIds() +","+ sysOrg1.getParentId());
            sysOrg1.setIsDept("0");

            // 层级
            String[] split1 = sysOrg1.getParentIds().split(",");
            sysOrg1.setTreeLevel(BigDecimal.valueOf(split1.length));
            // 保存部门
            SysOrg sysOrg3 = new SysOrg();
            sysOrg3.setOrgName("安全环保部");
            String deptId = IdHelper.getId32bit();
            sysOrg3.setOrgId(deptId);
            sysOrg3.setParentId(sysOrg1.getOrgId());
            sysOrg3.setParentIds(sysOrg1.getParentIds() +","+ sysOrg3.getParentId());
            sysOrg3.setIsDept("1");
            // 岗位
            TSysPostParam tSysPostParam1 = new TSysPostParam();
            tSysPostParam1.setDeptId(deptId);
            List<TSysPost> posts1 = new ArrayList<>();
            TSysPost tSysPost1 = new TSysPost();
            tSysPost1.setPostName("安全生产岗");
            posts1.add(tSysPost1);
            tSysPostParam1.setTSysPosts(posts1);
            tSysPostService.addEntity(tSysPostParam1);

            orgs.add(sysOrg1);
            orgs.add(sysOrg3);
        }
        orgs.add(org);
        orgs.add(sysOrg2);
        sysOrgService.saveOrUpdateBatch(orgs);
    }
}
