package com.kingdee.customer.hr.emp.web.handler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.MetaDataPK;
import com.kingdee.bos.metadata.data.DataTableInfo;
import com.kingdee.bos.metadata.entity.EntityObjectInfo;
import com.kingdee.bos.metadata.entity.PropertyInfo;
import com.kingdee.bos.metadata.query.*;
import com.kingdee.eas.hr.base.util.HRUtil;
import com.kingdee.eas.hr.emp.web.handler.SHRPersonBizManageF7ListHandler;
import com.kingdee.eas.hr.emp.web.util.PersonF7LikeConvertInitParamUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.component.commonquery.CommonQueryHelper;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.util.LocaleUtils;
import com.kingdee.shr.base.syssetting.web.dynamic.model.ListUIViewInfo;
import com.kingdee.util.StringUtils;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class SHRPersonBizManageF7ListHandlerEx  extends SHRPersonBizManageF7ListHandler {


    public String getListDataAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        String modelFilter = (String)modelMap.get("filter");
        if (StringUtils.isEmpty(modelFilter)) {
            String filter = request.getParameter("filter");
            if (null != filter) {
                if (filter.indexOf("idRangeFromPluralityDel") != -1) {  //and     fleffdt={2199-12-31}  and  FFlowOutAffairID is null   t.fassigntype=0 and t.fisInner = 1
                    filter = filter.replace("idRangeFromPluralityDel", " position.id in (select fpositionid from T_HR_EmpOrgRelation where FassignType=0    and FIsInner=1 and FActionID not in ('jpoAAAH/03nmaL7Z','V2vNOLaKRuGuv9/HNB5laOZovtk=')) ");
                    modelMap.put("filter", filter);
                }

                String queryFilter;
                String selectedOldCompanyId;
                if (filter.indexOf("idRanFromMultiEntry") != -1) {
                    queryFilter = filter.substring(0, filter.indexOf("idRanFromMultiEntry"));
                    selectedOldCompanyId = filter.substring(filter.indexOf("idRanFromMultiEntry") + "idRanFromMultiEntry".length());
                    filter = queryFilter + " id in (select fpersonid from t_hr_personposition where FPRIMARYPOSITIONID ='" + selectedOldCompanyId + "')";
                    modelMap.put("filter", filter);
                }

                if (filter.indexOf("idRanFromMultiEntryByCompany") != -1) {
                    queryFilter = filter.substring(0, filter.indexOf("idRanFromMultiEntryByCompany"));
                    selectedOldCompanyId = filter.substring(filter.indexOf("idRanFromMultiEntryByCompany") + "idRanFromMultiEntryByCompany".length(), filter.length() - 2);
                    filter = queryFilter + " id in (SELECT fpersonid FROM t_hr_personposition pp left join t_org_admin adminOrg on adminOrg.fid = pp.fpersondep where adminOrg.fcompanyid = '" + selectedOldCompanyId + "') ";
                    if (filter.indexOf("F7query") != -1) {
                        filter = filter.replace("F7query", "select");
                    }

                    modelMap.put("filter", filter);
                }

                if (filter.indexOf("F7query") != -1) {
                    filter = filter.replace("F7query", "select");
                    modelMap.put("filter", filter);
                }
            }
        }

        if (PersonF7LikeConvertInitParamUtil.isQueryUseLikeConvert(ctx)) {
            this.likeQueryConvert(request, response, modelMap);
        }

        return super.getListDataAction(request, response, modelMap);
    }



    private void likeQueryConvert(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        String filterItems = (String)modelMap.get("filterItems");
        if (StringUtils.isEmpty(filterItems)) {
            filterItems = request.getParameter("filterItems");
            String query = "";
            ListUIViewInfo uiViewInfo = (ListUIViewInfo)this.getUIViewInfo(request);
            if (uiViewInfo != null && uiViewInfo.getQuery() != null) {
                query = uiViewInfo.getQuery();
            }

            if (!StringUtils.isEmpty(filterItems)) {
                String queryEntity = "";
                String newFilterItems = "";
                String tempTableName = "";
                String ids = "";
                Boolean isUseTemplateTable = false;
                if (filterItems.contains("like") && !StringUtils.isEmpty(query)) {
                    QueryInfo queryInfo = CommonQueryHelper.getQueryInfo(ctx, MetaDataPK.create(query));
                    PropertyUnitCollection units = queryInfo.getUnits();

                    for(int i = 0; i < units.size(); ++i) {
                        PropertyUnitInfo propertyUnitInfo = units.get(i);
                        if (propertyUnitInfo instanceof QueryFieldInfo) {
                            QueryFieldInfo queryFieldInfo = (QueryFieldInfo)units.get(i);
                            PropertyRefCollection propertyRefs = queryFieldInfo.getPropertyRefs();
                            String l = LocaleUtils.getShortCode(ctx);

                            for(int j = 0; j < propertyRefs.size(); ++j) {
                                PropertyRefInfo propertyRefInfo = propertyRefs.get(j);
                                SubEntityInfo subEntity = propertyRefInfo.getSubEntity();
                                String entityName = subEntity.getName();
                                EntityObjectInfo entityRef = subEntity.getEntityRef();
                                PropertyInfo refProperty = propertyRefInfo.getRefProperty();
                                String propertyName = refProperty.getName();
                                String[] split = filterItems.split("like");
                                String queryRealName = split[0].replace("(", "").trim();
                                String queryName = entityName + "." + propertyName;
                                String sql = "";
                                if (queryName.equalsIgnoreCase(queryRealName)) {
                                    queryEntity = entityName;
                                    DataTableInfo table = entityRef.getTable();
                                    if (refProperty.getMappingField().isMultilingual()) {
                                        sql = "select fid from " + table.getName() + " where " + refProperty.getMappingField().getName() + "_" + l + " like " + split[1].replace(")", "").trim();
                                    } else {
                                        sql = "select fid from " + table.getName() + " where " + refProperty.getMappingField().getName() + " like " + split[1].replace(")", "").trim();
                                    }

                                    if (!StringUtils.isEmpty(sql)) {
                                        try {
                                            Set<String> idSet = new HashSet();
                                            IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);
                                            if (executeQuery.size() >= 400) {
                                                isUseTemplateTable = true;
                                            }

                                            if (isUseTemplateTable) {
                                                String userNumber = ctx.getUserName();
                                                String tempTableKey = "TT4EMPLIKE_" + userNumber;

                                                try {
                                                    tempTableName = createTempTable(request, ctx, tempTableKey, sql.toString());
                                                } catch (BOSException var37) {
                                                    var37.printStackTrace();
                                                    throw new SHRWebException(var37.getMessage(), var37);
                                                }
                                            } else {
                                                while(executeQuery.next()) {
                                                    idSet.add(executeQuery.getString("fid"));
                                                }

                                                ids = HRUtil.getStrFromSet(idSet);
                                            }
                                        } catch (BOSException var38) {
                                            var38.printStackTrace();
                                            throw new SHRWebException(var38.getMessage(), var38);
                                        } catch (SQLException var39) {
                                            var39.printStackTrace();
                                            throw new SHRWebException(var39.getMessage(), var39);
                                        }
                                    }
                                }

                                if (!StringUtils.isEmpty(ids)) {
                                    newFilterItems = queryEntity + ".id in " + ids;
                                    break;
                                }

                                if (isUseTemplateTable) {
                                    newFilterItems = queryEntity + ".id in " + "(select * from " + tempTableName + ")";
                                    break;
                                }
                            }

                            if (!StringUtils.isEmpty(newFilterItems)) {
                                break;
                            }
                        }
                    }

                    if (!StringUtils.isEmpty(newFilterItems)) {
                        modelMap.put("filterItems", newFilterItems);
                    }
                }
            }
        }

    }

}
