package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

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.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormColumnServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.ugp.api.Enum.CompanyTypeEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.entity.Company;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.component.robot.BadRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;


import java.util.*;

import static com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant.ORG_CODE_USER;

@Service
public class OrgServiceImpl {

    @Autowired
    OrgUsrServiceImpl orgUsrServiceImpl;

    @Autowired
    DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;

    @Autowired
    DynamicFormInstanceServiceImpl alertFormValueServiceImpl;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    MaterialServiceImpl materialServiceImpl;

    @Autowired
    CompanyServiceImpl companyServiceImpl;

    @Value("${ugp.charge.role.seq}")
    Long chargeRoleSeq;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存或更新orgUsr信息和FormInstance实体信息
     * sequenceNbr表示 若是更新动态表单，则传orgUsr表的sequenceNbr，
     *                  若是新增信息，传null
     * @param jsonObject 表单数据
     * @param bizOrgType 数据类型（企业、人员、部门）
     * @param sequenceNbr 有值更新 ，没值保存
     * @return
     */
    public OrgUsrDto dataHandling(JSONObject jsonObject, String bizOrgType,String sequenceNbr){
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock","1");
            try {
                if (lock) {
                    OrgUsr orgUsr = saveOrgUsr(jsonObject, bizOrgType, sequenceNbr);
                    sequenceNbr = String.valueOf(orgUsr.getSequenceNbr());
                    //条件构造器 找出column表种 类型为（COMPANY 或 DEPARTMENT 或 PERSON）的列
                    LambdaQueryWrapper<DynamicFormColumn> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(DynamicFormColumn::getGroupCode, bizOrgType);
                    List<DynamicFormColumn> dynamicFormColumnList = dynamicFormColumnServiceImpl.list(wrapper);
                    List<DynamicFormInstance> dynamicFormInstanceList = new ArrayList<>();
                    Map<String, Long> map = new HashMap<>();
                    for (DynamicFormColumn dynamicFormColumn : dynamicFormColumnList) {
                        //将column表的基本字段信息给instance表
                        DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
                        BeanUtils.copyProperties(dynamicFormColumn, dynamicFormInstance);
                        dynamicFormInstance.setFormColumnId(dynamicFormColumn.getSequenceNbr());
                        //通过字段名去拿到表单传来的值
                        if ("image".equals(dynamicFormColumn.getFieldCode())) {
                            if (!ValidationUtil.isEmpty(jsonObject.getJSONArray(dynamicFormInstance.getFieldCode()))) {
                                dynamicFormInstance.setFieldValue(JSON.toJSONString(jsonObject.getJSONArray(dynamicFormInstance.getFieldCode())));
                            }
                        } else {
                            dynamicFormInstance.setFieldValue(jsonObject.getString(dynamicFormInstance.getFieldCode()));
                        }
                        dynamicFormInstance.setInstanceId(orgUsr.getSequenceNbr());
                        dynamicFormInstance.setSequenceNbr(null);
                        dynamicFormInstanceList.add(dynamicFormInstance);
                    }
                    //如果sequenceNbr有值（更新）
                    if (!ValidationUtil.isEmpty(sequenceNbr)) {
                        LambdaQueryWrapper<DynamicFormInstance> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(DynamicFormInstance::getInstanceId, orgUsr.getSequenceNbr());
                        List<DynamicFormInstance> instanceList = alertFormValueServiceImpl.list(lambdaQueryWrapper);
                        //如果instance表中有值
                        if (!ValidationUtil.isEmpty(instanceList)) {
                            //将查到的instance信息装到map中
                            for (DynamicFormInstance dynamicFormInstance : instanceList) {
                                map.put(dynamicFormInstance.getFieldCode(), dynamicFormInstance.getSequenceNbr());
                            }
                            //将查到的instance信息中的sequenceNbr装到更新之后的表中。
                            for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
                                dynamicFormInstance.setSequenceNbr(map.get(dynamicFormInstance.getFieldCode()));
                            }
                        }
                    }
                    //保存或更新 根据sequenceNbr
                    alertFormValueServiceImpl.saveOrUpdateBatch(dynamicFormInstanceList);
                    OrgUsrDto orgUsrDto = new OrgUsrDto();
                    BeanUtils.copyProperties(orgUsr, orgUsrDto);
                    orgUsrDto.setDynamicFormValue(dynamicFormInstanceList);
                    return orgUsrDto;
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return dataHandling(jsonObject, bizOrgType, sequenceNbr);
                }
            }catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                if(lock) {
                    redisTemplate.delete("lock");
                }
            }
    }

    /**
     * 更新或保存orgUsr表信息
     * @param jsonObject
     * @param bizOrgType
     * @return
     */
    final  static  int codeSum = 12;
    final  static  int codeUserSum = 6;
    public OrgUsr saveOrgUsr(JSONObject jsonObject,String bizOrgType,String sequenceNbr){
        ReginParams reginParams = getReginParams();
        OrgUsr orgUsr = new OrgUsr();

        if(!ValidationUtil.isEmpty(sequenceNbr)) {
            if (!ValidationUtil.isEmpty(orgUsrServiceImpl.getById(sequenceNbr))) {
                orgUsr = orgUsrServiceImpl.getById(sequenceNbr);
            }
        }
        //部门负责人修改
        if(!ValidationUtil.isEmpty(jsonObject.getString("sequenceNbr")) && !ValidationUtil.isEmpty(jsonObject.getString("charge"))) {
            if (!ValidationUtil.isEmpty(orgUsrServiceImpl.getById(jsonObject.getString("charge")))) {
                if (!ValidationUtil.isEmpty(sequenceNbr)){
                    OrgUsr orgUsr1 = orgUsrServiceImpl.getById(jsonObject.getString("charge")).setParentId(sequenceNbr);
                    if (jsonObject.get("typeUser").equals("addUser")&& orgUsr1.getBizOrgCode().length()== ORG_CODE_USER ) {//部门负责人修改(十八位的话不需要更改code)
                        orgUsr1.setBizOrgCode(orgUsr.getBizOrgCode()+OrgUsrServiceImpl.getOrgCodeStr());
                    }
                    //更改其公司下所属部门
                    orgUsrServiceImpl.saveOrUpdate(orgUsr1);
                    LambdaQueryWrapper<DynamicFormInstance> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(DynamicFormInstance ::getInstanceId,jsonObject.getString("charge"));
                    lambdaQueryWrapper.eq(DynamicFormInstance ::getFieldCode,"deptId");
                    DynamicFormInstance one = alertFormValueServiceImpl.getOne(lambdaQueryWrapper);
                    one.setFieldValue(sequenceNbr);
                    //保存或更新 根据sequenceNbr
                    alertFormValueServiceImpl.saveOrUpdate(one);
                }
            }
        }
        orgUsr.setRecDate(new Date());
        orgUsr.setBizOrgName(jsonObject.getString("name"));
        orgUsr.setSequenceNbr(jsonObject.getLong("sequenceNbr"));
        //设置人员类型
        orgUsr.setBizOrgType(bizOrgType);
        orgUsr.setAmosOrgId(jsonObject.getString("amosOrgId"));
        orgUsr.setAmosOrgCode(jsonObject.getString("amosOrgCode"));

        if (OrgEnum.公司.getKey().equals(bizOrgType)){
            orgUsr.setOrgExpandAttr1(jsonObject.getString("type"));
            orgUsr.setBizOrgCode(jsonObject.getString("creditCode"));
        }

        if (OrgEnum.普通人员.getKey().equals(bizOrgType)){
            if(!ValidationUtil.isEmpty(jsonObject.getInteger("isWelder"))){
                if(ValidationUtil.isEmpty(sequenceNbr)){
                    if (1==jsonObject.getInteger("isWelder")) {
                        orgUsr.setOrgExpandAttr1(OrgEnum.焊工.getKey());
                        orgUsr.setCode(getCode());
                    }
                }
            }
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            //判断筛选条件
            if (!ValidationUtil.isEmpty(jsonObject.getLong("isCheck"))) {
                wrapper.eq(OrgUsr :: getAmosOrgId,jsonObject.getLong("isCheck"));
            } else if(!ValidationUtil.isEmpty(jsonObject.getString("deptId"))) {
                //判断是否存在部门id
                wrapper.eq(OrgUsr::getSequenceNbr,jsonObject.getString("deptId"));
            } else {
                wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(reginParams.getCompany().getSequenceNbr()));
            }
            //设置所属机构
            orgUsr.setParentId(String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr()));
        }
        //设置所属机构
        if (OrgEnum.部门.getKey().equals(bizOrgType)) {
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(reginParams.getCompany().getSequenceNbr()));
            orgUsr.setParentId(String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr()));

        }
        //设置bizOrgCode
        if (orgUsr.getParentId() != null) {
            OrgUsr parent = orgUsrServiceImpl.getById(orgUsr.getParentId());
            if (parent != null && ObjectUtils.isEmpty(orgUsr.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + OrgUsrServiceImpl.getOrgCodeStr());
            }
            if (!ValidationUtil.isEmpty(jsonObject.get("typeUser"))){

             if (jsonObject.get("typeUser").equals("add")  && parent.getBizOrgCode().length() == XJConstant.CODE_USER_SUM) {//添加部门
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + OrgUsrServiceImpl.getOrgCodeStr());
            } else if ((jsonObject.get("typeUser").equals("edit") && parent.getBizOrgCode().length() == XJConstant.ORG_CODE_USER)) {
                 orgUsr.setBizOrgCode(parent.getBizOrgCode() + OrgUsrServiceImpl.getOrgCodeStr());
             } else if (jsonObject.get("typeUser").equals("edit") && parent.getBizOrgCode().length() == XJConstant.ORG_CODE) {//修改所在部门
                 //判断你是否修改部门
                 if (!getOrgUsrById(jsonObject.getString("sequenceNbr")).getParentId().equals(jsonObject.getString("deptId"))){
                     orgUsr.setBizOrgCode(parent.getBizOrgCode().substring(0,codeSum)+OrgUsrServiceImpl.getOrgCodeStr());
                 }

            } else if (jsonObject.get("typeUser").equals("addUser")&&parent.getBizOrgCode().length()== ORG_CODE_USER ) {//部门负责人修改(十八位的话不需要更改code)
                 orgUsr.setBizOrgCode(parent.getBizOrgCode().substring(0,codeUserSum)+OrgUsrServiceImpl.getOrgCodeStr());
            }
            }
        } else {
            orgUsr.setBizOrgCode(OrgUsrServiceImpl.getOrgCodeStr());
        }

        LambdaQueryWrapper<OrgUsr> orgUsrLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orgUsrLambdaQueryWrapper.eq(OrgUsr::getBizOrgName, jsonObject.getString("name"));
        OrgUsr orgUsrOld = orgUsrServiceImpl.getOne(orgUsrLambdaQueryWrapper);
        if (ValidationUtil.isEmpty(orgUsrOld)) {
            orgUsrServiceImpl.saveOrUpdate(orgUsr);
        } else {
            if (OrgEnum.普通人员.getKey().equals(bizOrgType)) {
                orgUsr.setSequenceNbr(orgUsrOld.getSequenceNbr());
            }
            if(OrgEnum.公司.getKey().equals(bizOrgType)) {
                Long companyId = jsonObject.getLong("sequenceNbr");
                if(!ValidationUtil.isEmpty(companyId)){
                    orgUsr.setSequenceNbr(companyId);
                } else {
                    orgUsr.setSequenceNbr(orgUsrOld.getSequenceNbr());
                }
                orgUsrServiceImpl.getBaseMapper().updateIdByOrgName(orgUsr.getSequenceNbr(),orgUsr.getBizOrgName());
            }
            orgUsrServiceImpl.saveOrUpdate(orgUsr, orgUsrLambdaQueryWrapper);

        }

        return orgUsr;
    }

    public String getCode(){
        int c = 0001;
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(OrgUsr::getCode).eq(OrgUsr::getOrgExpandAttr1,OrgEnum.焊工.getKey());
        List<OrgUsr> orgUsr = orgUsrServiceImpl.list(wrapper);
        if(!ValidationUtil.isEmpty(orgUsr)) {
            String code = orgUsr.iterator().next().getCode();
            if (!ValidationUtil.isEmpty(code)) {
                c = Integer.parseInt(code.substring(code.indexOf("-") + 1, code.length())) + 1;
            }
        }

        String welderCode = OrgEnum.焊工.getKey() +"-"+ c;
        return welderCode;
    }

    /**
     * 用户单位信息redis获取
     **/
    public ReginParams getReginParams() {
        try {
            return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取企业下的焊工信息列表
     * @param companyId 单位/企业id
     * @return
     */
    public IPage getInfo(String companyId,IPage page){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getSequenceNbr ,companyId);
        OrgUsr orgUsrCompany = orgUsrServiceImpl.getOne(wrapper);

        LambdaQueryWrapper<OrgUsr> welderWrapper = new LambdaQueryWrapper<>();
        welderWrapper.likeRight(OrgUsr :: getBizOrgCode,orgUsrCompany.getBizOrgCode()).eq(OrgUsr :: getOrgExpandAttr1, OrgEnum.焊工.getKey());
        List<OrgUsr> orgUsrList = new ArrayList<>();
        if(ValidationUtil.isEmpty(page)){
            orgUsrList = orgUsrServiceImpl.list(welderWrapper);
            page = new Page();
        }else{
            orgUsrList = orgUsrServiceImpl.page(page,welderWrapper).getRecords();
        }

        List<Map> mapList = new ArrayList<>();
        for (OrgUsr orgUsr : orgUsrList) {
            Map map = getdetialInfo(String.valueOf(orgUsr.getSequenceNbr()));
            mapList.add(map);
        }
        page.setRecords(mapList);
        return page;
    }


    /**
     * 获取监检机构下的人员
     *
     * @param insDepId 机构id
     * @return
     */
    public List<OrgUsr> getVerInfo(String insDepId) {
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr::getSequenceNbr, insDepId);
        OrgUsr orgUsrCompany = orgUsrServiceImpl.getOne(wrapper);

        LambdaQueryWrapper<OrgUsr> welderWrapper = new LambdaQueryWrapper<>();
        welderWrapper.likeRight(OrgUsr::getBizOrgCode, orgUsrCompany.getBizOrgCode()).eq(OrgUsr::getBizOrgType, OrgEnum.普通人员.getKey());
        //默认拿到为空的getOrgExpandAttr1
        welderWrapper.isNull(OrgUsr::getOrgExpandAttr1);
        List<OrgUsr> orgUsrList = orgUsrServiceImpl.list(welderWrapper);


        return orgUsrList;
    }

    /**
     * 根据id查询详细信息
     * @param sequenceNbr
     * @return
     */
    public Map getdetialInfo(String sequenceNbr){
        Map map = new HashMap();
        OrgUsr orgUsr = getOrgUsrById(sequenceNbr);
        String type = orgUsr.getOrgExpandAttr1();
        LambdaQueryWrapper<DynamicFormInstance> instanceWrapper = new LambdaQueryWrapper<>();
        instanceWrapper.eq(DynamicFormInstance :: getInstanceId,sequenceNbr);
        List<DynamicFormInstance> dynamicFormInstanceList = alertFormValueServiceImpl.list(instanceWrapper);
        map.put("type",type);
        map.put("sequenceNbr",sequenceNbr);
        for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
            if("image".equals(dynamicFormInstance.getFieldCode())){
                if(!ValidationUtil.isEmpty(dynamicFormInstance.getFieldValue()) || !"null".equals(dynamicFormInstance.getFieldValue())){
                    map.put(dynamicFormInstance.getFieldCode(),JSON.parseArray(dynamicFormInstance.getFieldValue()));
                }
            } else {
                map.put(dynamicFormInstance.getFieldCode(), dynamicFormInstance.getFieldValue());
            }
        }
        return map;
    }
    /**
     * 获取当前登陆人的建设单位和建设单位的组织机构代码
     * @return
     */
    @BusinessIdentify
    public Map getConstructionInfo(){
        ReginParams reginParams = getReginParams();
        ReginParams.BusinessInfo businessInfo = reginParams.getBusinessInfo();
        Long companySequenceNbr = businessInfo.getCompanySequenceNbr();
        return getdetialInfo(String.valueOf(companySequenceNbr));
    }


    /**
     * 获取当前登陆人所在公司/单位/企业 下的 所有焊工人员
     * @return
     */
    public IPage getCompanyWelder(IPage page){
        Set<Long> companyIds = materialServiceImpl.getCompanyIds();
        List list = new ArrayList<>();
        for (Long companyId : companyIds) {
            list.addAll(getInfo(String.valueOf(companyId),page).getRecords());
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 获取当前登陆人所在公司/单位/企业 下的 所有部门
     * @return
     */
    public IPage getCompanyDept(IPage page){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        LambdaQueryWrapper<OrgUsr> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.likeRight(OrgUsr :: getBizOrgCode,String.valueOf(orgUsrServiceImpl.getOne(wrapper).getBizOrgCode()))
                .eq(OrgUsr ::getBizOrgType, OrgEnum.部门.getKey());
        wrapper1.orderByDesc(OrgUsr::getRecDate);
        IPage<OrgUsr> list = orgUsrServiceImpl.page(page,wrapper1);
        List<Map> mapList = new ArrayList<>();
        for(OrgUsr orgUsr: list.getRecords()){
            mapList.add(getdetialInfo(String.valueOf(orgUsr.getSequenceNbr())));
        }
        page.setRecords(mapList);
        return page;
    }

    /**
     * 部门管理回显
     * @return
     */
    public IPage getCompanyDeptSeq(IPage page){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        LambdaQueryWrapper<OrgUsr> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrgUsr :: getParentId,String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr())).eq(OrgUsr ::getBizOrgType, OrgEnum.部门.getKey());
        wrapper1.orderByDesc(OrgUsr::getRecDate);
        IPage<OrgUsr> list = orgUsrServiceImpl.page(page,wrapper1);
        List<Map> mapList = new ArrayList<>();
        for(OrgUsr orgUsr: list.getRecords()){
            Map map = getdetialInfo(String.valueOf(orgUsr.getSequenceNbr()));

            OrgUsr orgUsrById = getOrgUsrById(String.valueOf(map.get("charge")));
            map.put("charge",orgUsrById.getBizOrgName());

            mapList.add(map);
        }
        page.setRecords(mapList);

        return page;
    }

    /**
     * 获取当前登陆人所在公司/单位/企业 下的 所有部门
     * @return
     */
    public IPage getDepartmentDept(IPage page){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        LambdaQueryWrapper<OrgUsr> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrgUsr :: getParentId,orgUsrServiceImpl.getOne(wrapper).getSequenceNbr())
                .eq(OrgUsr ::getBizOrgType, OrgEnum.部门.getKey());
        wrapper1.orderByDesc(OrgUsr::getRecDate);
        IPage<OrgUsr> list = orgUsrServiceImpl.page(page,wrapper1);
        List<Map> mapList = new ArrayList<>();
        for(OrgUsr orgUsr: list.getRecords()){
            mapList.add(getdetialInfo(String.valueOf(orgUsr.getSequenceNbr())));
        }
        page.setRecords(mapList);
        return page;
    }

    /**
     * 获取下拉选择值
     * @param type INSTALL("安装单位")、DESIGN("设计单位")
     * @return
     */
    public List<OrgUsr> getSelectInfo(String type){
        if(ValidationUtil.isEmpty(type)){
            return orgUsrServiceImpl.list();
        }
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getOrgExpandAttr1,type);
       return  orgUsrServiceImpl.list(wrapper);
    }

    /**
     * 查询当前登录单位下的人员列表
     * @return
     */
    @BusinessIdentify
    public List<OrgUsr> getCharge(Long sequenceNbr) {
        List<OrgUsr> orgUsrs = new ArrayList<>();
        LambdaQueryWrapper<OrgUsr> personWrapper = new LambdaQueryWrapper<>();
        //获取单位下人员
        personWrapper.like(OrgUsr::getBizOrgCode, getOrgUsr().getBizOrgCode())
                .eq(OrgUsr::getBizOrgType, OrgEnum.普通人员.getKey());
        orgUsrs.addAll(orgUsrServiceImpl.list(personWrapper));

        //获取单位下的部门人员
        if (!ValidationUtil.isEmpty(sequenceNbr)) {
            LambdaQueryWrapper<OrgUsr> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrgUsr::getParentId, sequenceNbr);
            orgUsrs.addAll(orgUsrServiceImpl.list(lambdaQueryWrapper));
        }
        return orgUsrs;
    }

    /**
     * 获取当前登陆人所在单位id（orgUsr表中的id）
     * @return
     */
    public Long getCompanyId(){
        return getOrgUsr().getSequenceNbr();
    }

    /**
     * 获取当前登陆人所在单位信息（orgUsr表的）
     * @return
     */
    public OrgUsr getOrgUsr(){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        OrgUsr orgUsr = orgUsrServiceImpl.getOne(wrapper);
        if(ValidationUtil.isEmpty(orgUsr)){
            return  null;
        }
        return orgUsr;
    }

    /**
     * 根据id获取OrgUsr表的详细信息
     */
    public OrgUsr getOrgUsrById(String sequenceNbr){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getSequenceNbr,sequenceNbr);
        OrgUsr orgUsr = orgUsrServiceImpl.getOne(wrapper);
        if(ValidationUtil.isEmpty(orgUsr)){
            return  null;
        }
        return orgUsr;
    }


    /**
     * 根据id获取getOrgId表的详细信息
     */
    public OrgUsr getOrgId(String sequenceNbr){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,sequenceNbr);
        OrgUsr orgUsr = orgUsrServiceImpl.getOne(wrapper);
        if(ValidationUtil.isEmpty(orgUsr)){
            return  null;
        }
        return orgUsr;
    }

    /**
     * 根据parentId获取OrgUsr表的详细信息列表
     */
    public List<OrgUsr> getOrgUsrByParentId(String sequenceNbr){
        OrgUsr orgUsr = getOrgUsrById(sequenceNbr);
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(OrgUsr :: getBizOrgCode,orgUsr.getBizOrgCode())
                .eq(OrgUsr::getBizOrgType,OrgEnum.普通人员.getKey())
                .ne(OrgUsr::getOrgExpandAttr1,OrgEnum.焊工.getKey());
        List<OrgUsr> orgUsrList = orgUsrServiceImpl.list(wrapper);
        return orgUsrList;
    }

    /**
     * 根据OrgUsr表的sequenceNbr删除instance表的数据
     * @param sequencenNbr
     * @throws Exception
     */
    public void delectInfo(String sequencenNbr) throws Exception {
        OrgUsr orgUsr = getOrgUsrById(sequencenNbr);
        LambdaQueryWrapper<DynamicFormInstance> dynamicWrapper = new LambdaQueryWrapper<>();
        if(OrgEnum.普通人员.getKey().equals(orgUsr.getBizOrgType())){
            dynamicWrapper.eq(DynamicFormInstance::getInstanceId,sequencenNbr);
            alertFormValueServiceImpl.remove(dynamicWrapper);
        }else{
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrgUsr::getParentId,sequencenNbr);
            List<OrgUsr> orgUsrList = orgUsrServiceImpl.list(wrapper);
            if(ValidationUtil.isEmpty(orgUsrList)){
                dynamicWrapper.eq(DynamicFormInstance::getInstanceId,sequencenNbr);
                alertFormValueServiceImpl.remove(dynamicWrapper);
            }else {
                throw new Exception("该企业/部门下还有人员，不可删除！");
            }
        }
        orgUsrServiceImpl.deleteBySeq(Long.valueOf(sequencenNbr));
    }

    /**
     * 根据OrgUsr表的bizOrgName 查询
     * @param bizOrgName
     * @return
     */
    public OrgUsr getInfoByName(String bizOrgName) {
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getBizOrgName,bizOrgName);
        return orgUsrServiceImpl.getOne(wrapper);
    }


    /**
     * 获取企业下的人员信息列表
     * @param companyId 单位/企业id
     * @return
     */
    public IPage getPersonInfo(String companyId,IPage page){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getSequenceNbr ,companyId);
        OrgUsr orgUsrCompany = orgUsrServiceImpl.getOne(wrapper);

        LambdaQueryWrapper<OrgUsr> welderWrapper = new LambdaQueryWrapper<>();
        welderWrapper.likeRight(OrgUsr :: getBizOrgCode,orgUsrCompany.getBizOrgCode()).eq(OrgUsr :: getBizOrgType, OrgEnum.普通人员.getKey());
        welderWrapper.orderByDesc(OrgUsr::getRecDate);
        List<OrgUsr> orgUsrList = new ArrayList<>();
        if(ValidationUtil.isEmpty(page)){
            orgUsrList = orgUsrServiceImpl.list(welderWrapper);
            page = new Page();
        }else{
            orgUsrList = orgUsrServiceImpl.page(page,welderWrapper).getRecords();
        }

        List<Map> mapList = new ArrayList<>();
        for (OrgUsr orgUsr : orgUsrList) {
            Map map = getdetialInfo(String.valueOf(orgUsr.getSequenceNbr()));
            mapList.add(map);
        }
        page.setRecords(mapList);
        return page;
    }

    /**
     * 根据企业id获取企业下的所有人员
     * @return
     */
    public List<OrgUsr> getPersonByCompanyId(String companyId){
        if(ValidationUtil.isEmpty(companyId)){
            return new ArrayList<>();
        }
        OrgUsr orgUsr = this.getOrgUsrById(companyId);
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(OrgUsr::getBizOrgCode,orgUsr.getBizOrgCode())
                .eq(OrgUsr::getBizOrgType,OrgEnum.普通人员.getKey());
        return orgUsrServiceImpl.list(wrapper);
    }

    /**
     * 平台创建人员等操作更新 orgUsr表信息
     *
     */
    public void saveOrUpdateUser(JSONObject jsonObject, String orgType) {
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock","1");
        try {
            if (lock) {
                boolean isCharge = false;
                String amosOrgId = jsonObject.getString("sequenceNbr");
                LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(OrgUsr::getAmosOrgId, amosOrgId)
                        .eq(OrgUsr::getIsDelete, Boolean.FALSE);
                OrgUsr one = orgUsrServiceImpl.getOne(wrapper);
                if (ObjectUtils.isEmpty(one)) {
                    one = new OrgUsr();
                }
                OrgUsr parentOne = new OrgUsr();
                String companyId = "";
                if (OrgEnum.普通人员.getKey().equals(orgType)) {
                    JSONObject companys = JSON.parseObject(JSON.toJSONString(jsonObject.get("orgRoleSeqs")));
                    if (CollectionUtils.isEmpty(companys)) {
                        return;
                    } else {
                        for (Map.Entry<String, Object> stringObjectEntry : companys.entrySet()) {
                            companyId = stringObjectEntry.getKey();
                            break;
                        }
//                JSONObject parentJson = JSON.parseObject(JSON.toJSONString(companys));
//                companyId = parentJson.getString("sequenceNbr");
                    }
                } else {
                    companyId = jsonObject.getString("myParentId");
                    if (companyId.length() < 10) {
                        companyId = jsonObject.getString("companySeq");
                    }
                }
                if (!StringUtils.isEmpty(companyId)) {
                    LambdaQueryWrapper<OrgUsr> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(OrgUsr::getAmosOrgId, companyId)
                            .eq(OrgUsr::getIsDelete, Boolean.FALSE);
                    parentOne = orgUsrServiceImpl.getOne(wrapper2);
                }
                if (!OrgEnum.公司.getKey().equals(orgType) && ObjectUtils.isEmpty(parentOne)) {
                    throw new BadRequest("数据不完整");
                }
                one.setBizOrgName(jsonObject.getString("realName"));
                if (ValidationUtil.isEmpty(one.getBizOrgName())) {
                    Company company = saveMqtt(jsonObject);
                    one.setSequenceNbr(company.getSequenceNbr());
                    one.setBizOrgName(jsonObject.getString("companyName"));
                    one.setOrgExpandAttr1(CompanyTypeEnum.registerNameMap.get(jsonObject.getString("companyType")));
                }
                if (ValidationUtil.isEmpty(one.getBizOrgName())) {
                    one.setBizOrgName(jsonObject.getString("departmentName"));
                }
                if (StringUtils.isEmpty(one.getBizOrgCode())) {
                    if (OrgEnum.公司.getKey().equals(orgType)) {
                        one.setBizOrgCode(!ObjectUtils.isEmpty(parentOne) ? parentOne.getBizOrgCode() + getOrgCodeStr() : getOrgCodeStr());
                    } else if (OrgEnum.部门.getKey().equals(orgType)) {
                        one.setBizOrgCode(parentOne.getBizOrgCode() + getOrgCodeStr());
                    }
                }
                if (OrgEnum.普通人员.getKey().equals(orgType)) {
                    LambdaQueryWrapper<OrgUsr> wrapper3 = new LambdaQueryWrapper<>();
                    wrapper3.eq(OrgUsr::getAmosOrgId, companyId)
                            .eq(OrgUsr::getIsDelete, Boolean.FALSE);
                    OrgUsr one1 = orgUsrServiceImpl.getOne(wrapper3);
                    one.setBizOrgCode(one1.getBizOrgCode() + getOrgCodeStr());
                    if (OrgEnum.部门.getKey().equals(one1.getBizOrgType())) {
                        //向部门添加人员
                        isCharge = true;
                    } else {
                        //如果是修改 如果这个人之前是部门负责人，现在去掉负责人。
                        LambdaQueryWrapper<OrgUsr> orgUsrWrappers = new LambdaQueryWrapper<>();
                        orgUsrWrappers.eq(OrgUsr::getBizOrgName, one.getBizOrgName());
                        OrgUsr orgUsr = orgUsrServiceImpl.getOne(orgUsrWrappers);
                        if (!ValidationUtil.isEmpty(orgUsr)) {
                            orgUsr = orgUsrServiceImpl.getById(orgUsr.getParentId());
                            if (OrgEnum.部门.getKey().equals(orgUsr.getBizOrgType())) {
                                String deptId = String.valueOf(orgUsr.getSequenceNbr());
                                LambdaQueryWrapper<DynamicFormInstance> queryWrapper = new LambdaQueryWrapper<>();
                                queryWrapper.eq(DynamicFormInstance::getFieldCode, "charge").eq(DynamicFormInstance::getInstanceId, deptId);
                                DynamicFormInstance instance = alertFormValueServiceImpl.getOne(queryWrapper);
                                String obj = instance.getFieldValue();
                                List list = new ArrayList();
                                if (!ValidationUtil.isEmpty(obj)) {
                                    list = JSON.parseObject(obj, ArrayList.class);
                                }
                                Long personId = one.getSequenceNbr();
                                if (list.contains(personId)) {
                                    list.remove(personId);
                                    instance.setFieldValue(JSON.toJSONString(list));
                                    alertFormValueServiceImpl.update(instance, queryWrapper);
                                }
                            }
                        }
                    }
                }
                one.setAmosOrgId(amosOrgId);
                one.setAmosOrgCode("");
                one.setBizOrgType(orgType);
                if (StringUtils.isEmpty(jsonObject.getString("myParentId"))) {
                    one.setParentId(ObjectUtils.isEmpty(parentOne) ? null : String.valueOf(parentOne.getSequenceNbr()));
                }
                orgUsrServiceImpl.saveOrUpdate(one);
                if (isCharge) {
                    //向部门添加负责人
                    JSONArray roleSeqs = jsonObject.getJSONObject("orgRoleSeqs").getJSONArray(companyId);
                    LambdaQueryWrapper<OrgUsr> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(OrgUsr::getAmosOrgId, companyId);
                    OrgUsr orgUsr = orgUsrServiceImpl.getOne(wrapper1);
                    if (!ValidationUtil.isEmpty(orgUsr)) {
                        String deptId = String.valueOf(orgUsr.getSequenceNbr());
                        LambdaQueryWrapper<DynamicFormInstance> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(DynamicFormInstance::getFieldCode, "charge").eq(DynamicFormInstance::getInstanceId, deptId);
                        DynamicFormInstance instance = alertFormValueServiceImpl.getOne(queryWrapper);
                        String obj = instance.getFieldValue();
                        List list = new ArrayList();
                        if (!ValidationUtil.isEmpty(obj)) {
                            list = JSON.parseObject(obj, ArrayList.class);
                        }
                        Long personId = one.getSequenceNbr();
                        if (roleSeqs.contains(chargeRoleSeq)) {
                            if (!list.contains(personId)) {
                                list.add(personId);
                            }
                        } else {
                            if (list.contains(personId)) {
                                list.remove(personId);
                            }
                        }
                        instance.setFieldValue(JSON.toJSONString(list));
                        alertFormValueServiceImpl.update(instance, queryWrapper);
                    }
                }


                JSONObject jsonObjectFormColumn = new JSONObject();
                if (OrgEnum.公司.getKey().equals(orgType)) {
                    jsonObjectFormColumn.put("name", jsonObject.getString("companyName"));
                    jsonObjectFormColumn.put("type", jsonObject.getString("companyType"));
                    jsonObjectFormColumn.put("creditCode", jsonObject.getString("companyCode"));
                    jsonObjectFormColumn.put("address", jsonObject.getString("address"));
                    jsonObjectFormColumn.put("contact", jsonObject.getString("contact"));
                    jsonObjectFormColumn.put("contactPhone", jsonObject.getString("landlinePhone"));
                    jsonObjectFormColumn.put("orgCode", jsonObject.getString("orgCode"));
                } else if (OrgEnum.普通人员.getKey().equals(orgType)) {
                    jsonObjectFormColumn.put("name", jsonObject.getString("realName"));
                    jsonObjectFormColumn.put("phone", jsonObject.getString("mobile"));
                } else if (OrgEnum.部门.getKey().equals(orgType)) {
                    jsonObjectFormColumn.put("name", one.getBizOrgName());
                }

                //条件构造器 找出column表种 类型为（COMPANY 或 DEPARTMENT 或 PERSON）的列
                LambdaQueryWrapper<DynamicFormColumn> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(DynamicFormColumn::getGroupCode, orgType);
                List<DynamicFormColumn> dynamicFormColumnList = dynamicFormColumnServiceImpl.list(wrapper2);
                List<DynamicFormInstance> dynamicFormInstanceList = new ArrayList<>();
                Map<String, Long> map = new HashMap<>();
                for (DynamicFormColumn dynamicFormColumn : dynamicFormColumnList) {
                    //将column表的基本字段信息给instance表
                    DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
                    BeanUtils.copyProperties(dynamicFormColumn, dynamicFormInstance);
                    dynamicFormInstance.setFormColumnId(dynamicFormColumn.getSequenceNbr());
                    //通过字段名去拿到表单传来的值
                    if ("image".equals(dynamicFormColumn.getFieldCode())) {
                        if (!ValidationUtil.isEmpty(jsonObjectFormColumn.getJSONArray(dynamicFormInstance.getFieldCode()))) {
                            dynamicFormInstance.setFieldValue(JSON.toJSONString(jsonObjectFormColumn.getJSONArray(dynamicFormInstance.getFieldCode())));
                        }
                    } else {
                        dynamicFormInstance.setFieldValue(jsonObjectFormColumn.getString(dynamicFormInstance.getFieldCode()));
                    }
                    dynamicFormInstance.setInstanceId(one.getSequenceNbr());
                    dynamicFormInstance.setSequenceNbr(null);
                    dynamicFormInstanceList.add(dynamicFormInstance);
                }
                //如果sequenceNbr有值（更新）
                if (!ValidationUtil.isEmpty(one.getSequenceNbr())) {
                    LambdaQueryWrapper<DynamicFormInstance> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(DynamicFormInstance::getInstanceId, one.getSequenceNbr());
                    List<DynamicFormInstance> instanceList = alertFormValueServiceImpl.list(lambdaQueryWrapper);
                    //如果instance表中有值
                    if (!ValidationUtil.isEmpty(instanceList)) {
                        //将查到的instance信息装到map中
                        for (DynamicFormInstance dynamicFormInstance : instanceList) {
                            map.put(dynamicFormInstance.getFieldCode(), dynamicFormInstance.getSequenceNbr());
                        }
                        //将查到的instance信息中的sequenceNbr装到更新之后的表中。
                        for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
                            dynamicFormInstance.setSequenceNbr(map.get(dynamicFormInstance.getFieldCode()));
                        }
                    }
                }
                //保存或更新 根据sequenceNbr
                alertFormValueServiceImpl.saveOrUpdateBatch(dynamicFormInstanceList);
            } else {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                saveOrUpdateUser(jsonObject, orgType);
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(lock) {
                redisTemplate.delete("lock");
            }
        }
    }

    public static String getOrgCodeStr() {
        return TreeParser.genTreeCode();
    }



    public Company saveMqtt(JSONObject jsonObject){
        String companyName = jsonObject.getString("companyName");
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Company::getName,companyName);
        Company company = companyServiceImpl.getOne(wrapper);
        if(ValidationUtil.isEmpty(company)){
            company = new Company();
        }
        company.setName(companyName);
        company.setContact(jsonObject.getString("contact"));
        company.setContactPhone(jsonObject.getString("landlinePhone"));
        company.setType(CompanyTypeEnum.registerNameMap.get(jsonObject.getString("companyType")));
        company.setCreditCode(jsonObject.getString("companyCode"));
        company.setAddress(jsonObject.getString("address"));
        company.setApproved("已审核");
        companyServiceImpl.saveOrUpdate(company);
        return company;
    }
}
