package nckd.jxccl.hr.tsc.plugin.form;

import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.swc.helper.SWCHelper;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 政策公告布局列表插件
 * @author turborao
 * 时间 2026/1/13 16:05
 */
@SuppressWarnings("unused")
public class AnnouncementsTplListPlugin extends AbstractListPlugin implements Plugin {

    private static final Log logger = LogFactory.getLog(AnnouncementsTplListPlugin.class);

    @Override
    public void setFilter(SetFilterEvent e) {
        super.setFilter(e);
        List<QFilter> qFilters = e.getQFilters();
        List<QFilter> qFilterList = null;
        if(qFilters.size()>0 && qFilters.get(0) != null) {
            qFilterList = (List) qFilters.stream().filter((qFilter) -> {
                return HRStringUtils.equals(qFilter.getProperty(), "nckd_hradminorg.id");
            }).collect(Collectors.toList());
        }

        QFilter qFilter = null;
        Long userId = UserServiceHelper.getCurrentUserId();
        DynamicObject personUserDyn = SWCHelper.queryOne(FormConstant.HRPI_PERSONUSERREL, "employee.id","user",userId);

        Long empId = 0L;
        if(personUserDyn == null){
            /**
             * 没有员工信息时，返回常量，用于测试
             */
            //empId = 2313784485549715456L;
            this.getView().showMessage("未找到员工！");
            return;
        }else {
            empId = personUserDyn.getLong("employee.id");
        }
        List<Long> employeeIds = new java.util.ArrayList<>();
        employeeIds.add(empId);
        DynamicObject[] empDyns = SWCHelper.queryEmpPosOrgRelDyns(employeeIds);
        if(empDyns != null && empDyns.length > 0){
            ///获取当前员工的行政组织长编码
            String adminOrgStructnumber = empDyns[0].getString("adminorg.structlongnumber");
            logger.info("AnnouncementsTplListPlugin currEmpId:" + empId + " AdminOrgStructnumber:"+ adminOrgStructnumber);
            ///查询符合条件的公告
            Map<Long, String> announcementsMap = queryAnnouncementsByBillStatus();
            ///组织结构编码匹配，返回符合条件的公告
            List<Long> ids = getMatchingAnnouncementIds(announcementsMap, adminOrgStructnumber);
            if(ids.size() > 0){
                qFilter = new QFilter("id", QCP.in, ids);
            }

        }

        if (qFilterList == null  && qFilter != null) {
            //qFilter = new QFilter("number", QCP.equals, "在地愿为连理枝");
            qFilters.add(qFilter);
        }else{
            if(qFilterList != null && qFilterList.size() > 0){
                QFilter adminOrgFilter = (QFilter)qFilterList.get(0);
                qFilters.remove(adminOrgFilter);
                qFilters.add(qFilter);

            }else {
                qFilter = new QFilter("id", QCP.equals, 10000000000000000L);
                qFilters.add(qFilter);
            }
        }
        e.setOrderBy("nckd_istop Desc,nckd_publishdate Desc");

        logger.info("AnnouncementsTplListPlugin setFilters:" +  e.getQFilters().toString() );
    }


    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }

    /**
     * 根据组织结构编码匹配，返回符合条件的公告ID列表
     * @param announcementsMap Map<id, structnumber> 公告ID与组织结构编码的映射
     * @param adminOrgStructnumber 当前用户的行政组织结构编码
     * @return 匹配成功的公告ID列表
     */
    public List<Long> getMatchingAnnouncementIds(Map<Long, String> announcementsMap, String adminOrgStructnumber) {
        List<Long> matchingIds = new ArrayList<>();

        // 循环遍历 announcementsMap
        for (Map.Entry<Long, String> entry : announcementsMap.entrySet()) {
            Long id = entry.getKey();
            String structnumber = entry.getValue();

            // 检查 adminOrgStructnumber 是否包含 structnumber 中的字符
            if (adminOrgStructnumber != null && structnumber != null &&
                    adminOrgStructnumber.contains(structnumber)) {
                matchingIds.add(id);
            }
        }

        return matchingIds;
    }



    /**
     * 根据 billstatus 查询公告信息并返回 Map 结构
     * @return Map<id, structnumber>
     */
    public  Map<Long, String> queryAnnouncementsByBillStatus() {
        // 设置查询条件
        QFilter filter = new QFilter("nckd_billstatus", QCP.equals, "C");

        // 执行查询
        StringBuilder sb = getBillDetailSql();
        DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), sb.toString());
        DynamicObjectCollection result = ORM.create().toPlainDynamicObjectCollection(dataSet);

        // 将结果转换为 Map<Long, String>
        Map<Long, String> resultMap = new HashMap<>();
        for (DynamicObject item : result) {
            Long id = item.getLong("fid");
            String structnumber = (String) item.get("fstructlongnumber");
            if (structnumber != null) {
                resultMap.put(id, structnumber);
            }
        }
        return resultMap;
    }

    public  StringBuilder getBillDetailSql() {

        StringBuilder sb = new StringBuilder();
        sb.append("/*dialect*/ SELECT  a.fid, \n")
                .append("e.fstructlongnumber \n")
                .append("from tk_nckd_announcements a \n")
                .append("left join tk_nckd_announcesentry b on a.fid = b.fid \n")
                .append("left join t_haos_adminstruct e on e.fadminorgid = b.fk_nckd_adminorg and e.fiscurrentdata = '1' \n")
                .append("where 1 = 1 and e.fstructprojectid = 1010 \n")
                .append("and a.fk_nckd_billstatus in ('C') \n");
        return sb;
    }
}