package nckd.jxccl.hr.gzbb;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
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 java.util.*;

/**
 * 央国企人事云》国资报表ext》单据》数据填报
 * 数据填报初始化各级单位信息统计表
 * nckd_sjtbrw
 * duanyuqi
 * */
public class SjtbInitXxtjFormPlugin extends AbstractFormPlugin {
    private static final Log logger = LogFactory.getLog(SjtbInitXxtjFormPlugin.class);
    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs ags) {
        FormOperate formOperate = (FormOperate) ags.getSource();
        if ("nckd_getxxtji".equals(formOperate.getOperateKey())) { // 拉取各级单位信息统计表数据
            //this.getView().showLoading(new LocaleString("正在加载"));
            // 获取集团本部的信息
            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
            Long orgIdBenbu = orgDynamicObjectBenbu.getLong("id");// 集团本部Id
            Long tbzzId = this.getModel().getDataEntity().getLong("org.id");// 填报组织id
            Date tbSjny = this.getModel().getDataEntity().getDate("nckd_tbsjny");// 填报数据年月
            DynamicObject orgHrDynamicObjectTbzz = BusinessDataServiceHelper.loadSingle(tbzzId, "haos_adminorghr", "id,name,structnumber,structlongnumber,simplename,nckd_sscj.id,nckd_sscj.nckd_sjcj.id,parent.id,nckd_sssjgsdata.id");
            DynamicObject orgDynamicObjectTbzz = BusinessDataServiceHelper.loadSingle(tbzzId, "bos_org", "id,number,name,uniformsocialcreditcode,ffirmname,ftaxregnum");
            String tbUniformsocialcreditcode = orgDynamicObjectTbzz.getString("uniformsocialcreditcode");// 填报组织统一社会信用代码;
            // 获取填报组织所属上级公司的信息
            Long tbParentOrgId = 0L;
            String tbParentUniformsocialcreditcode = "";
            if (tbzzId.equals(orgIdBenbu) || tbzzId.equals(topParentOrgId)) {// 填报组织是集团本部 或 是根组织
                tbParentOrgId = topParentOrgId;// 根组织 id
                tbParentUniformsocialcreditcode = uniformsocialcreditcodeBenbu;// 集团本部统一社会信用代码
            } else  {
                tbParentOrgId = orgHrDynamicObjectTbzz.getLong("nckd_sssjgsdata.id");// 所属上级公司id
                if (tbParentOrgId.equals(0L)) {
                    tbParentOrgId = tbzzId;
                }
                if (tbParentOrgId.equals(topParentOrgId)) {// 上级组织是根组织
                    tbParentUniformsocialcreditcode = uniformsocialcreditcodeBenbu;
                } else {
                    DynamicObject tbParentOrgDynamicObject = BusinessDataServiceHelper.loadSingle(tbParentOrgId, "bos_org", "id,number,name,uniformsocialcreditcode,ffirmname,ftaxregnum");
                    tbParentUniformsocialcreditcode = tbParentOrgDynamicObject.getString("uniformsocialcreditcode");// 上级公司统一社会信用代码;
                }
            }

            // 查询所有下级组织
            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) {
                // 将所有的HR行政组织放到map中
                Map<Object, DynamicObject> hrObjMap = new LinkedHashMap<Object, DynamicObject>();
                Long[] orgIds = new Long[hrObjectCollection.size()];
                for (int i = 0; i < hrObjectCollection.size(); i++) {
                    DynamicObject dynamicObject = hrObjectCollection.get(i);
                    orgIds[i] = dynamicObject.getLong("id");
                    hrObjMap.put(dynamicObject.get("id"), dynamicObject);
                }
                // 获取所有的业务单元
                List<QFilter> qfilterYwdy = new ArrayList<QFilter>();
                qfilterYwdy.add(new QFilter("id", "in", orgIds));
                QFilter[] filtersYwdy = (QFilter[]) qfilterYwdy.toArray(new QFilter[qfilterYwdy.size()]);
                String selectYwdyFields = "id,number,name,uniformsocialcreditcode,ffirmname,ftaxregnum";
                DynamicObjectCollection ywdyObjectCollection = QueryServiceHelper.query("bos_org", selectYwdyFields, filtersYwdy);
                // 将所有的业务单元放到map中
                Map<Object, DynamicObject> ywdyObjMap = new LinkedHashMap<Object, DynamicObject>();
                for (int i = 0; i < ywdyObjectCollection.size(); i++) {
                    DynamicObject dynamicObject = ywdyObjectCollection.get(i);
                    ywdyObjMap.put(dynamicObject.get("id"), dynamicObject);
                }
                IDataModel dataModel = this.getModel();
                int createNewRow = hrObjectCollection.size();
                int newRow = this.getModel().getEntryEntity("nckd_gjdwtjbentry").size();
                dataModel.batchCreateNewEntryRow("nckd_gjdwtjbentry", createNewRow);

                // 遍历HR行政组织
                Set<Object> hrObjKeys = hrObjMap.keySet();
                for (Object hrObjKey : hrObjKeys) {
                    DynamicObject ywdyObject = ywdyObjMap.get(hrObjKey);
                    DynamicObject hrObject = hrObjMap.get(hrObjKey);
                    Object pkId = hrObject.get("id");// 单位名称
                    dataModel.setValue("nckd_atjny", tbSjny, newRow);// 统计年月
                    dataModel.setValue("nckd_axydm", uniformsocialcreditcodeBenbu, newRow);// 所属集团统一社会信用代码
                    dataModel.setValue("nckd_ajtzcdata", topParentOrgId, newRow);// 所属集团注册名称

                    Object uniformsocialcreditcode = ywdyObject.get("uniformsocialcreditcode");// 统一社会信用代码
                    if (!isNullEmpty(uniformsocialcreditcode)) {
                        dataModel.setValue("nckd_azjqxydm", uniformsocialcreditcode, newRow);
                    }
                    dataModel.setValue("nckd_azqydwdata", pkId, newRow);// 子企业单位名称
                    Object simplename = hrObject.get("simplename");// 企业简称
                    if (!isNullEmpty(simplename)) {
                        dataModel.setValue("nckd_aqyjc", simplename, newRow);
                    }

                    if (tbzzId.equals(pkId)) { // 填报组织
                        dataModel.setValue("nckd_asjqyxydm", tbParentUniformsocialcreditcode, newRow);// 所属上级企业统一社会信用代码
                        dataModel.setValue("nckd_asjqydata", tbParentOrgId, newRow);// 所属上级企业名称
                    } else {
                        if (topParentOrgId.equals(pkId)) {
                            dataModel.setValue("nckd_asjqyxydm", uniformsocialcreditcodeBenbu, newRow);// 所属上级企业统一社会信用代码
                        } else {
                            dataModel.setValue("nckd_asjqyxydm", tbUniformsocialcreditcode, newRow);// 所属上级企业统一社会信用代码
                        }
                        dataModel.setValue("nckd_asjqydata", tbzzId, newRow);// 所属上级企业名称
                    }

                    Object nckd_qyszhy = hrObject.get("nckd_qyszhy.id");// 企业所在行业
                    if (!isNullEmpty(nckd_qyszhy)) {
                        dataModel.setValue("nckd_azqyszhy", nckd_qyszhy, newRow);
                    }
                    Object nckd_gjdq = hrObject.get("nckd_gjdq.id");// 企业所在国家和地区
                    if (!isNullEmpty(nckd_gjdq)) {
                        dataModel.setValue("nckd_azqygj", nckd_gjdq, newRow);
                    }
                    Object nckd_xzqh = hrObject.get("nckd_xzqh.id");// 企业所在地市
                    if (!isNullEmpty(nckd_xzqh)) {
                        dataModel.setValue("nckd_azqyszdq", nckd_xzqh, newRow);
                    }
                    Object nckd_sscj = hrObject.get("nckd_sscj.id");// 企业所属层级
                    if (!isNullEmpty(nckd_sscj)) {
                        dataModel.setValue("nckd_azqysscj", nckd_sscj, newRow);
                    }
                    Object nckd_qygm = hrObject.get("nckd_qygm.id");// 企业规模
                    if (!isNullEmpty(nckd_qygm)) {
                        dataModel.setValue("nckd_azqygm", nckd_qygm, newRow);
                    }
                    Object nckd_sslx = hrObject.get("nckd_sslx.id");// 上市类型
                    if (!isNullEmpty(nckd_sslx)) {
                        dataModel.setValue("nckd_asslx", nckd_sslx, newRow);
                    }
                    Object nckd_sfnrhbbb = hrObject.get("nckd_sfnrhbbb");// 是否纳入合并报表
                    if (!isNullEmpty(nckd_sfnrhbbb)) {
                        dataModel.setValue("nckd_asfnrhbbb", nckd_sfnrhbbb, newRow);
                    }
                    Object nckd_sfsykjxqy = hrObject.get("nckd_sfsykjxqy");// 是否属于科技型企业
                    if (!isNullEmpty(nckd_sfsykjxqy)) {
                        dataModel.setValue("nckd_asfsykjxqy", nckd_sfsykjxqy, newRow);
                    }
                    Object nckd_kjxqylx = hrObject.get("nckd_kjxqylx.id");// 科技型企业类型
                    if (!isNullEmpty(nckd_kjxqylx)) {
                        dataModel.setValue("nckd_akjxqylx", nckd_kjxqylx, newRow);
                    }
                    Object nckd_qyfl = hrObject.get("nckd_qyfl.id");// 企业分类
                    if (!isNullEmpty(nckd_qyfl)) {
                        dataModel.setValue("nckd_aqyfl", nckd_qyfl, newRow);
                    }
                    Object nckd_zcqjl = hrObject.get("nckd_zcqjl");// 是否实施中长期激励
                    if (!isNullEmpty(nckd_zcqjl)) {
                        dataModel.setValue("nckd_azcqjl", nckd_zcqjl, newRow);
                    }
                    Object nckd_jbsszcqjl = hrObject.get("nckd_jbsszcqjl");// 是否具备实施中长期激励
                    if (!isNullEmpty(nckd_jbsszcqjl)) {
                        dataModel.setValue("nckd_ajbsszcqjl", nckd_jbsszcqjl, newRow);
                    }
                    Object nckd_zqypxm = hrObject.get("nckd_zqypxm");// 企业排序码
                    if (!isNullEmpty(nckd_zqypxm)) {
                        dataModel.setValue("nckd_azqypxm", nckd_zqypxm, newRow);
                    }
                    newRow ++;
                }
            }
            //this.getView().showLoading(new LocaleString("正在加载"), 1);
        }
        super.afterDoOperation(ags);
    }

    public static boolean isNullEmpty(Object obj) {
        return obj == null || (obj instanceof String && ((String) obj).isEmpty());
    }

    /**获取填报组织的上级*/
    public DynamicObject findParentOrg(DynamicObject orgHrDynamicObject, Object checkSscj, Object topParentOrgId) {
        Object orgId = orgHrDynamicObject.get("id");
        if (orgId.equals(topParentOrgId)) { // 根组织直接返回
            return orgHrDynamicObject;
        }
        Object tbPatentId = orgHrDynamicObject.get("parent.id");
        DynamicObject parentDynamicObject = BusinessDataServiceHelper.loadSingle(tbPatentId, "haos_adminorghr", "id,name,structnumber,structlongnumber,simplename,nckd_sscj.id,parent.id");
        Object parentId = parentDynamicObject.get("id");
        if (parentId.equals(topParentOrgId)) { // 根组织直接返回
            return parentDynamicObject;
        }
        Object parentSscj = parentDynamicObject.get("nckd_sscj.id");
        if (isNullEmpty(parentSscj)) {
            return findParentOrg(parentDynamicObject, checkSscj, topParentOrgId);
        } else {
            if (parentSscj.equals(checkSscj)) {
                return parentDynamicObject;
            } else {
                return findParentOrg(parentDynamicObject, checkSscj, topParentOrgId);
            }
        }
    }

}
