package com.engine.organization.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.cloudstore.dev.api.util.TextUtil;
import com.engine.core.impl.Service;
import com.engine.organization.entity.jclimport.po.CusFormFieldPO;
import com.engine.organization.entity.search.QuickSearchCondition;
import com.engine.organization.entity.search.QuickSearchDetail;
import com.engine.organization.entity.search.QuickSearchField;
import com.engine.organization.entity.search.QuickSearchSetting;
import com.engine.organization.entity.search.condition.ConditionOption;
import com.engine.organization.entity.search.condition.RangeCondition;
import com.engine.organization.enums.LogModuleNameEnum;
import com.engine.organization.mapper.condition.QuickSearchMapper;
import com.engine.organization.service.QuickSearchService;
import com.engine.organization.util.db.MapperProxyFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import weaver.formmode.exttools.impexp.common.DateUtils;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.systeminfo.SystemEnv;

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


/**
 * @author:dxfeng
 * @createTime: 2023/08/08
 * @version: 1.0
 */
public class QuickSearchServiceImpl extends Service implements QuickSearchService {
    private QuickSearchMapper getQuickSearchMapper() {
        return MapperProxyFactory.getProxy(QuickSearchMapper.class);
    }


    @Override
    public Map<String, Object> getQuickSearchCondition(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>(16);

        QuickSearchSetting quickSearchSetting = getQuickSearchMapper().getQuickSearchSetting(user.getUID());
        if (null != quickSearchSetting) {
            apiDatas.put("enable", "1".equals(Util.null2String(quickSearchSetting.getIsQuickSearch())));
        } else {
            apiDatas.put("enable", false);
        }

        List<Object> rangeConditions = new ArrayList<>();

        List<QuickSearchCondition> quickSearchConditionList = getQuickSearchMapper().getQuickSearchConditionList(user.getUID(), LogModuleNameEnum.RESOURCE.getValue());
        for (QuickSearchCondition quickSearchCondition : quickSearchConditionList) {

            RangeCondition condition = new RangeCondition();
            condition.setLabel(quickSearchCondition.getCustomName());
            condition.setDomkey(Collections.singletonList(quickSearchCondition.getFieldId()));
            // 根据条件字段类型，组装展示样式
            switch (quickSearchCondition.getType()) {
                case 5:
                    List<SearchConditionOption> selectOptions = getSelectOptions(quickSearchCondition);
                    if (CollectionUtils.isEmpty(selectOptions)) {
                        condition.setCom(SystemEnv.getHtmlLabelName(547591,user.getLanguage()));
                    } else {
                        // 字段本身值、判断有无下拉框选项
                        List<ConditionOption> options = selectOptions.stream().map(item -> ConditionOption.builder().key(item.getKey()).showname(item.getShowname()).build()).collect(Collectors.toList());
                        options.add(0,ConditionOption.builder().key("-1").showname(SystemEnv.getHtmlLabelName(547191,user.getLanguage())).build());
                        condition.setOptions(options);
                    }
                    rangeConditions.add(condition);
                    break;
                case 3:
                    // 日期类型数据
                    List<ConditionOption> options = new ArrayList<>();
                    options.add(ConditionOption.builder().key("0").showname(SystemEnv.getHtmlLabelName(332, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("1").showname(SystemEnv.getHtmlLabelName(15537, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("2").showname(SystemEnv.getHtmlLabelName(15539, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("3").showname(SystemEnv.getHtmlLabelName(15541, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("7").showname(SystemEnv.getHtmlLabelName(27347, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("4").showname(SystemEnv.getHtmlLabelName(21904, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("5").showname(SystemEnv.getHtmlLabelName(15384, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("8").showname(SystemEnv.getHtmlLabelName(81716, user.getLanguage())).build());
                    options.add(ConditionOption.builder().key("6").showname(SystemEnv.getHtmlLabelName(32530, user.getLanguage())).build());
                    condition.setOptions(options);
                    Map<String, Object> selectLinkageDataMap = new HashMap<>(1);
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("conditionType", "RANGEPICKER");
                    map.put("domkey", Arrays.asList(quickSearchCondition.getFieldId() + "_start", quickSearchCondition.getFieldId() + "_end"));
                    selectLinkageDataMap.put("6", map);
                    condition.setSelectLinkageDatas(selectLinkageDataMap);
                    rangeConditions.add(condition);
                    break;
                case 1:
                    // 整数-浮点数
                    List<QuickSearchDetail> quickSearchDetailList = getQuickSearchMapper().getQuickSearchDetailByCid(quickSearchCondition.getId().toString());

                    if (CollectionUtils.isEmpty(quickSearchDetailList)) {
                        condition.setCom(SystemEnv.getHtmlLabelName(547591,user.getLanguage()));
                    } else {
                        List<ConditionOption> collect = quickSearchDetailList.stream().map(item -> ConditionOption.builder().key(item.getId().toString()).showname(item.getCustomName()).build()).collect(Collectors.toList());
                        collect.add(0,ConditionOption.builder().key("-1").showname(SystemEnv.getHtmlLabelName(547191,user.getLanguage())).build());
                        condition.setOptions(collect);
                    }
                    rangeConditions.add(condition);
                    break;
                case -1:
                case -3:
                case -4:
                default:
                    rangeConditions.add(condition);
                    break;

            }
        }

        apiDatas.put("rangeConditions", rangeConditions);
        return apiDatas;
    }

    @Override
    public Map<String, Object> getQuickSearchInfo(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>(16);
        //开关查询
        QuickSearchSetting quickSearchSetting = getQuickSearchMapper().getQuickSearchSetting(user.getUID());
        JSONObject json = new JSONObject();
        if (null != quickSearchSetting) {
            json.put("isquicksearch", Util.null2String(quickSearchSetting.getIsQuickSearch()));
            json.put("isshowtype", null != quickSearchSetting.getIsShowType() ? quickSearchSetting.getIsShowType() : "1");
            json.put("ishidename", null != quickSearchSetting.getIsHideName() ? quickSearchSetting.getIsHideName() : "0");
            json.put("id", Util.null2String(quickSearchSetting.getId()));
        } else {
            json.put("isquicksearch", "0");
            json.put("isshowtype", "0");
            json.put("ishidename", "0");
            json.put("id", "0");
        }
        apiDatas.put("setting", json);

        //条件字段查询
        List<QuickSearchCondition> quickSearchConditionList = getQuickSearchMapper().getQuickSearchConditionList(user.getUID(), LogModuleNameEnum.RESOURCE.getValue());
        JSONArray datas = new JSONArray();
        if (CollectionUtils.isNotEmpty(quickSearchConditionList)) {
            for (QuickSearchCondition quickSearchCondition : quickSearchConditionList) {
                JSONObject obj = new JSONObject();
                String id = Util.null2String(quickSearchCondition.getId());
                String fieldId = Util.null2String(quickSearchCondition.getFieldId());
                String customName = Util.null2String(quickSearchCondition.getCustomName());
                String type = Util.null2String(quickSearchCondition.getType());
                String orderId = Util.null2String(quickSearchCondition.getOrderId());
                String showModel = null != quickSearchCondition.getShowModel() ? quickSearchCondition.getShowModel().toString() : "0";
                obj.put("cid", id);
                obj.put("key", id);
                obj.put("fieldid", fieldId);
                obj.put("orifieldid", fieldId);
                obj.put("customname", TextUtil.toBase64ForMultilang(customName));
                obj.put("type", type);
                obj.put("orderid", orderId);
                obj.put("groupid", "");
                obj.put("showmodel", showModel);
                datas.add(obj);
            }
        }
        apiDatas.put("datas", datas);

        //字段下拉框查询
        List<CusFormFieldPO> allFieldInfo = getQuickSearchMapper().getAllFieldInfo();
        //List<QuickSearchOption> quickSearchOptionList = getQuickSearchMapper().getQuickSearchOptionList();
        JSONArray options = new JSONArray();
        if (CollectionUtils.isNotEmpty(allFieldInfo)) {
            for (CusFormFieldPO formFieldPO : allFieldInfo) {
                JSONObject obj = new JSONObject();
                String fieldHtmlType = Util.null2String(formFieldPO.getFieldHtmlType());
                String fieldId = Util.null2String(formFieldPO.getScopeId() + "_" + formFieldPO.getTableName() + "_" + formFieldPO.getFieldName());
                // String fieldName = Util.null2String(quickSearchOption.getFieldName());
                String type = Util.null2String(formFieldPO.getType());
                int fieldLabel = Util.getIntValue(formFieldPO.getFieldLabel(), 0);
                String labelName = SystemEnv.getHtmlLabelName(Util.getIntValue(formFieldPO.getFieldLabel()), user.getLanguage());
                String fieldType = "2";
                boolean isShowModel = false;
                if ("1".equals(fieldHtmlType)) {
                    if ("1".equals(type)) {
                        //单行文本
                        continue;
                    } else {
                        //整数或浮点数
                        fieldType = "1";
                        isShowModel = true;
                    }
                } else if ("5".equals(fieldHtmlType) && "3".equals(type)) {
                    //选择框单选框
                    fieldType = "5";
                    isShowModel = true;
                } else if ("5".equals(fieldHtmlType) && "2".equals(type)) {
                    //选择框多选框
                    fieldType = "5";
                    isShowModel = true;
                } else if ("5".equals(fieldHtmlType) && "0".equals(type)) {
                    //选择框
                    fieldType = "5";
                    isShowModel = true;
                } else if ("4".equals(fieldHtmlType) && "1".equals(type)) {
                    //check框
                    fieldType = "5";
                    isShowModel = true;
                } else if ("3".equals(fieldHtmlType)) {
                    switch (type) {
                        case "2":
                            //日期
                            fieldType = "3";
                            break;
                        case "1":
                        case "3":
                        case "5":
                        default:
                            continue;
                    }
                } else {
                    continue;
                }

                if ("".equals(labelName)) {
                    labelName = SystemEnv.getHtmlLabelName(fieldLabel, user.getLanguage());
                }

                obj.put("key", fieldId);
                obj.put("fieldid", fieldId);
                obj.put("showname", labelName);
                obj.put("isdetailtable", "0");
                obj.put("type", fieldType);
                obj.put("isShowModel", isShowModel);
                options.add(obj);
            }
        }
        apiDatas.put("options", options);
        apiDatas.put("groupidOptions", new JSONArray());
        return apiDatas;
    }

    @Override
    public Map<String, Object> saveQuickSearchInfo(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>(16);
        String isQuickSearch = Util.null2String(params.get("isquicksearch"));
        String isShowType = Util.null2String(params.get("isshowtype"));
        isShowType = StringUtils.isBlank(isShowType) ? "0" : isShowType;
        String isHideName = Util.null2String(params.get("ishidename"));
        isHideName = StringUtils.isBlank(isHideName) ? "0" : isHideName;
        String id = Util.null2String(params.get("id"));
        String data = Util.null2String(params.get("data"));
        JSONArray datas = JSONArray.parseArray(data);
        //配置信息更新
        if ("0".equals(id) || "".equals(id)) {
            QuickSearchSetting quickSearchSetting = QuickSearchSetting.builder()
                    .belongTo(user.getUID())
                    .isQuickSearch(Integer.parseInt(isQuickSearch))
                    .isShowType(Integer.parseInt(isShowType))
                    .isHideName(Integer.parseInt(isHideName))
                    .updateTor(user.getUID())
                    .updateDate(DateUtils.getCurrentDate())
                    .updateTime(DateUtils.getCurrentTime())
                    .build();
            //第一次修改配置
            getQuickSearchMapper().insertQuickSearchSetting(quickSearchSetting);
        } else {
            QuickSearchSetting quickSearchSetting = QuickSearchSetting.builder()
                    .id(Integer.parseInt(id))
                    .isQuickSearch(Integer.parseInt(isQuickSearch))
                    .isShowType(Integer.parseInt(isShowType))
                    .isHideName(Integer.parseInt(isHideName))
                    .build();
            getQuickSearchMapper().updateQuickSearchSetting(quickSearchSetting);
        }

        List<QuickSearchCondition> quickSearchConditionList = getQuickSearchMapper().getQuickSearchConditionList(user.getUID(), LogModuleNameEnum.RESOURCE.getValue());
        List<Integer> list = quickSearchConditionList.stream().map(QuickSearchCondition::getId).collect(Collectors.toList());

        for (int i = 0; i < datas.size(); i++) {
            JSONObject obj = (JSONObject) datas.get(i);
            String fieldId = obj.getString("fieldid");
            String oriFieldId = obj.getString("orifieldid");
            Integer cid = Util.getIntValue(obj.getString("cid"));
            String customName = obj.getString("customname");
            String type = obj.getString("type");
            String orderId = obj.getString("orderid");
            String showModel = obj.getString("showmodel");
            if (cid > 0) {
                list.remove(cid);
                QuickSearchCondition quickSearchCondition = QuickSearchCondition.builder()
                        .belongTo(user.getUID())
                        .fieldId(fieldId)
                        .customName(customName)
                        .type(StringUtils.isBlank(type) ? null : Integer.parseInt(type))
                        .orderId(StringUtils.isBlank(orderId) ? null : Integer.parseInt(orderId))
                        .showModel(StringUtils.isBlank(showModel) ? null : Integer.parseInt(showModel))
                        .id(cid)
                        .modelId(LogModuleNameEnum.RESOURCE.getValue())
                        .build();
                getQuickSearchMapper().updateQuickSearchCondition(quickSearchCondition);
                if (!fieldId.equals(oriFieldId)) {
                    //改变了字段,将原先字段的明细删除
                    getQuickSearchMapper().deleteQuickSearchDetailByCid(cid);
                }
            } else {
                QuickSearchCondition quickSearchCondition = QuickSearchCondition.builder()
                        .belongTo(user.getUID())
                        .fieldId(fieldId)
                        .customName(customName)
                        .type(StringUtils.isBlank(type) ? null : Integer.parseInt(type))
                        .orderId(StringUtils.isBlank(orderId) ? null : Integer.parseInt(orderId))
                        .showModel(StringUtils.isBlank(showModel) ? null : Integer.parseInt(showModel))
                        .modelId(LogModuleNameEnum.RESOURCE.getValue())
                        .build();
                getQuickSearchMapper().insertQuickSearchCondition(quickSearchCondition);
            }
        }

        if (CollectionUtils.isNotEmpty(list)) {
            getQuickSearchMapper().deleteQuickSearchConditionByIds(list);
            getQuickSearchMapper().deleteQuickSearchDetailByCids(list);
        }

        return apiDatas;
    }

    @Override
    public Map<String, Object> getQuickSearchDetailInfo(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>(16);
        String cid = weaver.formmode.exttools.impexp.common.StringUtils.null2String(params.get("cid"));
        //开关查询
        List<QuickSearchDetail> quickSearchDetailList = getQuickSearchMapper().getQuickSearchDetailByCid(cid);
        JSONArray datas = new JSONArray();
        for (QuickSearchDetail quickSearchDetail : quickSearchDetailList) {
            JSONObject obj = new JSONObject();
            String id = Util.null2String(quickSearchDetail.getId());
            String customName = Util.null2String(quickSearchDetail.getCustomName());
            String minNum = Util.null2String(quickSearchDetail.getMinNum());
            minNum = minNum.startsWith("0E") ? "0" : minNum;
            String maxNum = Util.null2String(quickSearchDetail.getMaxNum());
            maxNum = maxNum.startsWith("0E") ? "0" : maxNum;
            String type = Util.null2String(quickSearchDetail.getType());
            String orderId = Util.null2String(quickSearchDetail.getOrderId());
            String fieldId = Util.null2String(quickSearchDetail.getFieldId());
            String belongTo = Util.null2String(quickSearchDetail.getBelongTo());
            obj.put("id", id);
            obj.put("cid", cid);
            obj.put("key", id);
            obj.put("customname", customName);
            obj.put("minnum", minNum);
            obj.put("maxnum", maxNum);
            obj.put("type", type);
            obj.put("fieldid", fieldId);
            obj.put("belongto", belongTo);
            obj.put("orderid", orderId);
            datas.add(obj);
        }
        QuickSearchCondition quickSearchConditionById = getQuickSearchMapper().getQuickSearchConditionById(cid);
        String[] split = quickSearchConditionById.getFieldId().split("_");
        int precision = 0;
        if(split.length==3) {
            QuickSearchField quickSearchField = getQuickSearchMapper().getQuickSearchFieldListByConditionId(split[2], split[0]);
            String fieldHtmlType = quickSearchField.getFieldHtmlType();
            String type = quickSearchField.getType();
            String fieldDbType = quickSearchField.getFieldDbType();
            if ("1".equals(fieldHtmlType) && !"1".equals(type)) {
                int digitsIndex = fieldDbType.indexOf(",");
                precision = Util.getIntValue(fieldDbType.substring(digitsIndex + 1, fieldDbType.length() - 1), 0);
            }
        }
        apiDatas.put("datas", datas);
        apiDatas.put("precision", precision);
        return apiDatas;
    }

    @Override
    public Map<String, Object> saveQuickSearchDetailInfo(Map<String, Object> params) {
        Map<String, Object> apiDatas = new HashMap<>(16);
        String cid = Util.null2String(params.get("cid"));
        String data = Util.null2String(params.get("data"));
        JSONArray datas = JSONArray.parseArray(data);
        List<Integer> list = getQuickSearchMapper().getQuickSearchDetailByCid(cid).stream().map(QuickSearchDetail::getId).collect(Collectors.toList());

        try {
            for (int i = 0; i < datas.size(); i++) {
                JSONObject obj = (JSONObject) datas.get(i);
                String customName = obj.getString("customname");
                String fieldId = obj.getString("fieldid");
                String minNum = obj.getString("minnum");
                minNum = "".equals(minNum) ? null : minNum;
                String maxNum = obj.getString("maxnum");
                maxNum = "".equals(maxNum) ? null : maxNum;
                String type = obj.getString("type");
                String orderId = obj.getString("orderid");
                Integer id = Util.getIntValue(obj.getString("id"));

                QuickSearchDetail quickSearchDetail = QuickSearchDetail.builder()
                        .cId(StringUtils.isBlank(cid) ? null : Integer.parseInt(cid))
                        .customName(customName)
                        .minNum(StringUtils.isBlank(minNum) ? null : Integer.parseInt(minNum))
                        .maxNum(StringUtils.isBlank(maxNum) ? null : Integer.parseInt(maxNum))
                        .type(StringUtils.isBlank(type) ? null : Integer.parseInt(type))
                        .orderId(StringUtils.isBlank(orderId) ? null : Integer.parseInt(orderId))
                        .fieldId(fieldId)
                        .belongTo(user.getUID())
                        .build();

                if (id > 0) {
                    list.remove(id);
                    quickSearchDetail.setId(id);
                    getQuickSearchMapper().updateQuickSearchDetail(quickSearchDetail);
                } else {
                    getQuickSearchMapper().insertQuickSearchDetail(quickSearchDetail);
                }
            }
            if (CollectionUtils.isNotEmpty(list)) {
                getQuickSearchMapper().deleteQuickSearchDetailByIds(list);
            }
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            e.printStackTrace();
        }

        return apiDatas;
    }

    /**
     * 获取人员自定义选择字段，所有选择选项
     *
     * @param quickSearchCondition 快速搜索条件
     * @return 选择字段，所有选项列表
     */
    private List<SearchConditionOption> getSelectOptions(QuickSearchCondition quickSearchCondition) {
        try {
            String fieldId = quickSearchCondition.getFieldId();
            HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
            int scopeid = Integer.parseInt(fieldId.split("_")[0]);
            HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeid);
            String fieldName = fieldId.substring(fieldId.lastIndexOf("_") + 1);

            org.json.JSONObject hrmFieldConf = hfm.getHrmFieldConf(fieldName);
            if (null == hrmFieldConf) {
                return new ArrayList<>();
            }
            boolean baseField = hfm.isBaseField(fieldName);
            HrmFieldBean hrmFieldBean = new HrmFieldBean();
            hrmFieldBean.setFieldid(Util.null2String(hrmFieldConf.getString("id")));
            hrmFieldBean.setFieldname(scopeid + "_" + (baseField ? "hrm" : "cus") + "_" + fieldName);
            hrmFieldBean.setFieldlabel(hrmFieldConf.getString("fieldlabel"));
            hrmFieldBean.setFieldhtmltype(hrmFieldConf.getString("fieldhtmltype"));
            hrmFieldBean.setType(hrmFieldConf.getString("type"));
            hrmFieldBean.setDmlurl(hrmFieldConf.getString("dmlurl"));
            hrmFieldBean.setIssystem(baseField ? "1" : "0");
            hrmFieldBean.setIsFormField(true);
            hrmFieldBean.setIsQuickSearch(false);
            hrmFieldBean.setIsScope(false);
            if ("jobactivity".equals(fieldName)) {
                // 职务：282
                hrmFieldBean.setType("282");
            }
            SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
            return searchConditionItem.getOptions();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

}
