package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.organization.entity.DeleteParam;
import com.engine.organization.entity.SelectOptionParam;
import com.engine.organization.entity.extend.bo.ExtendGroupBO;
import com.engine.organization.entity.extend.bo.ExtendInfoBO;
import com.engine.organization.entity.extend.param.ExtendFieldSearchParam;
import com.engine.organization.entity.extend.param.ExtendInfoChangeParam;
import com.engine.organization.entity.extend.param.ExtendInfoFieldParam;
import com.engine.organization.entity.extend.param.ExtendTitleSaveParam;
import com.engine.organization.entity.extend.po.ExtendGroupPO;
import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.entity.extend.po.ExtendTitlePO;
import com.engine.organization.entity.fieldset.param.FieldTypeTreeParam;
import com.engine.organization.entity.fieldset.vo.TypeTreeVO;
import com.engine.organization.entity.personnelcard.po.CardAccessPO;
import com.engine.organization.enums.DeleteTypeEnum;
import com.engine.organization.enums.ModuleTypeEnum;
import com.engine.organization.mapper.extend.ExtendGroupMapper;
import com.engine.organization.mapper.extend.ExtendInfoMapper;
import com.engine.organization.mapper.extend.ExtendTitleMapper;
import com.engine.organization.service.CardAccessService;
import com.engine.organization.service.FieldDefinedService;
import com.engine.organization.util.HasRightUtil;
import com.engine.organization.util.OrganizationAssert;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.field.BrowserComInfo;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/6/13
 * @Version V1.0
 **/
public class FieldDefinedServiceImpl extends Service implements FieldDefinedService {

    private ExtendGroupMapper getExtendGroupMapper() {
        return MapperProxyFactory.getProxy(ExtendGroupMapper.class);
    }

    private ExtendTitleMapper getExtendTitleMapper() {
        return MapperProxyFactory.getProxy(ExtendTitleMapper.class);
    }

    private ExtendInfoMapper getExtendInfoMapper() {
        return MapperProxyFactory.getProxy(ExtendInfoMapper.class);
    }

    private CardAccessService getCardAccessService(User user) {
        return ServiceUtil.getService(CardAccessServiceImpl.class, user);

    }

    @Override
    public List<TypeTreeVO> getTree(ModuleTypeEnum moduleTypeEnum) {
        Integer extendType = moduleTypeEnum.getValue();
        List<ExtendGroupPO> extendGroupPOS = MapperProxyFactory.getProxy(ExtendGroupMapper.class).listByType(extendType, null);
        return ExtendGroupBO.buildTypeTree(extendGroupPOS);
    }

    @Override
    public Map<String, Object> getTabInfo(String groupType) {
        OrganizationAssert.notBlank(groupType, "分组信息有误，请确认");
        Map<String, Object> datas = new HashMap<>();
        Long groupId = Long.parseLong(groupType);
        String tableName = ExtendGroupBO.getTableNameByGroupPO(getExtendGroupMapper().getGroupById(groupId));
        List<ExtendTitlePO> extendTitleList = getExtendTitleMapper().getTitlesByGroupID(groupId, null);
        List<Map<String, Object>> tabs = new ArrayList<>();
        int idx = 1;
        for (ExtendTitlePO extendTitle : extendTitleList) {
            Map<String, Object> tab = new HashMap<>();
            tab.put("tabkey", idx++);
            tab.put("title", extendTitle.getTitle());
            tab.put("isShow", extendTitle.getIsShow());
            tab.put("groupid", String.valueOf(extendTitle.getId()));
            tab.put("viewAttr", extendTitle.getIsSystemDefault() == 0 ? 1 : 2);
            tab.put("editable", getExtendInfoMapper().countFieldsByGroupId(tableName, extendTitle.getId()) == 0);
            tabs.add(tab);
        }
        datas.put("status", "1");
        datas.put("tabs", tabs);
        return datas;
    }

    @Override
    public int saveFields(String data) {
        if (StringUtils.isEmpty(data)) {
            return 0;
        }
        JSONObject jsonObject = JSON.parseObject(data);
        // extend_group主键
        Long groupType = jsonObject.getLong("groupType");
        ExtendGroupPO extendGroup = getExtendGroupMapper().getGroupById(groupType);

        // 主表、主表拓展表为extend_title主键；明细表为extend_group主键
        Long extendGroupId = jsonObject.getLong("groupId");

        JSONArray records = jsonObject.getJSONArray("records");
        int updateCount = 0;
        for (int i = 0; i < records.size(); i++) {
            // 存在ID则更新 ，不存在ID则增加
            ExtendInfoFieldParam infoFieldParam = JSONObject.toJavaObject((JSONObject) records.get(i), ExtendInfoFieldParam.class);
            ExtendInfoPO extendInfo = ExtendInfoBO.convertFieldParam2ExtendInfo(user, infoFieldParam, extendGroup, extendGroupId, i + 1);

            if (null != extendInfo.getId()) {
                // 更新 extend_title数据
                updateCount += getExtendInfoMapper().updateExtendInfo(extendInfo);
            } else {
                // 新增extend_title数据
                // 获取操作表最大id,生成字段名
                Long maxId = getExtendInfoMapper().getMaxId();
                extendInfo.setFieldName("field" + (maxId + 1));
                extendInfo.setIsSystemDefault(1);
                // 新增表结构
                getExtendInfoMapper().addTableColumn(extendInfo.getTableName(), extendInfo.getFieldName(), extendInfo.getFieldType());
                updateCount += getExtendInfoMapper().insertExtendInfo(extendInfo);
                // 明细表且为浏览按钮字段，添加span字段
                if (null != extendGroup.getPid() && 3 == extendInfo.getControlType()) {
                    String dbType = infoFieldParam.getDbType("2", "");
                    getExtendInfoMapper().addTableColumn(extendInfo.getTableName(), extendInfo.getFieldName() + "span", dbType);
                }

            }
        }
        return updateCount;
    }

    @Override
    public Map<String, Object> saveGroup(ExtendTitleSaveParam param) {
        Map<String, Object> datas = new HashMap<>();
        Long groupType = param.getGroupType();
        Set<Long> lsDelGroupId = new HashSet<>();
        List<ExtendTitlePO> extendTitleList = getExtendTitleMapper().getTitlesByGroupID(groupType, null);
        extendTitleList.forEach(item -> lsDelGroupId.add(item.getId()));
        String data = param.getData();
        JSONObject jsonObject = JSON.parseObject(data);
        Set<Long> ids = new HashSet<>();
        JSONArray records = jsonObject.getJSONArray("records");
        for (int i = 0; i < records.size(); i++) {
            ExtendTitlePO extendTitle = new ExtendTitlePO();
            JSONObject object = (JSONObject) records.get(i);
            extendTitle.setId(object.getLong("id"));
            extendTitle.setGroupId(groupType);
            extendTitle.setIsShow(object.getString("isShow"));
            extendTitle.setTitle(object.getString("groupName"));
            extendTitle.setShowOrder(i + 1);

            if (null != extendTitle.getId()) {
                lsDelGroupId.remove(extendTitle.getId());
            }

            if (null == extendTitle.getId()) {
                extendTitle.setIsSystemDefault(1);
                extendTitle.setCreator((long) user.getUID());
                extendTitle.setCreateTime(new Date());
                extendTitle.setDeleteType(0);
                getExtendTitleMapper().insertIgnoreNull(extendTitle);
            } else {
                extendTitle.setUpdateTime(new Date());
                getExtendTitleMapper().updateExtendTitle(extendTitle);
            }
            ids.add(extendTitle.getId());
        }
        if (CollectionUtils.isNotEmpty(lsDelGroupId)) {
            getExtendTitleMapper().deleteExtendTitleByIds(lsDelGroupId);
        }
        datas.put("groupid", StringUtils.join(ids, ","));
        datas.put("status", "1");
        return datas;
    }

    @Override
    public Map<String, Object> saveTitle(ExtendTitleSaveParam param) {
        Map<String, Object> datas = new HashMap<>();

        List<ExtendTitlePO> titlesByGroupID = getExtendTitleMapper().getTitlesByGroupID(param.getGroupType(), null);
        ExtendTitlePO extendTitlePO = titlesByGroupID.stream().max(Comparator.comparing(ExtendTitlePO::getShowOrder)).orElse(ExtendTitlePO.builder().showOrder(1).build());
        Set<Long> ids = titlesByGroupID.stream().map(ExtendTitlePO::getId).collect(Collectors.toSet());
        ExtendTitlePO extendTitle = new ExtendTitlePO();
        extendTitle.setGroupId(param.getGroupType());
        extendTitle.setIsShow(param.getIsShow());
        extendTitle.setTitle(param.getGroupName());
        extendTitle.setShowOrder(extendTitlePO.getShowOrder() + 1);
        extendTitle.setCreator((long) user.getUID());
        extendTitle.setCreateTime(new Date());
        extendTitle.setDeleteType(0);
        extendTitle.setIsSystemDefault(1);
        getExtendTitleMapper().insertIgnoreNull(extendTitle);
        ids.add(extendTitle.getId());

        datas.put("groupid", StringUtils.join(ids, ","));
        datas.put("status", "1");
        return datas;
    }

    @Override
    public void changeTree(ModuleTypeEnum moduleTypeEnum, FieldTypeTreeParam fieldTypeTreeParam) {
        if (fieldTypeTreeParam.getId() == null) {
            List<ExtendGroupPO> extendGroupPOList = MapperProxyFactory.getProxy(ExtendGroupMapper.class).listByType(moduleTypeEnum.getValue(), null);
            ExtendGroupPO extendGroup = extendGroupPOList.stream().max(Comparator.comparing(ExtendGroupPO::getShowOrder)).get();
            ExtendGroupPO extendGroupPO = buildExtendGroupType(moduleTypeEnum, fieldTypeTreeParam, extendGroup.getShowOrder());
            MapperProxyFactory.getProxy(ExtendGroupMapper.class).insertIgnoreNull(extendGroupPO);
            //默认新增title
            ExtendTitlePO extendTitlePO = buildExtendTitleType(extendGroupPO, 1);
            MapperProxyFactory.getProxy(ExtendTitleMapper.class).insertIgnoreNull(extendTitlePO);
            if (4 == moduleTypeEnum.getValue()) {
                CardAccessPO cardAccessPO = CardAccessPO.builder()
                        .typeId(extendGroupPO.getId().intValue())
                        .typeName(fieldTypeTreeParam.getName())
                        .status(1)
                        .allPeople(0)
                        .superior(0)
                        .allSuperior(0)
                        .creator((long) user.getUID())
                        .deleteType(0)
                        .createTime(new Date())
                        .updateTime(new Date())
                        .build();
                getCardAccessService(user).addData(cardAccessPO);
            }
        } else {
            MapperProxyFactory.getProxy(ExtendGroupMapper.class).update(fieldTypeTreeParam.getId(), fieldTypeTreeParam.getName());
            if (4 == moduleTypeEnum.getValue()) {
                getCardAccessService(user).updateTabName(fieldTypeTreeParam.getName(), fieldTypeTreeParam.getId().intValue());
            }
        }

    }

    @Override
    public int deleteTitle(ExtendTitleSaveParam param) {
        getExtendTitleMapper().deleteExtendTitleByIds(DeleteParam.builder().ids(param.getId().toString()).build().getIds());
        List<ExtendTitlePO> titlesByGroupID = getExtendTitleMapper().getTitlesByGroupID(param.getGroupType(), null);

        if (CollectionUtils.isEmpty(titlesByGroupID)) {
            // 删除整个分组
            getExtendGroupMapper().delete(param.getGroupType());
            getCardAccessService(user).deleteByIds(DeleteParam.builder().ids(param.getGroupType().toString()).build().getIds());
            return 1;
        }
        return 0;
    }

    @Override
    public Map<String, Object> getFieldDefinedInfo(ExtendFieldSearchParam param) {
        Map<String, Object> returnMap = new HashMap<>();
        Long groupType = param.getGroupType();
        ExtendGroupPO extendGroupPO = getExtendGroupMapper().getGroupById(groupType);
        List<Map<String, Object>> lsFieldInfo = new ArrayList<>();
        Map<String, Object> fieldInfo;
        Map<String, Object> recordInfo;
        Map<String, Object> propsInfo;
        Map<String, Object> comInfo;
        List<Object> fieldTypeInfo;
        List<Object> lsComDetialInfo;
        Map<String, Object> comDetialInfo;
        // 区分主表明细表

        String tableName = ExtendGroupBO.getTableNameByGroupPO(extendGroupPO);
        List<ExtendInfoPO> infoPOList = getExtendInfoMapper().listFields("", param.getGroupId().toString(), tableName, "", "");
        for (ExtendInfoPO extendInfoPO : infoPOList) {
            Long fieldId = extendInfoPO.getId();
            String fieldName = extendInfoPO.getFieldName();
            String fieldLabel = extendInfoPO.getFieldNameDesc();
            String fieldHtmlType = extendInfoPO.getControlType().toString();
            String browserType = extendInfoPO.getBrowserType();
            String customValue = extendInfoPO.getCustomValue();
            String fieldStrLength = SelectOptionParam.getTextLength(customValue);
            //自定义字段排序 标识rowKey
            String fieldIdRowKey;
            int showOrder = extendInfoPO.getShowOrder();
            boolean isUsed = false;
            // 是否为系统字段
            boolean isSysField = extendInfoPO.getIsSystemDefault() == 0;
            if (isSysField) {
                fieldIdRowKey = fieldId + "_hrm";
            } else {
                fieldIdRowKey = fieldId + "_cus";
            }
            if (!isSysField) {
                isUsed = ExtendInfoBO.fieldIsUsed(extendInfoPO.getTableName(), extendInfoPO.getFieldName());
            }

            BrowserComInfo BrowserComInfo = new BrowserComInfo();
            List<Object> fieldTypeObj = new ArrayList<>();
            String fieldType = "";
            switch (fieldHtmlType) {
                case "1":
                    fieldTypeObj.add("input");
                    fieldType = SystemEnv.getHtmlLabelName(688, user.getLanguage());
                    switch (browserType) {
                        case "1":
                            fieldTypeObj.add("text");
                            fieldType += " " + SystemEnv.getHtmlLabelName(608, user.getLanguage());
                            fieldType += " " + SystemEnv.getHtmlLabelName(608, user.getLanguage()) + ":" + fieldStrLength;
                            fieldTypeObj.add(fieldStrLength);
                            break;
                        case "2":
                            fieldTypeObj.add("int");
                            fieldType += " " + SystemEnv.getHtmlLabelName(696, user.getLanguage());
                            break;
                        case "3":
                            fieldTypeObj.add("float");
                            fieldType += " " + SystemEnv.getHtmlLabelName(697, user.getLanguage());
                            break;
                    }
                    break;
                case "2":
                    fieldTypeObj.add("textarea");
                    fieldType = SystemEnv.getHtmlLabelName(689, user.getLanguage());
                    break;
                case "3": {
                    fieldTypeObj.add("browser");
                    List<Object> replaceDatas = new ArrayList<>();
                    Map<String, Object> tmp = new HashMap<>();
                    tmp.put("value", browserType);
                    tmp.put("valueSpan", SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(browserType), 0), user.getLanguage()));
                    Map<String, Object> tmp1 = new HashMap<>();
                    tmp1.put("id", browserType);
                    tmp1.put("name", SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(browserType), 0), user.getLanguage()));
                    replaceDatas.add(tmp1);
                    tmp.put("replaceDatas", replaceDatas);
                    fieldTypeObj.add(tmp);
                    fieldType = SystemEnv.getHtmlLabelName(695, user.getLanguage());
                    fieldType += " " + SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(browserType), 0), user.getLanguage());
                    if ("161".equals(browserType) || "162".equals(browserType) || "256".equals(browserType) || "257".equals(browserType)) {
                        tmp = new HashMap<>();
                        tmp.put("value", SelectOptionParam.getCustomBrowserId(customValue));
                        tmp.put("valueSpan", SelectOptionParam.getCustomBrowserValueSpan(customValue));
                        fieldTypeObj.add(tmp);
                        fieldType += " " + SelectOptionParam.getCustomBrowserValueSpan(customValue);
                    }
                    break;
                }
                case "4":
                    fieldTypeObj.add("check");
                    fieldType = SystemEnv.getHtmlLabelName(691, user.getLanguage());
                    break;
                case "5": {
                    fieldTypeObj.add("select");
                    fieldTypeObj.add("select");
                    Map<String, Object> tmp = new HashMap<>();
                    tmp.put("datas", SelectOptionParam.getSelectFields(customValue));
                    tmp.put("sort", "horizontal");
                    fieldTypeObj.add(tmp);
                    fieldType = SystemEnv.getHtmlLabelName(690, user.getLanguage());
                    break;
                }
                case "6":
                    fieldTypeObj.add("upload");
                    fieldTypeObj.add("file");
                    fieldType = SystemEnv.getHtmlLabelName(17616, user.getLanguage());
                    fieldType += " " + SystemEnv.getHtmlLabelName(20798, user.getLanguage());
                    break;
            }

            fieldInfo = new HashMap<>();
            recordInfo = new HashMap<>();
            recordInfo.put("id", "" + fieldId);
            recordInfo.put("fieldlabel", fieldLabel);
            recordInfo.put("fieldname", fieldName);
            recordInfo.put("fieldType", fieldType);
            recordInfo.put("fieldTypeObj", fieldTypeObj);
            // 启用是否勾选
            recordInfo.put("enable", Util.null2String(extendInfoPO.getIsenable()));
            // 必填是否勾选
            recordInfo.put("required", Util.null2String(extendInfoPO.getIsrequired()));
            // 允许修改是否勾选
            recordInfo.put("isModify", Util.null2String(extendInfoPO.getIsModify()));
            // 勾选框是否可选
            recordInfo.put("viewAttr", isUsed || isSysField ? 1 : 2);
            recordInfo.put("key", "" + showOrder);
            recordInfo.put("fieldidrowKey", fieldIdRowKey);

            fieldInfo.put("record", recordInfo);

            propsInfo = new HashMap<>();
            Map<String, Object> checkPropsInfo = new HashMap<>();
            Map<String, Object> checkPropsEnableInfo = new HashMap<>();
            Map<String, Object> checkPropsRequiredInfo = new HashMap<>();

            //允许个人修改字段check框属性
            Map<String, Object> checkPropsModifyInfo = new HashMap<>();

            // 1:只读，2：可编辑,
            Integer checkProps = extendInfoPO.getCheckProps();
            if (null == checkProps) {
                checkProps = 1;
            }
            // 1:只读，2：可编辑,
            Integer modifyProps = extendInfoPO.getModifyProps();
            if (null == modifyProps) {
                modifyProps = 1;
            }
            // 启用列是否可编辑
            checkPropsEnableInfo.put("viewAttr", checkProps);
            // 必填列是否可编辑
            checkPropsRequiredInfo.put("viewAttr", checkProps);
            //允许个人修改列是否可编辑
            checkPropsModifyInfo.put("viewAttr", modifyProps);

            checkPropsInfo.put("enable", checkPropsEnableInfo);
            checkPropsInfo.put("required", checkPropsRequiredInfo);
            checkPropsInfo.put("isModify", checkPropsModifyInfo);
            propsInfo.put("checkProps", checkPropsInfo);
            fieldInfo.put("props", propsInfo);

            comInfo = new HashMap<>();

            lsComDetialInfo = new ArrayList<>();
            comDetialInfo = new HashMap<>();
            comDetialInfo.put("label", "");
            if (isSysField) {
                comDetialInfo.put("type", "TEXT");
            } else {
                comDetialInfo.put("type", "INPUT");
            }
            comDetialInfo.put("width", "15%");
            comDetialInfo.put("key", "fieldlabel");
            comDetialInfo.put("viewAttr", "3");
            lsComDetialInfo.add(comDetialInfo);
            comInfo.put("fieldlabel", lsComDetialInfo);

            lsComDetialInfo = new ArrayList<>();
            comDetialInfo = new HashMap<>();
            comDetialInfo.put("label", "");
            comDetialInfo.put("type", "TEXT");
            comDetialInfo.put("width", "15%");
            comDetialInfo.put("key", "fieldname");
            comDetialInfo.put("viewAttr", "3");
            lsComDetialInfo.add(comDetialInfo);
            comInfo.put("fieldname", lsComDetialInfo);

            lsComDetialInfo = new ArrayList<>();
            comDetialInfo = new HashMap<>();
            comDetialInfo.put("label", "");
            comDetialInfo.put("type", "5".equals(fieldHtmlType) ? "CUSTOMFIELD" : "TEXT");
            comDetialInfo.put("width", "60%");
            comDetialInfo.put("key", "fieldType");
            lsComDetialInfo.add(comDetialInfo);
            comInfo.put("fieldType", lsComDetialInfo);

            fieldInfo.put("com", comInfo);
            fieldInfo.put("isSysField", isSysField);

            fieldTypeInfo = new ArrayList<>();
            fieldTypeInfo.add("select");
            fieldTypeInfo.add("select");
            Map<String, Object> fieldTypeParamInfo = new HashMap<>();

            if ("5".equals(fieldHtmlType)) {

                fieldTypeParamInfo.put("datas", SelectOptionParam.getSelectFields(customValue));
                fieldTypeParamInfo.put("sort", "horizontal");
                fieldTypeInfo.add(fieldTypeParamInfo);
                fieldInfo.put("fieldType", fieldTypeInfo);
            }
            lsFieldInfo.add(fieldInfo);

        }


        returnMap.put("data", lsFieldInfo);
        returnMap.put("encryptEnable", false);
        return returnMap;
    }

    @Override
    public void deleteTree(Long id) {
        //明细表删除字段信息、删除表结构
        ExtendGroupPO extendGroupPO = getExtendGroupMapper().getGroupById(id);
        List<ExtendInfoPO> extendInfoList = getExtendInfoMapper().listFields(extendGroupPO.getExtendType().toString(), extendGroupPO.getId().toString(), ExtendGroupBO.getTableNameByGroupPO(extendGroupPO), "", "");
        String msg = "";
        for (ExtendInfoPO extendInfoPO : extendInfoList) {
            // 判断字段是否使用
            boolean isUsed = ExtendInfoBO.fieldIsUsed(extendInfoPO.getTableName(), extendInfoPO.getFieldName());
            if (isUsed) {
                msg = extendInfoPO.getFieldNameDesc() + "字段已被使用，不可删除";
                break;
            }
            if (extendInfoPO.getIsSystemDefault() == 0) {
                msg = extendInfoPO.getFieldNameDesc() + "字段为系统必须字段，不可删除";
                break;
            }
        }
        OrganizationAssert.isBlank(msg, msg);
        MapperProxyFactory.getProxy(ExtendGroupMapper.class).delete(id);
        List<Long> ids = extendInfoList.stream().map(ExtendInfoPO::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)) {
            // 删除数据
            dropColumns(ids, extendGroupPO, extendInfoList);
        }
    }

    @Override
    public void saveTree(ModuleTypeEnum moduleTypeEnum, FieldTypeTreeParam fieldTypeTreeParam) {
        Set<Long> collect = MapperProxyFactory.getProxy(ExtendGroupMapper.class)
                .listGroupByPid(fieldTypeTreeParam.getParentId(), null).stream().map(ExtendGroupPO::getId).collect(Collectors.toSet());
        Integer extendType = moduleTypeEnum.getValue();
        List<ExtendGroupPO> extendGroupPOS = JSONArray.parseArray(fieldTypeTreeParam.getData(), ExtendGroupPO.class);

        List<Long> collect1 = extendGroupPOS.stream().map(ExtendGroupPO::getId).collect(Collectors.toList());
        collect1.forEach(collect::remove);
        if (CollectionUtils.isNotEmpty(collect)) {
            MapperProxyFactory.getProxy(ExtendGroupMapper.class).batchDelete(collect);
        }

        AtomicInteger showOrder = new AtomicInteger(0);
        extendGroupPOS.forEach(e -> {
            showOrder.getAndIncrement();
            e.setExtendType(extendType);
            e.setPid(fieldTypeTreeParam.getParentId());
            e.setShowOrder(showOrder.get());
            e.setIsSystemDefault(1);
            e.setCreator((long) user.getUID());
            e.setDeleteType(DeleteTypeEnum.NOT_DELETED.getValue());
            e.setCreateTime(new Date());
            e.setUpdateTime(new Date());

            if (e.getId() == null) {//新增
                MapperProxyFactory.getProxy(ExtendGroupMapper.class).insertIgnoreNull(e);
            } else { //更新
                MapperProxyFactory.getProxy(ExtendGroupMapper.class).updateNameAndOrder(e.getId(), e.getGroupName(), e.getShowOrder(), e.getIsShow());
            }
        });


    }

    @Override
    public void deleteFieldDefined(ExtendFieldSearchParam param) {
        Collection<Long> ids = param.getId();
        Long groupType = param.getGroupType();
        ExtendGroupPO extendGroupPO = getExtendGroupMapper().getGroupById(groupType);

        List<ExtendInfoPO> extendInfoList = getExtendInfoMapper().getExtendInfosByIds(ids);
        dropColumns(ids, extendGroupPO, extendInfoList);

    }

    @Override
    public void changeGroup(ExtendInfoChangeParam param) {
        // 移动字段的ID
        String fieldids = param.getFieldids();
        // extendTiele表ID
        Long groupid = param.getGroupid();

        if (StringUtils.isNotEmpty(fieldids) && null != groupid) {
            // 更新extendInfo表的extend_group_id
            List<Long> ids = Arrays.stream(fieldids.split(",")).map(Long::parseLong).collect(Collectors.toList());
            getExtendInfoMapper().updateExtendGroupId(groupid, ids);
        }

    }

    @Override
    public Map<String, Object> getHasRight(ModuleTypeEnum moduleTypeEnum) {
        Map<String, Object> btnDatas = new HashMap<>();
        String rightName = "";
        switch (moduleTypeEnum.getValue().toString()) {
            case "1":
                rightName = "CompanyField:All";
                break;
            case "2":
                rightName = "DepartmentField:All";
                break;
            case "3":
                rightName = "PostField:All";
                break;
            case "4":
                rightName = "ResourceField:All";
                break;
            default:
                break;
        }
        boolean hasRight = StringUtils.isNotBlank(rightName) && HasRightUtil.hasRight(user, rightName, true);
        btnDatas.put("hasRight", hasRight);
        return btnDatas;
    }

    /**
     * 删除数据及表结构
     *
     * @param ids
     * @param extendGroupPO
     * @param extendInfoList
     */
    private void dropColumns(Collection<Long> ids, ExtendGroupPO extendGroupPO, List<ExtendInfoPO> extendInfoList) {
        // 删除数据
        getExtendInfoMapper().deleteExtendInfoByIds(ids);
        // 删除表结构
        for (ExtendInfoPO extendInfoPO : extendInfoList) {
            getExtendInfoMapper().deleteTableColumn(extendInfoPO.getTableName(), extendInfoPO.getFieldName());
            // 明细表浏览按钮，额外删除span字段
            if (null != extendGroupPO.getPid() && 3 == extendInfoPO.getControlType()) {
                getExtendInfoMapper().deleteTableColumn(extendInfoPO.getTableName(), extendInfoPO.getFieldName() + "span");
            }

        }
    }

    private ExtendTitlePO buildExtendTitleType(ExtendGroupPO extendGroupPO, Integer max) {
        return ExtendTitlePO.builder()
                .groupId(extendGroupPO.getId())
                .title(extendGroupPO.getGroupName())
                .showOrder(max)
                .isShow("1")
                .isSystemDefault(1)
                .creator((long) user.getUID())
                .deleteType(DeleteTypeEnum.NOT_DELETED.getValue())
                .createTime(new Date())
                .updateTime(new Date()).build();
    }


    private ExtendGroupPO buildExtendGroupType(ModuleTypeEnum moduleTypeEnum, FieldTypeTreeParam fieldTypeTreeParam, Integer max) {
        return ExtendGroupPO.builder()
                .extendType(moduleTypeEnum.getValue())
                .groupName(fieldTypeTreeParam.getName())
                .showOrder(++max)
                .isSystemDefault(1)
                .creator((long) user.getUID())
                .deleteType(DeleteTypeEnum.NOT_DELETED.getValue())
                .createTime(new Date())
                .updateTime(new Date())
                .pid(fieldTypeTreeParam.getParentId())
                .isShow(fieldTypeTreeParam.getIsShow() == null ? "1" : fieldTypeTreeParam.getIsShow()).build();
    }


}
