package nckd.jxccl.hr.gzbb;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
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.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.control.Control;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.OrgEdit;
import kd.bos.form.field.events.AfterF7SelectEvent;
import kd.bos.form.field.events.AfterF7SelectListener;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
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 org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * 央国企人事云》国资报表ext》单据》数据填报
 * 数据填报所有单据体通用插件
 * nckd_sjtbrw
 * duanyuqi
 * */
public class SjtbInitRowDataFormPlugin extends AbstractFormPlugin implements AfterF7SelectListener, BeforeF7SelectListener {
    private static final Log logger = LogFactory.getLog(SjtbInitRowDataFormPlugin.class);

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

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs adoea) {
        FormOperate formOperate = (FormOperate) adoea.getSource();
        if ("gjdwtjbentry".equals(formOperate.getOperateKey())) { // 各级单位信息统计表添加
            int row = this.getModel().getEntryCurrentRowIndex("nckd_gjdwtjbentry");
            this.getModel().setValue("nckd_ajtzcdata", 0, row);
            this.getModel().setValue("nckd_azqydwdata", 0, row);
            this.getModel().setValue("nckd_asjqydata", 0, row);
        } else if ("cgxxtjbtj".equals(formOperate.getOperateKey())) {// 单位参股信息统计表添加
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwcgxxentry");
            this.getModel().setValue("nckd_bssjtdata", 0, row);
            this.getModel().setValue("nckd_bcgqydata", 0, row);
            this.getModel().setValue("nckd_bsssjqydata", 0, row);
        } else if ("dwrgcbtjbtj".equals(formOperate.getOperateKey())) {// 人工成本信息统计表添加
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwrgcbentry");
            Object orgId = this.getModel().getDataEntity().get("org.id");
            DynamicObject orgObject = BusinessDataServiceHelper.loadSingle(orgId, "bos_org");
            String uniformsocialcreditcode = orgObject.getString("uniformsocialcreditcode");// 统一社会信用代码;
            this.getModel().setValue("nckd_czzdata", orgId, row);
            this.getModel().setValue("nckd_czqyxxdm", uniformsocialcreditcode, row);
        } else if ("dwrgcbtjbtjcw".equals(formOperate.getOperateKey())) {// 人工成本信息统计表添加-财务
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwrgcbentrycw");
            Object orgId = this.getModel().getDataEntity().get("org.id");
            DynamicObject orgObject = BusinessDataServiceHelper.loadSingle(orgId, "bos_org");
            String uniformsocialcreditcode = orgObject.getString("uniformsocialcreditcode");// 统一社会信用代码;
            this.getModel().setValue("nckd_cazzdata", orgId, row);
            this.getModel().setValue("nckd_cazqyxxdm", uniformsocialcreditcode, row);
        } else if ("dwrgcbtjbtjrs".equals(formOperate.getOperateKey())) {// 人工成本信息统计表添加-人事
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwrgcbentryrs");
            Object orgId = this.getModel().getDataEntity().get("org.id");
            DynamicObject orgObject = BusinessDataServiceHelper.loadSingle(orgId, "bos_org");
            String uniformsocialcreditcode = orgObject.getString("uniformsocialcreditcode");// 统一社会信用代码;
            this.getModel().setValue("nckd_cbzzdata", orgId, row);
            this.getModel().setValue("nckd_cbzqyxxdm", uniformsocialcreditcode, row);
        } else if ("zgsrqktjbtj".equals(formOperate.getOperateKey())) {// 职工收入信息统计表添加
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwzgsrentry");
            this.getModel().setValue("nckd_dzqydwdata", 0, row);
            this.getModel().setValue("nckd_dxmdata", 0, row);
        } else if ("ldqktjbtj".equals(formOperate.getOperateKey())) {// 劳动情况信息统计表添加
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwldqkentry");
            this.getModel().setValue("nckd_gzzdata", 0, row);
        } else if ("dybxtjbtj".equals(formOperate.getOperateKey())) {// 履职待遇信息统计表添加
            int row = this.getModel().getEntryCurrentRowIndex("nckd_dwdybxentry");
            this.getModel().setValue("nckd_fzzdata", 0, row);
            //this.getModel().setValue("nckd_fyhdata", 0, row);
        }
        super.afterDoOperation(adoea);
    }

    @Override
    public void registerListener(EventObject e) {
        //单位信息表
        BasedataEdit ajtzcdata = this.getView().getControl("nckd_ajtzcdata");//所属集团注册名称
        BasedataEdit azqydwdata = this.getView().getControl("nckd_azqydwdata");//子企业单位名称
        BasedataEdit asjqydata = this.getView().getControl("nckd_asjqydata");//所属上级企业名称
        //参股信息表
        BasedataEdit bssjtdata = this.getView().getControl("nckd_bssjtdata");//所属集团注册名称
        BasedataEdit bcgqydata = this.getView().getControl("nckd_bcgqydata");//参股企业单位名称
        BasedataEdit bsssjqydata = this.getView().getControl("nckd_bsssjqydata");//所属上级企业名称
        //人工成本表
        BasedataEdit czzdata = this.getView().getControl("nckd_czzdata");//子企业单位名称
        //职工收入情况表
        BasedataEdit dzqydwdata = this.getView().getControl("nckd_dzqydwdata");//子企业单位名称
        BasedataEdit dxmdata = this.getView().getControl("nckd_dxmdata");//姓名
        //劳动情况表
        BasedataEdit gzzdata = this.getView().getControl("nckd_gzzdata");//单位名称
        //履职待遇表
        BasedataEdit fzzdata = this.getView().getControl("nckd_fzzdata");//单位名称
        BasedataEdit fyhdata = this.getView().getControl("nckd_fyhdata");//姓名

        ajtzcdata.addAfterF7SelectListener(this);
        azqydwdata.addAfterF7SelectListener(this);
        asjqydata.addAfterF7SelectListener(this);
        bssjtdata.addAfterF7SelectListener(this);
        bcgqydata.addAfterF7SelectListener(this);
        bsssjqydata.addAfterF7SelectListener(this);
        czzdata.addAfterF7SelectListener(this);
        dzqydwdata.addAfterF7SelectListener(this);
        dxmdata.addAfterF7SelectListener(this);
        dxmdata.addBeforeF7SelectListener(this);
        gzzdata.addAfterF7SelectListener(this);
        fzzdata.addAfterF7SelectListener(this);
        fyhdata.addAfterF7SelectListener(this);
        fyhdata.addBeforeF7SelectListener(this);
        super.registerListener(e);
    }


    @Override
    public void afterF7Select(AfterF7SelectEvent afterF7SelectEvent) {
        Control ctrl = (Control)afterF7SelectEvent.getSource();
        String fieldKey = ctrl.getKey();
        ListSelectedRowCollection list = afterF7SelectEvent.getListSelectedRowCollection();
        if ("nckd_fyhdata".equals(fieldKey)) {// 企业负责人履职待遇、业务支出和社会保险统计表字段
            // 姓名
            setValueDwdybxentry("nckd_dwdybxentry", fieldKey,  list);
        } else if ("nckd_czzdata".equals(fieldKey)) {// 各级单位人工成本统计表字段
            // 子企业单位名称
            setValueDwrgcbentry("nckd_dwrgcbentry", fieldKey,  list);
        } else if ("nckd_bcgqydata".equals(fieldKey)) {// 各级单位参股企业信息统计表字段
            // 参股企业单位名称
            setValueDwcgxxentry("nckd_bcgqydata", fieldKey,  list);
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        String ftName = beforeF7SelectEvent.getProperty().getName();
        if ("nckd_dxmdata".equals(ftName)) { // 各级单位职工收入情况统计表选择用户
            Object orgId = this.getModel().getDataEntity().get("org.id");// 填报组织Id
            ListShowParameter listShowParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
            listShowParameter.getListFilterParameter().setFilter(new QFilter("adminorg.company.id", "=", orgId));
            // 获取指定用户集合
            Object[] userIds = findHeSuanMingDanUserPersonId();
            listShowParameter.getListFilterParameter().setFilter(new QFilter("person.id", "in", userIds));
        } else if ("nckd_fyhdata".equals(ftName)) { // 企业负责人履职待遇、业务支出和社会保险统计表选择用户
            Object orgId = this.getModel().getDataEntity().get("org.id");// 填报组织Id
            ListShowParameter listShowParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
            listShowParameter.getListFilterParameter().setFilter(new QFilter("adminorg.company.id", "=", orgId));
        }
    }

    /**各级单位参股企业信息统计表*/
    public void setValueDwcgxxentry(String entryKey, String fieldKey, ListSelectedRowCollection list) {
        int index = this.getModel().getEntryCurrentRowIndex(entryKey);
        for (ListSelectedRow row : list) {
            Object selectedId = row.getPrimaryKeyValue();
            if ("nckd_bcgqydata".equals(fieldKey)) {// 参股企业单位名称
                DynamicObject orgDynamicObjectHr = getOrgObjectHr(selectedId);
                DynamicObject orgDynamicObjectYwdy = getOrgObjectYwdy(selectedId);
                // 获取集团本部的信息
                List<QFilter> qfilterBenbu = new ArrayList<QFilter>();
                qfilterBenbu.add(new QFilter("number", "=", "101"));
                QFilter[] filtersQueryBenbu = (QFilter[]) qfilterBenbu.toArray(new QFilter[qfilterBenbu.size()]);
                DynamicObject orgHrDynamicObjectBenbu = BusinessDataServiceHelper.loadSingle("haos_adminorghr", "id,name,structnumber,structlongnumber,simplename,parent.id", filtersQueryBenbu);
                DynamicObject orgDynamicObjectBenbu = BusinessDataServiceHelper.loadSingle("bos_org", "id,number,name,uniformsocialcreditcode,ffirmname,ftaxregnum", filtersQueryBenbu);
                String uniformsocialcreditcodeBenbu = orgDynamicObjectBenbu.getString("uniformsocialcreditcode");// 集团本部统一社会信用代码
                Long topParentOrgId = orgHrDynamicObjectBenbu.getLong("parent.id");// 根组织 id
                if (selectedId.equals(topParentOrgId)) {
                    return;
                }

                this.getModel().setValue("nckd_bssjtxxdm", uniformsocialcreditcodeBenbu, index);// 所属集团统一社会信用代码
                this.getModel().setValue("nckd_bssjtdata", topParentOrgId, index);// 所属集团名称
                this.getModel().setValue("nckd_bcgqyxxdm", orgDynamicObjectYwdy.getString("uniformsocialcreditcode"), index);//参股企业统一社会信用代码
                this.getModel().setValue("nckd_bqyjc", orgDynamicObjectHr.getString("simplename"), index);//企业简称

                Long parentId = orgDynamicObjectHr.getLong("nckd_sssjgsdata.id");
                if (parentId.equals(topParentOrgId)) {
                    this.getModel().setValue("nckd_sssjxxdm", uniformsocialcreditcodeBenbu, index);//参股企业统一社会信用代码
                } else {
                    if (!parentId.equals(0L)) {
                        DynamicObject parentOrgDynamicObject = getOrgObjectYwdy(parentId);
                        this.getModel().setValue("nckd_sssjxxdm", parentOrgDynamicObject.get("uniformsocialcreditcode"), index);//参股企业统一社会信用代码
                    }
                }
                this.getModel().setValue("nckd_bsssjqydata", parentId, index);//所属上级企业名称
                this.getModel().setValue("nckd_bcgqyszhy", orgDynamicObjectHr.get("nckd_qyszhy.id"), index);//参股企业所在行业
                this.getModel().setValue("nckd_bcgqygj", orgDynamicObjectHr.get("nckd_gjdq.id"), index);//参股企业所在国家和地区
                this.getModel().setValue("nckd_bcgqyds", orgDynamicObjectHr.get("nckd_xzqh.id"), index);//参股企业所在地市
                index ++;
            }
        }
    }

    /**各级单位人工成本统计表*/
    public void setValueDwrgcbentry(String entryKey, String fieldKey, ListSelectedRowCollection list) {
        int index = this.getModel().getEntryCurrentRowIndex(entryKey);
        if ("nckd_czzdata".equals(fieldKey)) {
            Object[] orgIds = new Long[list.size()];
            for (int i = 0; i < list.size(); i++) {
                orgIds[i] = list.get(i).getPrimaryKeyValue();
            }
            if (orgIds.length > 0) {
                List<QFilter> qfilter = new ArrayList<QFilter>();
                qfilter.add(new QFilter("id", "in", orgIds));
                QFilter[] filtersQuery = (QFilter[]) qfilter.toArray(new QFilter[qfilter.size()]);
                DynamicObjectCollection objectCollection = QueryServiceHelper.query("bos_org", "id,number,name,uniformsocialcreditcode,ffirmname,ftaxregnum", filtersQuery);
                for (DynamicObject object : objectCollection) {
                    String uniformsocialcreditcode = object.getString("uniformsocialcreditcode");// 统一社会信用代码;
                    this.getModel().setValue("nckd_czqyxxdm", uniformsocialcreditcode, index);
                    index ++;
                }
            }
        }
    }

    /**企业负责人履职待遇、业务支出和社会保险统计表*/
    public void setValueDwdybxentry(String entryKey, String fieldKey, ListSelectedRowCollection list) {
        int index = this.getModel().getEntryCurrentRowIndex(entryKey);
        if ("nckd_fyhdata".equals(fieldKey)) {// 用户名称
            List<Long> userIds = new ArrayList<Long>();
            List<String> idDatas = new ArrayList<String>();
            for (int i = 0; i < list.size(); i++) {
                Long id = (Long) list.get(i).getPrimaryKeyValue();
                userIds.add(id);
                idDatas.add("'"+id+"'");
            }
            if (userIds.size() > 0) {
                String idData = StringUtils.join(idDatas, ",");
                Map<Long, Object> map = new HashMap<Long, Object>();
                String ksql_ry = " select c.fid as selectid,c.fadminorgid as xzzz,a.forgid as rszz,a.fpersonid as ryid," +
                        " a.fname rymc,b.fnumber as zjhm,d.fcompanyid as gsid " +
                        " from t_hrpi_ermanfile a " +
                        " left join t_hrpi_percre b on a.fpersonid = b.fpersonid" +
                        " left join t_hrpi_depemp c on a.fpersonid = c.fpersonid" +
                        " left join t_haos_adminorg d on d.fid = c.fadminorgid  " +
                        " where b.fiscurrentversion = 1 and b.fdatastatus = 1 and b.fismajor = 1" +
                        " and a.fiscurrentversion = 1 and a.fdatastatus = 1 and a.fbusinessstatus = 1 " +
                        " and c.fid in ("+idData+")  ";
                logger.info("sql_ry:"+ksql_ry);
                DataSet dataSet_ry = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), ksql_ry);
                Iterator<Row> iterator_ry = dataSet_ry.iterator();
                while (iterator_ry.hasNext()) {
                    Row row_ry = iterator_ry.next();
                    Long selectid = row_ry.getLong("selectid");
                    map.put(selectid, row_ry.getString("zjhm") + "#" + row_ry.getLong("gsid"));
                }

                for (Long userId : userIds) {
                    if (map.get(userId) != null) {
                        String[] dataStr = map.get(userId).toString().split("#");
                        String idCard = dataStr[0];
                        Object gsid = dataStr[1];

                        this.getModel().setValue("nckd_fsfzhm", idCard, index);// 证件号码
                        this.getModel().setValue("nckd_fzzdata", gsid, index);// 单位名称
                    }
                    index ++;
                }
            }

        }
    }

    public DynamicObject getOrgObjectYwdy(Object orgId) {
        DynamicObject orgDynamicObject = BusinessDataServiceHelper.loadSingle(orgId, "bos_org", "id,number,name,uniformsocialcreditcode," +
                "ffirmname,ftaxregnum");
        return orgDynamicObject;
    }

    public DynamicObject getOrgObjectHr(Object orgId) {
        DynamicObject orgDynamicObject = BusinessDataServiceHelper.loadSingle(orgId, "haos_adminorghr", "id,name,simplename,nckd_qyszhy.id," +
                "nckd_gjdq.id,nckd_xzqh.id,nckd_sscj.id,nckd_qygm.id,nckd_sslx.id,nckd_sfnrhbbb,nckd_sfsykjxqy,nckd_kjxqylx.id,nckd_qyfl.id,nckd_zcqjl," +
                "nckd_jbsszcqjl,nckd_zqypxm,nckd_sssjgsdata.id");
        return orgDynamicObject;
    }

    public DynamicObject getUserObject(Object userId) {
        DynamicObject orgDynamicObject = BusinessDataServiceHelper.loadSingle(userId, "bos_user", "id,name,number");
        return orgDynamicObject;

    }

    public Object[] findHeSuanMingDanUserPersonId() {
        Object[] resultIds = new  Object[1];
        resultIds[0] = 0;
        // 填报数据年月
        Date nckd_tbsjny = this.getModel().getDataEntity().getDate("nckd_tbsjny");
        // 填报组织id
        Object tbzzId = this.getModel().getDataEntity().get("org.id");
        // 核算任务id
        List<Long> hsTaskId = findHeSuanRenWuIds(tbzzId, nckd_tbsjny);
        if (hsTaskId.size() > 0) {
            String ksql_rysj = " select a.fid as mingdanid,c.fpersonid as renyuanid,c.femployeeid as qiyerenyuanid " +
                    " from t_hsas_calperson a " +
                    " left join t_hsas_calperson_s a1 on a.fid = a1.fid " +
                    " left join t_hsas_calpayrolltask b on a.fcaltaskid = b.fid " +
                    " left join t_hsas_empposorgrelhr c on a.fempposorgrelhrvid = c.fid" +
                    " where b.fid in ("+hsTaskId+") and a1.fcalstatus in (4,10)  ";
            logger.info("查询人员数据：{}", ksql_rysj);
            DataSet dataSet_rysj = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), ksql_rysj);
            List<Long> personIdList = new ArrayList();
            Iterator<Row> iterator_rysj = dataSet_rysj.iterator();
            while (iterator_rysj.hasNext()) {
                Row row = iterator_rysj.next();
                personIdList.add(row.getLong("renyuanid"));
            }
            if (personIdList.size() > 0) {
                resultIds = new Object[personIdList.size()];
                for (int i = 0;i < personIdList.size();i++) {
                    resultIds[i] = personIdList.get(i);
                }
            }
        }
        return resultIds;
    }

    public List<Long> findHeSuanRenWuIds(Object tbzzId, Date nckd_tbsjny) {
        List<Long> hsrwIds = new ArrayList<Long>();
        // 查询所有下级组织
        List<QFilter> qfilterHr = new ArrayList<QFilter>();
        qfilterHr.add(new QFilter("iscurrentversion", "=", "1"));// 是否当前版本
        qfilterHr.add(new QFilter("datastatus", "=", "1"));// 数据版本状态
        qfilterHr.add(new QFilter("nckd_sssjgsdata.id", "=", tbzzId).or(new QFilter("id", "=", tbzzId)));// 所属公司为填报组织
        QFilter[] filtersQueryHr = (QFilter[]) qfilterHr.toArray(new QFilter[qfilterHr.size()]);
        String selectHrFields = "id,number,structnumber,structlongnumber,name,nckd_qyszhy.id,nckd_gjdq.id,nckd_xzqh.id,nckd_sscj.id,nckd_qygm.id,nckd_sslx.id,nckd_sfnrhbbb,nckd_sfsykjxqy" +
                ",nckd_kjxqylx.id,nckd_qyfl.id,nckd_zcqjl,nckd_jbsszcqjl,nckd_zqypxm,simplename";
        DynamicObjectCollection hrObjectCollection = QueryServiceHelper.query("haos_adminorghr", selectHrFields, filtersQueryHr, "sortcode asc");
        if (hrObjectCollection.size() > 0) {
            Long[] hrOrgIds = new Long[hrObjectCollection.size()];
            for (int i = 0; i < hrObjectCollection.size(); i++) {
                DynamicObject dynamicObject = hrObjectCollection.get(i);
                hrOrgIds[i] = dynamicObject.getLong("id");
            }
            List<QFilter> qfilterHs = new ArrayList<QFilter>();
            qfilterHs.add(new QFilter("enable", "=", "1"));// 使用状态
            qfilterHs.add(new QFilter("taskstatus", "=", "4").or(new QFilter("taskstatus", "=", "7")));// 任务状态-审批通过-已审核
            qfilterHs.add(new QFilter("org.id", "in", hrOrgIds));// 核算组织id
            qfilterHs.add(new QFilter("payrolldate", "=", nckd_tbsjny));// 薪资所属年月
            qfilterHs.add(new QFilter("payrollscene.nckd_notgzbb", "=", "0"));// 核算场景
            QFilter[] filtersQueryHs = (QFilter[]) qfilterHs.toArray(new QFilter[qfilterHs.size()]);
            String selectHsFields = "id,name,number";
            DynamicObjectCollection hsObjectCollection = QueryServiceHelper.query("hsas_calpayrolltask", selectHsFields, filtersQueryHs);
            if (hsObjectCollection.size() > 0) {
                for (int i = 0; i < hsObjectCollection.size(); i++) {
                    DynamicObject dynamicObject = hsObjectCollection.get(i);
                    hsrwIds.add(dynamicObject.getLong("id"));
                }
            }
        }
        return hsrwIds;
    }

}
