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

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
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.common.utils.ConvertUtil;
import nckd.jxccl.base.swc.helper.SWCHelper;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    private static final Log logger = LogFactory.getLog(AnnouncementsListPlugin.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(), "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){
            ///获取当前员工的行政组织长编码
            Long companyId = empDyns[0].getLong("company.id");
            logger.info("AnnouncementsListPlugin currEmpId:" + empId + " companyId:"+ companyId);
            qFilter = new QFilter("nckd_hradminorg.id", QCP.equals, companyId);

        }

        if (qFilterList == null  && qFilter != null) {
            //qFilter = new QFilter("number", QCP.equals, "在地愿为连理枝");
            qFilters.add(qFilter);
        }else{
            //qFilter = new QFilter("number", QCP.equals, "在地愿为连理枝");
            //qFilter = new QFilter("id", QCP.equals, 2392305707270548480L);
            qFilter = new QFilter("id", QCP.equals, 10000000000000000L);
            qFilters.add(qFilter);
        }
        e.setOrderBy("nckd_istop Desc,nckd_publishdate Desc");

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

    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        ///如果有合法检验，需要有判断是否操作成功！
        OperationResult operationResult = args.getOperationResult();
        if (operationResult != null && !operationResult.isSuccess()) {
            return;
        }
        FormOperate formOperate = (FormOperate)args.getSource();
        String key = formOperate.getOperateKey();
        switch (key) {
            case "publish":
                setBillStatus("C",key);
                break;
            case "withdraw":
                setBillStatus("A",key);
                break;
            case "top":
                setBillStatus("A",key);
                break;
            case "untop":
                setBillStatus("A",key);
                break;
            case "takedown":
                //载入党政职务履历
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId(FormConstant.NCKD_ANNOUNCE_DOWNDATE);
                showParameter.getOpenStyle().setShowType(ShowType.Modal);
                showParameter.setCaption("延长下架时间");
                showParameter.setSendToClient(true);
                showParameter.setCloseCallBack(new CloseCallBack(this, FormConstant.NCKD_ANNOUNCE_DOWNDATE));
                this.getView().showForm(showParameter);
                break;
        }
    }

    /**
     * 设置单据状态
     * @param billStatus
     * A	待处理
     * D	处理中
     * C	已处理
     * F	已忽略
     */
    public void setBillStatus(String billStatus,String operateKey) {
        ListSelectedRowCollection selectedRows = this.getSelectedRows();
        MainEntityType entityType= EntityMetadataCache.getDataEntityType(FormConstant.NCKD_ANNOUNCEMENTS);
        DynamicObject[] billDyns = BusinessDataServiceHelper.load(selectedRows.getPrimaryKeyValues(), entityType);
        for (DynamicObject billDyn : billDyns){
            if(operateKey.equals("takedown") ){
                billDyn.set("nckd_billstatus", billStatus);
            }
            if(operateKey.equals("withdraw") ){
                billDyn.set("nckd_billstatus", billStatus);
                billDyn.set("nckd_publishdate", null);
                billDyn.set("nckd_publishuser", null);
            }
            if(operateKey.equals("publish") ){
                billDyn.set("nckd_billstatus", "C");
                billDyn.set("nckd_publishdate", new java.util.Date());
                billDyn.set("nckd_publishuser", UserServiceHelper.getCurrentUserId());
            }
            if(operateKey.equals("untop") ){
                billDyn.set("nckd_istop", false);
            }
            if(operateKey.equals("top") ){
                billDyn.set("nckd_istop", true);
            }
        }

        Object[] update = SaveServiceHelper.save(billDyns);
        this.getView().showSuccessNotification(update.length + "条，操作成功", 3000);

        this.getView().updateView();

    }

    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        String actionId = closedCallBackEvent.getActionId();
        if(FormConstant.NCKD_ANNOUNCE_DOWNDATE.equalsIgnoreCase(actionId)){
            Object returnData = closedCallBackEvent.getReturnData();
            if(returnData != null) {
                Map<String, Object> map = ConvertUtil.toMap(returnData);
                Date date = ConvertUtil.toDate(map.get("downdate"));
                setDowndate(date);
            }
        }
    }

    public void setDowndate(Date date) {
        ListSelectedRowCollection selectedRows = this.getSelectedRows();
        MainEntityType entityType= EntityMetadataCache.getDataEntityType(FormConstant.NCKD_ANNOUNCEMENTS);
        DynamicObject[] billDyns = BusinessDataServiceHelper.load(selectedRows.getPrimaryKeyValues(), entityType);
        for (DynamicObject billDyn : billDyns){
            billDyn.set("nckd_downdate", date);
            billDyn.set("nckd_billstatus", "C");
        }
        Object[] update = SaveServiceHelper.save(billDyns);
        this.getView().showSuccessNotification(update.length + "条，操作成功", 3000);
    }


}