/** 清理组织重名数据 */
delete from t_org_org_l where FPKID not in (select FPKID from (select MAX(FPKID) FID from t_org_org_l group by fid, flocaleid) T);
delete from t_org_structure_l where FPKID not in (select FPKID from (select MAX(FPKID) FID from t_org_structure_l group by fid, flocaleid) T);

/** 清理视图方案不存在的组织结构数据 */
delete from t_org_structure where fviewid not in (select fid from t_org_viewschema);
delete from t_org_structure_l where fid not in (select fid from t_org_structure);

-- 勾选是否业务组织
update t_org_org o set fisbizorg = '0' where NOT EXISTS (SELECT 1 from t_org_structure where o.FID = FORGID AND fviewid not in (1));
update t_org_org o set fisbizorg = '1' where EXISTS (SELECT 1 from t_org_structure where o.FID = FORGID AND fviewid not in (1));


/** 更新是否叶子节点 */
update t_org_structure p set fisleaf = '1' where NOT EXISTS(select fparentid from (select c.fparentid,c.FVIEWID from t_org_structure c) as tmp where tmp.fviewid = p.fviewid and p.forgid = tmp.fparentid);
update t_org_structure p set fisleaf = '0' where EXISTS(select fparentid from (select c.fparentid,c.FVIEWID from t_org_structure c) as tmp where tmp.fviewid = p.fviewid and p.forgid = tmp.fparentid);

/* 更新职能类型ID */
UPDATE t_org_viewschema SET ftreetypeid = isnull((SELECT max(t.fid) FROM t_org_bizlist T WHERE fnumber = t_org_viewschema.ftreetype), 0) WHERE ftreetypeid = 0;

/* 非预置的视图方案都设置为非默认视图 */
update t_org_viewschema set fisdefault = '0' where fisdefault = '1' and ftreetypeid in (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40) and fid not in (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40);

/** 更新组织视图方案的管控单元标志：非主数据控制视图时，全部是管控单元 */
update t_org_structure set fisctrlunit = '1' where fisctrlunit = '0' and fviewid in (select fid from t_org_viewschema where ftreetype != '16' and ftreetypeid != 16);