package com.engine.organization.entity.extend.bo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.BrowserBean;
import com.api.browser.bean.BrowserValueInfo;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.service.BrowserValueInfoService;
import com.api.browser.util.BrowserInitUtil;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.api.hrm.bean.FieldItem;
import com.api.hrm.util.FieldType;
import com.api.hrm.util.ServiceUtil;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.organization.entity.SelectOptionParam;
import com.engine.organization.entity.extend.param.ExtendInfoFieldParam;
import com.engine.organization.entity.extend.po.ExtendGroupPO;
import com.engine.organization.entity.extend.po.ExtendInfoPO;
import com.engine.organization.mapper.extend.ExtendInfoMapper;
import com.engine.organization.entity.browser.po.CustomBrowserBean;
import com.engine.organization.util.OrganizationFormItemUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import com.engine.sensitive.biz.SensitiveWordTypeComInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.systeminfo.SystemEnv;

import java.util.*;

/**
 * @author:dxfeng
 * @createTime: 2022/05/19
 * @version: 1.0
 */
public class ExtendInfoBO {

    public static String DATE_SELECT = "select";
    public static String DATE_FROM = "from";
    public static String DATE_TO = "to";
    public static String DATE_Time_FROM = "_start";
    public static String DATE_Time_TO = "_end";

    // 封装对象为table组件
    public static List<Map<String, Object>> convertInfoListToTable(User user, List<ExtendInfoPO> infoPOList, int viewAttr, boolean showLabel) {
        List<Map<String, Object>> lsCol = new ArrayList<>();
        Map<String, Object> col;

        int width = 100 / infoPOList.size();
        for (ExtendInfoPO extendInfoPO : infoPOList) {
            String tmpkey = extendInfoPO.getFieldName();
            col = new HashMap<>();
            col.put("title", extendInfoPO.getFieldNameDesc());

            col.put("key", tmpkey);
            col.put("dataIndex", tmpkey);
            col.put("com", getFieldDetailInfo(user, extendInfoPO, viewAttr, showLabel, width));

            col.put("width", width + "%");

            lsCol.add(col);
        }
        return lsCol;

    }

    /**
     * 新增自定义字段时，对象转换
     *
     * @param user           当前用户
     * @param infoFieldParam 拓展字段
     * @param extendGroupPO  分组实体
     * @param extendGroupId  分组ID
     * @param showOrder      展示顺序
     */
    public static ExtendInfoPO convertFieldParam2ExtendInfo(User user, ExtendInfoFieldParam infoFieldParam, ExtendGroupPO extendGroupPO, Long extendGroupId, Integer showOrder) {
        if (null == infoFieldParam) {
            return null;
        }
        String controlType = infoFieldParam.getControlType();
        String browserType = infoFieldParam.getBrowserType(controlType);
        String dbType = infoFieldParam.getDbType(controlType, browserType);
        if (StringUtils.isEmpty(dbType)) {
            dbType = infoFieldParam.getDbType("2", "");
        }
        return ExtendInfoPO
                .builder()
                .id(infoFieldParam.getId())
                .extendType(extendGroupPO.getExtendType())
                .tableName(ExtendGroupBO.getTableNameByGroupPO(extendGroupPO))
                .fieldName(infoFieldParam.getFieldname())
                .fieldNameDesc(infoFieldParam.getFieldlabel())
                // 数据库类型
                .fieldType(dbType)
                .controlType(Integer.parseInt(controlType))
                .browserType(browserType)
                .extendGroupId(extendGroupId)
                .isenable("1".equals(infoFieldParam.getEnable()) ? 1 : 0)
                .isrequired("1".equals(infoFieldParam.getRequired()) ? 1 : 0)
                .listShow(1)
                // .editShow("0".equals(infoFieldParam.getIsModify()) ? 0 : 1)
                .editShow(1)
                .addShow(1)
                .browserShow(1)
                .customValue(convertSelectCustom(controlType, infoFieldParam.getFieldType().toString()))
                .showOrder(showOrder)
                // 非系统初始化字段
                .isSystemDefault(1)
                .creator((long) user.getUID())
                .deleteType(0)
                .createTime(new Date())
                .build();
    }

    private static String convertSelectCustom(String controlType, String fieldType) {
        if (!"5".equals(controlType)) {
            return fieldType;
        }
        JSONArray objects = JSONObject.parseArray(fieldType);
        if (objects.size() < 3) {
            return objects.toString();
        }
        JSONObject o = (JSONObject) objects.get(2);
        JSONArray datas = o.getJSONArray("datas");
        if (!datas.isEmpty()) {
            int size = datas.size();
            for (int i = 0; i < size; i++) {
                JSONObject jsonObject = (JSONObject) datas.get(i);
                if (StringUtils.isBlank(jsonObject.getString("id"))) {
                    jsonObject.put("id", i + "");
                }
                if (StringUtils.isBlank(jsonObject.getString("key"))) {
                    jsonObject.put("key", i + "");
                }
            }
        }
        return objects.toString();
    }

    /**
     * 当前自定义字段是否已使用
     *
     * @param tableName 表名
     * @param fieldName 字段名
     */
    public static boolean fieldIsUsed(String tableName, String fieldName) {
        if (StringUtils.isAnyEmpty(tableName, fieldName)) {
            return true;
        }
        List<Object> objects = MapperProxyFactory.getProxy(ExtendInfoMapper.class).listFieldsByTableName(tableName, fieldName);
        objects.removeIf(Objects::isNull);
        return CollectionUtils.isNotEmpty(objects);
    }

    /**
     * 明细表字段
     *
     * @param user 当前用户
     * @param extendInfoPO 名字表字段实体
     * @param viewAttr 操作类型
     */
    private static List<FieldItem> getFieldDetailInfo(User user, ExtendInfoPO extendInfoPO, int viewAttr, boolean showLabel, int width) {
        List<FieldItem> ls = new ArrayList<>();
        FieldItem fieldItem = createField(user, extendInfoPO, viewAttr, showLabel, width);
        ls.add(fieldItem);
        return ls;
    }

    /**
     * 创建列表字段信息
     *
     * @param user 当前用户
     * @param extendInfoPO 字段信息
     * @param viewAttr 操作类型
     * @param showLabel 展示名字
     * @param width 宽度
     */
    private static FieldItem createField(User user, ExtendInfoPO extendInfoPO, int viewAttr, boolean showLabel, int width) {
        FieldItem fieldItem = new FieldItem();
        if (showLabel) {
            fieldItem.setLabel(extendInfoPO.getFieldNameDesc());
        } else {
            fieldItem.setLabel("");
        }

        fieldItem.setType(getFieldHtmlType(Util.null2String(extendInfoPO.getControlType())));
        fieldItem.setKey(extendInfoPO.getFieldName());
        // 查看操作 全部设置为只读
        if (1 == viewAttr) {
            fieldItem.setViewAttr(viewAttr);
        } else {
            // 必填
            if (1 == extendInfoPO.getIsrequired()) {
                fieldItem.setViewAttr(3);
                fieldItem.setRules("required");
            } else {
                fieldItem.setViewAttr(2);
            }
        }

        // 浏览按钮特殊处理
        if (FieldType.BROWSER.equals(fieldItem.getType())) {
            String browserId = SelectOptionParam.getCustomBrowserId(extendInfoPO.getCustomValue());
            BrowserBean browserConditionParam = OrganizationFormItemUtil.browserItem(user, 2, 16, fieldItem.getViewAttr(), false, extendInfoPO.getFieldNameDesc(), extendInfoPO.getBrowserType(), extendInfoPO.getFieldName(), browserId).getBrowserConditionParam();
            fieldItem.setBrowserConditionParam(browserConditionParam);
        }

        fieldItem.setWidth(width + "%");
        return fieldItem;
    }

    /**
     * 获取对应的控件类型
     *
     * @param fieldHtmlType 控件类型
     */
    private static FieldType getFieldHtmlType(String fieldHtmlType) {
        FieldType fieldtype = null;
        switch (fieldHtmlType) {
            case "1":
                fieldtype = FieldType.INPUT;
                break;
            case "2":
                fieldtype = FieldType.TEXTAREA;
                break;
            case "3":
                fieldtype = FieldType.BROWSER;
                break;
            case "4":
                fieldtype = FieldType.CHECKBOX;
                break;
            case "5":
                fieldtype = FieldType.SELECT;
                break;
            case "6":
                fieldtype = FieldType.FILEUPLOAD;
                break;
            case "7":
                fieldtype = FieldType.TEXT;
                break;
        }
        return fieldtype;
    }


    public static SearchConditionItem getSearchConditionItem(User user, int viewAttr, ExtendInfoPO extendInfoPO, Object fieldvalue) {
        SearchConditionItem searchConditionItem = null;
        try {
            if (user == null) {
                user = new User();
                user.setLanguage(7);
            }
            ConditionFactory conditionFactory = new ConditionFactory(user);
            HrmFieldManager hrmFieldManager = new HrmFieldManager();
            String fieldid = Util.null2String(extendInfoPO.getId());//字段id
            String fieldname = Util.null2String(extendInfoPO.getFieldName());//字段名
            // String fieldlabel = Util.null2String(extendInfoPO.getFieldNameDesc());//字段显示名
             String fieldlabel = "502327";//字段显示名
            String fieldhtmltype = Util.null2String(extendInfoPO.getControlType());//字段类型
            String detailtype = Util.null2String(extendInfoPO.getBrowserType());//字段二级类型（浏览框--单人力）
            String customValue = Util.null2String(extendInfoPO.getCustomValue());
            boolean isQuickSearch = true;

            switch (fieldhtmltype) {
                case "1": //单行文本框
                    if (detailtype.equals("2")) {//数字
                        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUTNUMBER, fieldlabel, fieldname, isQuickSearch);
                    } else {
                        searchConditionItem = conditionFactory.createCondition(ConditionType.INPUT, "25034", fieldname, isQuickSearch);
                    }
                    break;
                case "2": //多行文本框
                    searchConditionItem = conditionFactory.createCondition(ConditionType.TEXTAREA, fieldlabel, fieldname);
                    break;
                case "3": //浏览按钮
                    customValue = SelectOptionParam.getCustomBrowserId(customValue);
                    switch (detailtype) {
                        case "2":
                            if (!extendInfoPO.getTableName().toLowerCase().contains("_dt")) {
                                searchConditionItem = conditionFactory.createCondition(ConditionType.DATEPICKER, fieldlabel, fieldname);
                            } else {
                                searchConditionItem = conditionFactory.createCondition(ConditionType.DATE, fieldlabel, fieldname, detailtype);
                                searchConditionItem.setDomkey(new String[]{fieldname + DATE_SELECT, fieldname + DATE_FROM, fieldname + DATE_TO});
                                searchConditionItem.setOptions(ServiceUtil.getDateSelectFromTo(user.getLanguage()));
                            }
                            break;
                        case "19":
                            searchConditionItem = conditionFactory.createCondition(ConditionType.TIMEPICKER, fieldlabel, fieldname, detailtype);
                            break;
                        case "402":  // 年
                            searchConditionItem = conditionFactory.createCondition(ConditionType.DATEPICKER, fieldlabel, fieldname, detailtype);
                            searchConditionItem.setFormat("yyyy");
                            searchConditionItem.setMode("year");
                            searchConditionItem.setPlaceholder(SystemEnv.getHtmlLabelNames("526306", user.getLanguage()));
                            searchConditionItem.setShowTime(false);
                            break;
                        case "403":
                            searchConditionItem = conditionFactory.createCondition(ConditionType.DATEPICKER, fieldlabel, fieldname, detailtype);
                            searchConditionItem.setFormat("yyyy-MM");
                            searchConditionItem.setMode("month");
                            searchConditionItem.setPlaceholder(SystemEnv.getHtmlLabelNames("126137", user.getLanguage()));
                            searchConditionItem.setShowTime(false);
                            break;
                        case "RANGEPICKER": {//日期区间
                            String[] domkey = new String[]{DATE_FROM + fieldname, DATE_TO + fieldname};
                            searchConditionItem = conditionFactory.createCondition(ConditionType.RANGEPICKER, fieldlabel, domkey);
                            searchConditionItem.setValue(fieldvalue);
                            break;
                        }
                        case "TIMERANGEPICKER": {//时间区间
                            String[] domkey = new String[]{fieldname + DATE_Time_FROM, fieldname + DATE_Time_TO};
                            searchConditionItem = conditionFactory.createCondition(ConditionType.TIMERANGEPICKER, fieldlabel, domkey);
                            searchConditionItem.setValue(fieldvalue);
                            break;
                        }
                        default:
                            if (detailtype.equals("161") || detailtype.equals("162") || detailtype.equals("256") || detailtype.equals("257")) {
                                BrowserBean browserbean = new BrowserBean( Util.null2String(detailtype));
                                BrowserInitUtil browserInitUtil = new BrowserInitUtil();
                                String fielddbtype = customValue;
                                if (!customValue.startsWith("browser.")) {
                                    fielddbtype = "browser." + customValue;
                                }
                                if (detailtype.equals("161") || detailtype.equals("162")) {
                                    browserInitUtil.initCustomizeBrow(browserbean, fielddbtype, Util.getIntValue(detailtype), user.getUID());
                                } else {
                                    browserbean.getDataParams().put("cube_treeid", customValue);
                                    browserbean.getDataParams().put("currenttime", System.currentTimeMillis());
                                    browserInitUtil.initBrowser(browserbean, user.getLanguage());
                                }
                                searchConditionItem = new SearchConditionItem(ConditionType.BROWSER, fieldlabel, new String[]{fieldname}, browserbean);
                            } else {
                                searchConditionItem = conditionFactory.createCondition(ConditionType.BROWSER, fieldlabel, fieldname, detailtype);
                            }
                            // 岗位浏览按钮
                            if ("666".equals(detailtype)) {
                                BrowserBean browserBean = searchConditionItem.getBrowserConditionParam();
                                String s = JSONObject.toJSONString(browserBean);
                                CustomBrowserBean customBrowserBean = JSONObject.parseObject(s, CustomBrowserBean.class);
                                customBrowserBean.setHasLeftTree(true);
                                customBrowserBean.setLeftToSearchKey("treeKey");
                                searchConditionItem.setBrowserConditionParam(customBrowserBean);
                            }
                            List<Map<String, Object>> replaceDatas = new ArrayList<>();
                            String tmpFieldValue = Util.null2String(fieldvalue);
                            switch (detailtype) {
                                case "mkqshift": {
                                    ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit();
                                    String[] fieldvalues = Util.splitString(tmpFieldValue, ",");
                                    for (int i = 0; fieldvalues != null && i < fieldvalues.length; i++) {
                                        String fieldshowname = Util.null2String(shiftManagementToolKit.getShiftOnOffWorkSections(fieldvalues[i], user.getLanguage()));
                                        if (fieldshowname.length() == 0) continue;
                                        Map<String, Object> replaceData = new HashMap<>();
                                        replaceData.put("id", fieldvalues[i]);
                                        replaceData.put("name", fieldshowname);
                                        replaceDatas.add(replaceData);
                                    }
                                    break;
                                }
                                case "sensitivewordstype": {
                                    SensitiveWordTypeComInfo sensitiveWordTypeComInfo = new SensitiveWordTypeComInfo();
                                    String[] fieldvalues = Util.splitString(tmpFieldValue, ",");
                                    for (int i = 0; fieldvalues != null && i < fieldvalues.length; i++) {
                                        String fieldshowname = Util.null2String(sensitiveWordTypeComInfo.getName(fieldvalues[i]));
                                        if (fieldshowname.length() == 0) continue;
                                        Map<String, Object> replaceData = new HashMap<>();
                                        replaceData.put("id", fieldvalues[i]);
                                        replaceData.put("name", fieldshowname);
                                        replaceDatas.add(replaceData);
                                    }
                                    break;
                                }
                                case "doccategory": {
                                    List<BrowserValueInfo> fieldvalues = new BrowserValueInfoService().getBrowserValueInfo(detailtype, Util.null2String(fieldvalue));
                                    for (int i = 0; fieldvalues != null && i < fieldvalues.size(); i++) {
                                        BrowserValueInfo valueInfo = fieldvalues.get(i);
                                        String fieldshowname = valueInfo.getName();
                                        if (fieldshowname.length() == 0) {
                                            continue;
                                        }
                                        Map<String, Object> replaceData = new HashMap<>();
                                        replaceData.put("id", valueInfo.getId());
                                        replaceData.put("name", fieldshowname);
                                        replaceDatas.add(replaceData);
                                    }
                                    break;
                                }
                                default:
                                    if (tmpFieldValue.length() > 0) {
                                        String fieldshowname = hrmFieldManager.getFieldvalue(user, customValue, Util.getIntValue(fieldid), Util.getIntValue(fieldhtmltype), Util.getIntValue(detailtype), tmpFieldValue, 0);
                                        String[] fieldvalues = Util.splitString(tmpFieldValue, ",");
                                        String[] fieldshownames = Util.splitString(fieldshowname, ",");
                                        if (detailtype.equals("257")) {
                                            if (fieldshowname.endsWith("&nbsp")) {
                                                fieldshowname = fieldshowname.substring(0, fieldshowname.length() - 5);
                                            }
                                            fieldshownames = Util.splitString(fieldshowname, "&nbsp");
                                        }
                                        for (int i = 0; fieldvalues != null && i < fieldvalues.length; i++) {
                                            if (fieldvalues.length != fieldshownames.length) {
                                                break;
                                            }
                                            if (Util.null2String(fieldshownames[i]).length() == 0) {
                                                continue;
                                            }
                                            Map<String, Object> replaceData = new HashMap<>();
                                            replaceData.put("id", fieldvalues[i]);
                                            replaceData.put("name", fieldshownames[i]);
                                            replaceDatas.add(replaceData);
                                        }
                                    }
                                    break;
                            }
                            fieldvalue = replaceDatas;
                            break;
                    }
                    break;
                case "4": //Check框
                    searchConditionItem = conditionFactory.createCondition(ConditionType.CHECKBOX, fieldlabel, fieldname);
                    if (detailtype.equals("2")) {
                        searchConditionItem.setConditionType(ConditionType.SWITCH);
                    }

                    break;
                case "5":     //选择框

                    List<SearchConditionOption> searchConditionOptions = SelectOptionParam.convertJsonToListOption(customValue);
                    searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, fieldlabel, fieldname, searchConditionOptions);
                    if (detailtype.equals("") || detailtype.equals("0")) {
                        detailtype = "1";
                    }
                    searchConditionItem.setKey(Util.null2String(fieldvalue));
                    searchConditionItem.setValue(Util.null2String(fieldvalue));
                    searchConditionItem.setDetailtype(Util.getIntValue(detailtype, 3));
                    break;
                case "6": //附件
                    if (fieldname.equals("resourceimageid")) {
                        searchConditionItem = conditionFactory.createCondition(ConditionType.RESOURCEIMG, fieldlabel, fieldname, isQuickSearch);
                    } else {
                        searchConditionItem = conditionFactory.createCondition(ConditionType.UPLOAD, fieldlabel, fieldname, isQuickSearch);
                        searchConditionItem.setUploadUrl("/api/doc/upload/uploadFile");
                        searchConditionItem.setCategory("category");
                        searchConditionItem.setMaxFilesNumber(10);
                        searchConditionItem.setMultiSelection(true);
                        Map<String, Object> otherParamsMap = new HashMap<>();
                        otherParamsMap.put("showClearAll", false);
                        otherParamsMap.put("showOrder", true);
                        searchConditionItem.setOtherParams(otherParamsMap);
                        if (Util.null2String(fieldvalue).length() > 0) {
                            List<Object> datas = new ArrayList<>();
                            Map<String, Object> data;
                            String[] tmpIds = Util.splitString(Util.null2String(fieldvalue), ",");
                            for (String fileid : tmpIds) {
                                ImageFileManager manager = new ImageFileManager();
                                manager.getImageFileInfoById(Util.getIntValue(fileid));
                                String filename = manager.getImageFileName();
                                String extname = filename.contains(".") ? filename.substring(filename.lastIndexOf(".") + 1) : "";
                                data = new HashMap<>();
                                data.put("acclink", "/weaver/weaver.file.FileDownload?fileid=" + fileid);
                                data.put("fileExtendName", extname);
                                data.put("fileid", fileid);
                                //if (Util.null2String(this.isMobile).equals("1")) {
                                //    data.put("filelink", "/spa/document/static4mobile/index.html#/attach/" + fileid);
                                //} else {
                                data.put("filelink", "/spa/document/index2file.jsp?imagefileId=" + fileid + "#/main/document/fileView");
                                //}
                                data.put("filename", filename);
                                data.put("filesize", manager.getImgsize());
                                data.put("imgSrc", "");
                                data.put("isImg", "");
                                data.put("loadlink", "/weaver/weaver.file.FileDownload?fileid=" + fileid + "&download=1");
                                data.put("showDelete", "true");
                                data.put("showLoad", "true");
                                datas.add(data);
                            }
                            searchConditionItem.setDatas(datas);
                        }
                    }
                    break;
                case "7": //颜色选择
                    searchConditionItem = conditionFactory.createCondition(ConditionType.COLORPICKER, fieldlabel, fieldname, true);
                    searchConditionItem.setValue(fieldvalue);
                    break;
                case "8": //DESCRIPTION
                    searchConditionItem = conditionFactory.createCondition(ConditionType.DESCRIPTION, fieldlabel, fieldname);
                    searchConditionItem.setValue(fieldvalue);
                    break;
            }
            if (searchConditionItem != null) {
                BrowserInitUtil.setConditionItemDefaultValue(searchConditionItem, fieldvalue, 2);
                searchConditionItem.setLabelcol(6);
                searchConditionItem.setFieldcol(12);
                searchConditionItem.setViewAttr(viewAttr);
                if (searchConditionItem.getBrowserConditionParam() != null) {
                    searchConditionItem.getBrowserConditionParam().setViewAttr(viewAttr);
                }
                if (searchConditionItem.getConditionType().equals(ConditionType.DATE)) {
                    searchConditionItem.setFieldcol(18);
                }

                if (Util.null2String(extendInfoPO.getFieldNameDesc()).length() > 0) {
                    searchConditionItem.setLabel(extendInfoPO.getFieldNameDesc());
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return searchConditionItem;
    }
}
