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


import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.eas.basedata.cm.util.BDUtils;
import com.kingdee.eas.basedata.framework.util.BDUtil;
import com.kingdee.eas.hr.base.EmpPosOrgRelationCollection;
import com.kingdee.eas.hr.base.EmpPosOrgRelationFactory;
import com.kingdee.eas.hr.base.EmpPosOrgRelationInfo;
import com.kingdee.eas.hr.base.IEmpPosOrgRelation;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.json.GridDataEntity;
import com.kingdee.shr.base.syssetting.web.handler.ListHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.DateTimeUtils;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;


/**
 * 兼职单
 *
 * @author coyle
 * 20250331
 */
public class PositionAdminRangeF7HandlerEx extends EmpOrgF7Handler {

    private static Logger logger = Logger.getLogger(PositionAdminRangeF7HandlerEx.class);
    Context ctx = SHRContext.getInstance().getContext();

    public String getListDataAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
            throws SHRWebException {
        String modelFilter = (String) modelMap.get("filter");
        if (StringUtils.isEmpty(modelFilter)) {
            String filter = request.getParameter("filter");
            String personId = filter.substring(filter.indexOf("idRanFromPluralityDel") + "idRanFromPluralityDel".length());
            logger.error("filter ----" + filter);
            logger.error("personId-----" + personId);
            if (null != filter) {
                String empBatchEnrollConsecutiveAddNew;
                String filterEndSign;
                if (filter.indexOf("idRanFromPluralityAdd") != -1) {
                    empBatchEnrollConsecutiveAddNew = filter.substring(0, filter.indexOf("idRanFromPluralityAdd"));
                    filterEndSign = filter
                            .substring(filter.indexOf("idRanFromPluralityAdd") + "idRanFromPluralityAdd".length());
                    if (!StringUtils.isEmpty(filterEndSign)) {

                        filter = empBatchEnrollConsecutiveAddNew
                                + " id not in (select fpositionid from T_HR_EmpOrgRelation t where t.fpersonid='"
                                + filterEndSign + "' and t.fleffdt = {2199-12-31}  and t.FISSYSTEM = 1)";
                    } else {
                        filter = empBatchEnrollConsecutiveAddNew;
                    }
                    modelMap.put("filter", filter);
                }

                if (filter.indexOf("idRanFromPluralityDel") != -1) {
                    ////202503 日期更改
                    Date curDate = new Date();
                    String dateStr = DateTimeUtils.format(curDate, "yyyy-MM-dd");

                    empBatchEnrollConsecutiveAddNew = filter.substring(0, filter.indexOf("idRanFromPluralityDel"));
                    filterEndSign = filter
                            .substring(filter.indexOf("idRanFromPluralityDel") + "idRanFromPluralityDel".length());
                    filter = empBatchEnrollConsecutiveAddNew
                            + " id in (select fpositionid from T_HR_EmpOrgRelation t where t.fpersonid='"
                            + filterEndSign
                            + "' and t.fleffdt >= {" + dateStr + "}  and t.fassigntype=0 and t.fisInner = 1 and t.FActionID not in ('jpoAAAH/03nmaL7Z','V2vNOLaKRuGuv9/HNB5laOZovtk='))";
                    modelMap.put("filter", filter);
                }

                if (filter.indexOf("idRanFromPositionHierarchy") != -1) {
                    empBatchEnrollConsecutiveAddNew = filter.substring(0, filter.indexOf("idRanFromPositionHierarchy"));
                    filterEndSign = filter.substring(
                            filter.indexOf("idRanFromPositionHierarchy") + "idRanFromPositionHierarchy".length());
                    filter = empBatchEnrollConsecutiveAddNew
                            + " id in (select fchildid from T_ORG_PositionHierarchy where FHierarchyID = '"
                            + filterEndSign + "')";
                    modelMap.put("filter", filter);
                }

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

                if (filter.indexOf("=''") != -1) {
                    filter = filter.replace("=''", " is not null");
                    modelMap.put("filter", filter);
                }

                if (filter.indexOf("empBatchEnrollConsecutiveAddNew") != -1) {
                    empBatchEnrollConsecutiveAddNew = "empBatchEnrollConsecutiveAddNew";
                    filterEndSign = "filterEndSign";
                    int start = filter.indexOf(empBatchEnrollConsecutiveAddNew);
                    int end = filter.indexOf(filterEndSign) + filterEndSign.length();
                    String partFilterStr = filter.substring(start, end);
                    String partFilterParam = partFilterStr.substring(empBatchEnrollConsecutiveAddNew.length(),
                            partFilterStr.indexOf(filterEndSign));
                    String[] partFilterParamArr = partFilterParam.split(",");
                    String partFilterStrAfterTranfer = "";
                    if (partFilterParamArr.length == 2) {
                        String bizManageTypeId = partFilterParamArr[0];
                        String manageHrOrgID = partFilterParamArr[1];
                        partFilterStrAfterTranfer = "adminOrgUnit.id in (select FAdminOrgID from T_HR_AdminOrgBURelation where fbizManagetypeId='"
                                + bizManageTypeId + "' and FManageHrOrgID = '" + manageHrOrgID + "' and fstate = 1)";
                    }

                    filter = filter.replace(partFilterStr, partFilterStrAfterTranfer);
                    modelMap.put("filter", filter);
                }
            }

            this.prepareQueryList(request, response, modelMap);
            long start = 0L;
            long end = 0L;
            if (logger.isDebugEnabled()) {
                start = (new Date()).getTime();
            }
            GridDataEntity gridDataEntity = this.getGridRequestData(request, response, modelMap);
            if (logger.isDebugEnabled()) {
                end = (new Date()).getTime();
                logger.debug(MessageFormat.format("handler: {0}, get list data, cost: {1}", this.getClass().getName(), end - start));
            }
            this.afterGetListData(request, response, gridDataEntity);
            this.doFieldPermFilter(gridDataEntity);
            try {
                //新增开始结束数据
                List<Map<String, Object>> rows = gridDataEntity.getRows();
                for (Map<String, Object> map : rows) {
                    String positionNumber = (String) map.get("number");
                    String effdeAndLeffdeSql = getEffdeAndLeffdeSql(personId, positionNumber);
                    logger.error("effdeAndLeffdeSql" + effdeAndLeffdeSql);
                    IRowSet rowSet = DbUtil.executeQuery(ctx, effdeAndLeffdeSql);
                    if (rowSet.next()) {
                        map.put("EmpPosOrgRelation.EFFDT", rowSet.getString("effdt"));
                        map.put("EmpPosOrgRelation.LEFFDT", rowSet.getString("leffdt"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            JSONUtils.writeJson(response, gridDataEntity);
        }
        return null;
    }

    public String getEffdeAndLeffdeSql(String personId, String positionNumber) {
        StringBuilder sb = new StringBuilder();
        sb.append("select ").append("\n");
        sb.append("porgerelation.feffdt as effdt ,").append("\n");
        sb.append("porgerelation.fleffdt as leffdt ").append("\n");
        sb.append("from T_HR_EMPORGRELATION porgerelation").append("\n");
        sb.append("left join T_ORG_Position position on porgerelation.FPOSITIONID= position.fid").append("\n");
        sb.append(" where position.fnumber='" + positionNumber + "' ").append("\n");
        sb.append("and fpersonid = '" + personId + "' ").append("\n");
        sb.append("order by porgerelation.feffdt desc").append("\n");
        return sb.toString();
    }

}
