package nckd.jxccl.hr.gzbb;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.AfterDeleteEntryEventArgs;
import kd.bos.entity.datamodel.events.BeforeDeleteRowEventArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.*;

/**
 * 央国企人事云》国资报表ext》单据》数据填报
 * 数据填报表单插件
 * nckd_sjtbrw
 * duanyuqi
 * */
public class SjtbCheckFormPlugin extends AbstractFormPlugin {
    private static final Log logger = LogFactory.getLog(SjtbCheckFormPlugin.class);

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        OperationResult operationResult = args.getOperationResult();
        // 够获取页面配置的校验规则的执行结果
        if (operationResult != null && !operationResult.isSuccess()) {
            return;
        }
        FormOperate formOperate = (FormOperate) args.getSource();
        if ("nckd_zjspbtn".equals(formOperate.getOperateKey())) { // 直接审批
            this.getModel().setValue("billstatus", "C");// 已审核
            this.getModel().setValue("nckd_rwzt", "1");// 待上报
            Object[] result = SaveServiceHelper.save(new DynamicObject[]{this.getModel().getDataEntity()});
            DynamicObject dynamicObject = (DynamicObject) result[0];
            SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
            this.getView().showSuccessNotification("审核成功");
            this.getView().invokeOperation("refresh");
        } else if ("nckd_fshbtn".equals(formOperate.getOperateKey())) { // 反审核
            Long pkValue = (Long) this.getModel().getDataEntity().getPkValue();
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(pkValue, "nckd_sjtbrw");
            dynamicObject.set("billstatus", "A");// 暂存
            dynamicObject.set("nckd_rwzt", "1");// 待上报
            SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
            this.getView().showSuccessNotification("反审核成功");
            this.getView().invokeOperation("refresh");
        } else if ("nckd_sbbtn".equals(formOperate.getOperateKey())) { // 上报
            //上报操作前让用户选择是否继续上报操作，在用户点击确认框上的按钮后，系统会调用confirmCallBack方法
            ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("querenshangbaoOp", this);
            //设置页面确认框，参数为：标题，选项框类型，回调监听
            this.getView().showConfirm("请确认是否上报吗？", MessageBoxOptions.YesNo, confirmCallBackListener);
        } else if ("nckd_scbtn".equals(formOperate.getOperateKey())) { // 删除
            //上报操作前让用户选择是否继续上报操作，在用户点击确认框上的按钮后，系统会调用confirmCallBack方法
            ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("querenShanChuOp", this);
            //设置页面确认框，参数为：标题，选项框类型，回调监听
            this.getView().showConfirm("请确认是否删除吗？", MessageBoxOptions.YesNo, confirmCallBackListener);
        }
        super.afterDoOperation(args);
    }

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

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        // TODO Auto-generated method stub
        super.confirmCallBack(messageBoxClosedEvent);
        //判断回调参数id
        if("querenshangbaoOp".equals(messageBoxClosedEvent.getCallBackId())){
            if (MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
                Long pkValue = (Long) this.getModel().getDataEntity().getPkValue();
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(pkValue, "nckd_sjtbrw");
                dynamicObject.set("nckd_rwzt", "2");// 已上报
                SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
                this.getView().showSuccessNotification("上报成功");
                this.getView().invokeOperation("refresh");
            }
        } else if("querenShanChuOp".equals(messageBoxClosedEvent.getCallBackId())){
            if (MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
                Long pkValue = (Long) this.getModel().getDataEntity().getPkValue();
                boolean isDelete = PushSjcjDataUtils.deleteSjcjHzBill(pkValue);
                if (isDelete) {
                    //this.getView().showSuccessNotification("删除成功");
                    List<QFilter> qfilterQuery = new ArrayList<QFilter>();
                    qfilterQuery.add(new QFilter("id", "=", pkValue));
                    QFilter[] filtersQuery = (QFilter[]) qfilterQuery.toArray(new QFilter[qfilterQuery.size()]);
                    DeleteServiceHelper.delete("nckd_sjtbrw", filtersQuery);
                    this.getView().close();
                }
            }
        }
    }

    @Override
    public void afterDeleteEntry(AfterDeleteEntryEventArgs e) {
        super.afterDeleteEntry(e);
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        String name = e.getEntryProp().getName();
        if ("nckd_dwrgcbentry".equals(name)) {
            // 各单位人工成本统计表删除行逻辑
            EntryGrid entry = this.getControl("nckd_dwrgcbentry");
            DynamicObjectCollection entryColl = this.getModel().getEntryEntity("nckd_dwrgcbentry");
            int[] rows = entry.getSelectRows();
            Long zero = 0L;
            Set<Long> nckdCzzdataSet = new HashSet<Long>();
            Map<Long, Integer> nckdCzzdataCwMap = new HashMap<Long, Integer>();
            Map<Long, Integer> nckdCzzdataRsMap = new HashMap<Long, Integer>();
            for (int i = 0; i < rows.length; i++) {
                DynamicObject dynamicObject = entryColl.get(rows[i]);
                Long czzdataId = dynamicObject.getLong("nckd_czzdata.id");
                if (!zero.equals(czzdataId)) {
                    nckdCzzdataCwMap.put(czzdataId, dynamicObject.getInt("nckd_lycwh"));
                    nckdCzzdataRsMap.put(czzdataId, dynamicObject.getInt("nckd_lyrsh"));
                    nckdCzzdataSet.add(czzdataId);
                }
            }
            if (nckdCzzdataSet.size() > 0) {
                // 各单位人工成本统计表财务
                List<DynamicObject> rmCwList = new ArrayList<DynamicObject>();
                DynamicObjectCollection entryCollCw = this.getModel().getEntryEntity("nckd_dwrgcbentrycw");
                for (int i = 0; i < entryCollCw.size(); i++) {
                    DynamicObject dynamicObject = entryCollCw.get(i);
                    Long czzdataId = dynamicObject.getLong("nckd_cazzdata.id");
                    Integer seq = dynamicObject.getInt("seq");
                    if (nckdCzzdataCwMap.get(czzdataId) != null) {
                        Integer lycwh = nckdCzzdataCwMap.get(czzdataId);
                        if (seq.intValue() == lycwh.intValue()) {
                            rmCwList.add(dynamicObject);
                        }
                    }
                }
                if (rmCwList.size() > 0) {
                    for (DynamicObject rmRow:rmCwList) {
                        entryCollCw.remove(rmRow);
                    }
                    this.getView().updateView("nckd_dwrgcbentrycw");
                }

                // 各单位人工成本统计表人事
                List<DynamicObject> rmRsList = new ArrayList<DynamicObject>();
                DynamicObjectCollection entryCollRs = this.getModel().getEntryEntity("nckd_dwrgcbentryrs");
                for (int i = 0; i < entryCollRs.size(); i++) {
                    DynamicObject dynamicObject = entryCollRs.get(i);
                    Long czzdataId = dynamicObject.getLong("nckd_cbzzdata.id");
                    Integer seq = dynamicObject.getInt("seq");
                    if (nckdCzzdataRsMap.get(czzdataId) != null) {
                        Integer lyrsh = nckdCzzdataRsMap.get(czzdataId);
                        if (seq.intValue() == lyrsh.intValue()) {
                            rmRsList.add(dynamicObject);
                        }
                    }
                }
                if (rmRsList.size() > 0) {
                    for (DynamicObject rmRow:rmRsList) {
                        entryCollRs.remove(rmRow);
                    }
                    this.getView().updateView("nckd_dwrgcbentryrs");
                }
            }
        }
        super.beforeDeleteRow(e);
    }
}
