using System;
using System.Collections.Generic;
using System.Text;
using H3;

public  class D150516CGtools : H3.SmartForm.SmartFormController
{
    public  D150516CGtools(H3.SmartForm.SmartFormRequest request) : base(request)
    {
    }

    protected override void OnLoad(H3.SmartForm.LoadSmartFormResponse response)
    {
        base.OnLoad(response);
    }

    protected override void OnSubmit(string actionName, H3.SmartForm.SmartFormPostValue postValue, H3.SmartForm.SubmitSmartFormResponse response)
    {
        base.OnSubmit(actionName, postValue, response);
    }
}

public  class Utils {
    public  Utils() { }

    /*
        拷贝基础公共类中的日志方法
        添加表单访问日志
        schemaName 表单名称
        schemaCode 表单code
        userId 当前登录人id
        by:lins  date:2020-07-29
     */
    public static void addLog(string context, string schemaCode, string userId , H3.IEngine engine) {
        string[] sArray=context.Split(',');// 一定是单引 
        string schemaName = sArray[0];
        string IsMobileDevice = "false";
        if(sArray.Length > 1 ) IsMobileDevice = sArray[1];
        string accessCategory = "";

        switch(sArray[2]){
            case "Create":
                accessCategory = "创建";
                break;
            case "Edit":
                accessCategory = "修改";
                break;
            case "View":
                accessCategory = "预览";
                break;
            case "Remove":
                accessCategory = "删除";
                break;
            default :
                accessCategory = sArray[2];
                break;
        }
        string sourceId = "";
        if(sArray.Length > 3){
            sourceId = sArray[3];
        }

        //获取当前登录人的人员Id(只能在表单设计后端类、列表设计后端类中获取)
        //获取D00021testtable表单的表单结构对象
        H3.DataModel.BizObjectSchema aSchema = engine.BizObjectManager.GetPublishedSchema("D002033backStageMangementLog");
        //new一个D00021testtable表单的业务对象
        H3.DataModel.BizObject aBo = new H3.DataModel.BizObject(engine, aSchema, userId);
        //根据表单code查询业务表单数据,获取应用id
        H3.Data.Filter.Filter filter = new H3.Data.Filter.Filter();
        H3.Data.Filter.And and = new H3.Data.Filter.And();
        and.Add(new H3.Data.Filter.ItemMatcher("Schema", H3.Data.ComparisonOperatorType.Equal, schemaCode));    //主表ID
        filter.Matcher = and;
        H3.DataModel.BizObjectSchema schema = engine.BizObjectManager.GetPublishedSchema("D002033formMenu");  //业务表单 D002033formMenu
        H3.DataModel.BizObject[] result = H3.DataModel.BizObject.GetList(engine, H3.Organization.User.SystemUserId, schema, H3.DataModel.GetListScopeType.GlobalAll, filter);
        if(result != null && result.Length > 0) {
            aBo["application"] = Convert.ToString(result[0]["joinApplication"]);
            aBo["joinFormMenu"] = Convert.ToString(result[0]["ObjectId"]);
        }
        string accessType = "PC";
        if(IsMobileDevice == "true") {
            accessType = "mobile";
        }
        //设置业务对象的创建人为当前登录人
        aBo.CreatedBy = userId;
        aBo["SchemaName"] = schemaName;
        aBo["Schema"] = schemaCode;
        aBo["accessType"] = accessType;
        aBo["sourceId"] = sourceId;
        aBo["accessCategory"] = accessCategory;
        //设置业务对象数据为生效状态
        aBo.Status = H3.DataModel.BizObjectStatus.Effective;
        //查询日志表中的相同的记录,获取最近一条判断时间间隔是否在15秒内,在15秒内不添加日志
        H3.Data.Filter.Filter filter1 = new H3.Data.Filter.Filter();
        H3.Data.Filter.And and1 = new H3.Data.Filter.And();
        and1.Add(new H3.Data.Filter.ItemMatcher("Schema", H3.Data.ComparisonOperatorType.Equal, schemaCode));    //表单编码
        and1.Add(new H3.Data.Filter.ItemMatcher("SchemaName", H3.Data.ComparisonOperatorType.Equal, schemaName));    //表单名称
        and1.Add(new H3.Data.Filter.ItemMatcher("CreatedBy", H3.Data.ComparisonOperatorType.Equal, userId));    //创建人
        and1.Add(new H3.Data.Filter.ItemMatcher("accessType", H3.Data.ComparisonOperatorType.Equal, accessType));    //访问方式
        and1.Add(new H3.Data.Filter.ItemMatcher("accessCategory", H3.Data.ComparisonOperatorType.Equal, accessCategory));    //访问类型
        filter1.Matcher = and1;
        filter1.AddSortBy("CreatedTime", H3.Data.Filter.SortDirection.Descending);
        H3.DataModel.BizObjectSchema schema1 = engine.BizObjectManager.GetPublishedSchema("D002033backStageMangementLog");  //业务表单 D002033backStageMangementLog
        H3.DataModel.BizObject[] result1 = H3.DataModel.BizObject.GetList(engine, H3.Organization.User.SystemUserId, schema1, H3.DataModel.GetListScopeType.GlobalAll, filter1);
        if(result1 != null && result1.Length > 0) {
            DateTime date = (DateTime) result1[0]["CreatedTime"];
            double seconds = (DateTime.Now - date).TotalSeconds;
            if(seconds > 15) { 
                //将业务对象创建到数据库中
                aBo.Create();
            }
        } 
        else {
            //将业务对象创建到数据库中
            aBo.Create();
        }
    }

/*=========================================================================================================================================*/

    /*
        刷新合并唯一编码
        入参: 表单编码,where条件,合并字段,是否刷新标示,氚云引擎
        where条件: 书写格式示例 -> " where field1 = 'xxx' AND field2 = 'xxx' " 记得添加where,一般情况下约束项目工程或合同。
        表单编码: 书写格式示例 -> "D002033zjglProClass"
        合并字段: 书写格式示例 -> " concat(field1, field2, ...) " concat必须小写
        by:lins  date:2020-06-19
     */
    public static void refreshMergeOnlyCoding( string schemaCode, string where, string field, bool isRefresh, H3.IEngine engine) {

        //数据传入示例: concat(field1, field2, ...)
        //将链接字段转换成原始字段,用于查询 示例: concat(field1, field2) -> field1, field2
        string oldField = field.Replace("concat(", "");
        oldField = oldField.Replace(")", "");
        //将链接字段转换成数据库操作字段,用于更新 示例: concat(field1, field2) -> concat(b.field1, b.field2)
        field = field.Replace("(", "( b.");
        field = field.Replace(",", ",b.");
        //使用sql语句根据拼接规则进行更新合并唯一编码 将刷新标识改成1。  其中a为更新表单, b为数据源。
        string sql = " UPDATE I_" + schemaCode + " AS a ,  (SELECT objectid, " + oldField + " FROM I_" + schemaCode + " ";
        sql += getWhere(isRefresh, where);
        sql += " ) AS b  SET a.mergeOnlyCoding = " + field + "   WHERE a.objectid = b.objectid ";
        engine.Query.QueryTable(sql, null);
    }

/*=========================================================================================================================================*/

    /*
        刷新排序编码
        入参: 表单编码,where条件,拼接字段,需要处理的字段,是否刷新标示,氚云引擎
        表单编码: 书写格式示例 -> "D002033zjglProClass"
        where条件: 书写格式示例 -> " where field1 = 'xxx' AND field2 = 'xxx' " 记得添加where,一般情况下约束项目工程或合同。
        拼接字段: 书写格式示例 -> " contractCoding " 
        需要处理字段: 书写格式示例 -> " projWBSNo "
        by:lins  date:2020-06-20
     */
    public static void refreshSortCoding( string schemaCode, string where, string field, string handleField, bool isRefresh, H3.IEngine engine) {
        //按条件获取数据。
        string sql = "SELECT objectid," + handleField + "  FROM I_" + schemaCode;
        sql += getWhere(isRefresh, where);
        System.Data.DataTable table = engine.Query.QueryTable(sql, null);
        if(table != null && table.Rows.Count > 0) {
            //遍历数据进行添加修改排序编号 例 1.1.1  -> 010101

            for(int i = 0;i < table.Rows.Count; i++) {
                string num = Convert.ToString(table.Rows[i][handleField]);
                string parentNum = getSortCode(num); 
                //将新的排序编码保存进数据库
                string concat = " CONCAT('" + parentNum + "') ";
                if(field != null && field != "") {
                    concat = " CONCAT(" + field + ", '" + parentNum + "') ";
                }

                sql = " UPDATE I_" + schemaCode + " SET sequenceCoding = " + concat + " WHERE objectid = '" + table.Rows[i]["objectid"] + "' ";
                engine.Query.QueryTable(sql, null);
            }
        }
    }

/*=========================================================================================================================================*/

    /*
        刷新编码等级
        入参: 表单编码,where条件,分级依据,是否刷新标示,氚云引擎
        where条件: 书写格式示例 -> " where field1 = 'xxx' AND field2 = 'xxx' " 记得添加where,一般情况下约束项目工程或合同。
        表单编码: 书写格式示例 -> "D002033zjglProClass"
        分级依据: 书写格式示例 -> " projWBSNo " 用项目编码 1  1.1  1.1.1
        by:lins  date:2020-06-20
     */
    public static void refreshLevel( string schemaCode, string where, string field, bool isRefresh, H3.IEngine engine) {
        //使用sql语句根据拼接规则进行更新等级 将刷新标识改成1。  其中a为更新表单, b为数据源。
        //关键代码解析:CONCAT( (LENGTH("+field+") + 1) - LENGTH(REPLACE("+field+", '.', '') ), '级')
        //CONCAT为字符串拼接,  length获取字符串长度并将原始长度+1。例:1 没有.则是1-1=0 不成立。应1+1-1=1再拼接级。
        string sql = " UPDATE I_" + schemaCode + " AS a, (SELECT objectId, "+field;
        sql += " , CONCAT( (LENGTH("+field+") + 1) - LENGTH(REPLACE("+field+", '.', '') ), '级') AS lv FROM I_" + schemaCode + " ";
        sql += getWhere(isRefresh, where);
        sql += " ) AS b  SET a.level = b.lv  WHERE a.objectid = b.objectid ";
        engine.Query.QueryTable(sql, null);
    }

/*=========================================================================================================================================*/

    /*
        刷新子项标识
        入参: 表单编码,where条件,分级依据,是否刷新标示,氚云引擎
        where条件: 书写格式示例 -> " where field1 = 'xxx' AND field2 = 'xxx' " 记得添加where,一般情况下约束项目工程或合同。
        表单编码: 书写格式示例 -> "D002033zjglProClass"
        刷新依据: 书写格式示例 -> " projWBSNo " 用项目编码 1  1.1  1.1.1
        by:lins  date:2020-07-27
    */
    public static void refreshChildFlag(string schemaCode, string where, string field, bool isRefresh, H3.IEngine engine){
        string newWhere = getWhere(isRefresh, where);
        string sql = " UPDATE I_" + schemaCode + " AS a SET childFlag = CASE WHEN ( SELECT count(1) ";
        sql += " FROM ( SELECT "+field+" FROM I_" + schemaCode;
        if(string.IsNullOrEmpty(newWhere)) {
            sql += " WHERE static = '有效' ) AS b ";
        }
        else {
            sql += newWhere + " AND static = '有效' ) AS b ";
        }
        //AND static = '有效' ) AS b WHERE b.sequenceCoding LIKE CONCAT(a.sequenceCoding
        sql += " WHERE b."+field+" LIKE CONCAT(a."+field+", '%')) < 2 THEN '1' ELSE '0' END ";
        if(string.IsNullOrEmpty(newWhere)) {
            sql += " WHERE static = '有效' ";
        }
        else {
            sql += newWhere + " AND static = '有效' ";
        }
        engine.Query.QueryTable(sql, null);
    }

/*=========================================================================================================================================*/

    /*
        更新增量标示
        入参: 表单编码,where条件,是否刷新标示,氚云引擎
        where条件: 书写格式示例 -> " where field1 = 'xxx' AND field2 = 'xxx' " 记得添加where,一般情况下约束项目工程或合同。
        by:lins  date:2020-06-23
     */
    public static void updateRefreshFlag( string schemaCode, string where, bool isRefresh, H3.IEngine engine ) {
        string sql = " UPDATE I_" + schemaCode + " SET refreshFlag = 1 ";
        sql += getWhere(isRefresh, where);
        engine.Query.QueryTable(sql, null);
    }

/*=========================================================================================================================================*/

    /*
        通过枚举的方式获取数据源的where条件。
        示例: 00 01 10 11
        根据两个标识的状态返回where条件,
        by:lins date:2020-07-27
     */
    public static string getFilter(string joinProjectEngineering){
        string sql = "";
        if(!(string.IsNullOrEmpty(joinProjectEngineering))){
            sql += " WHERE joinProjectEngineering = '" + joinProjectEngineering + "' ";
        }
        return sql;
    }

/*=========================================================================================================================================*/

    /*
        将wbs编码转换成排序编码
        入参: 需要处理的编码(具体编码值)
        出参: 排序后编码
        by:lins date: 2020-06-21
     */
    public static string getSortCode(string sourceCode) {
        string parentNum = "";
        int n = 0;
        string[] numArray = sourceCode.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
        if(numArray.Length > 0) {
            //第一级wbs编码为数字则在前面补0
            if(int.TryParse(numArray[0],out n)){
                parentNum = Convert.ToString(numArray[0]).PadLeft(3, '0');
            }
            //不为数字则在前面补9
            else {
                parentNum = Convert.ToString(numArray[0]).PadLeft(3, '9');
            }
            
            //判断编码位数,用0填充
            for(int i = 1;i < numArray.Length; i++) {
                if(numArray[i].IndexOf("-") > -1) {
                    string[] numArray2 = numArray[i].Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                    for(int j = 0; j < numArray2.Length; j++) {
                        parentNum += Convert.ToString(numArray2[j]).PadLeft(3, '0');
                    }
                }
                else{
                    parentNum += Convert.ToString(numArray[i]).PadLeft(3, '0');
                }
            }
        }
        return parentNum;
    }

/*=========================================================================================================================================*/

    /*
        通过枚举的方式获取数据源的where条件。
        示例: 00 01 10 11
        根据两个标识的状态返回where条件,
        by:lins date:2020-06-20
     */
    public static string getWhere(bool isRefresh, string where) {
        string sql = "";
        //判断where有没有数据,如果没有则返回true 否则返回false
        bool whereFlag = string.IsNullOrEmpty(where);
        //如果刷新标识为真,则只更新刷新标识为0的数据,否则全部更新。  更新完毕后把刷新标识改成1.
        //isRefresh && whereFlag where没有数据且只需要更新刷新标示的数据。 11
        if(isRefresh && whereFlag) {
            sql += " WHERE refreshFlag <> 1 ";
        }
        //isRefresh && !whereFlag where有数据且需要更新刷新标示的数据。 10
        else if(isRefresh && !whereFlag) {
            sql += where + " AND refreshFlag <> 1 ";
        }
        //!isRefresh && !whereFlag where有数据且需要全部更新。
        //剩下一种可能性 -> 需要更新全部数据且没有特定的where条件  00
        else if(!isRefresh && !whereFlag) {
            sql += where;
        }
        //!isRefresh && whereFlag 需要更新全部数据且没有特定的where, 无须额外书写代码。 01
        return sql;
    }

/*=========================================================================================================================================*/

    /*
        根据用户id获取用户信息
        入参: 用户id, 氚云引擎
        出参: 当前用户id的全部用户信息
        by: lins, date: 2020-08-01
     */
    public static System.Data.DataTable getPersonnel(string userId, H3.IEngine engine){
        string sql = " SELECT * ";
        sql += " FROM I_D002033personnelManagement WHERE personnel = '" + userId + "' AND static = '有效'";
        return engine.Query.QueryTable(sql, null);
    }

/*=========================================================================================================================================*/

    /*
        将字符串类型转换为2位小数的双精度浮点类型
        入参: 需要处理的字符串(以对象的形式传入)
        出参: 处理后的双精度浮点
        by: lins, date: 2020-08-17
     */
    public static double toDoubleByString(object str){
        //将字符串转换为双精度浮点后加0.0001
        double dou = Convert.ToDouble(str) + 0.0001;  
        //将双精度浮点保留两位小数后返回
        return  Math.Round(dou, 3);
    }

/*=========================================================================================================================================*/

    /*
        根据登陆用户的工程全线控制加载列表的数据
        入参: 列表请求, 列表响应, 是否对合同做控制
        监理:对所在工程下的所有数据可见,如果工程为空,则所有数据都不可见
        安装单位:对所在工程下的所有数据可见,如果工程为空,则所有数据都不可见
        项目部:对所在工程下的所有数据可见,如果工程为空,则所有工程都可见
        厂家:对所在工程和合同下的数据可见
        by: lins, date: 2020-08-20
     */
    public static void defaultInit(H3.SmartForm.ListViewRequest request, H3.SmartForm.LoadListViewResponse response, bool engineeringContractFlag) {

        //jinx 2020-07-15 
        //根据曹总提出的需求,将添加合同文档权限
        string userId = request.UserContext.UserId;   //获取当前用户id
        H3.Data.Filter.Filter filter = new H3.Data.Filter.Filter(); //构建过滤器
        H3.Data.Filter.And andMatcher = new H3.Data.Filter.And(); //构造and匹配器

        string sql = "SELECT * FROM  I_D002033personnelManagement WHERE personnel='" + userId + "' AND static ='有效' ";    //personnel   personnelID  D002033personnelManagement 用户信息
        System.Data.DataTable table = request.Engine.Query.QueryTable(sql, null);
        if(table != null && table.Rows.Count > 0) {
            //获取当前人员是否含有标段(合同)
            //start  关联多选存储位置为 I_表单编码_关联多选控件编码 
            string sqlCT = "SELECT * FROM I_D002033personnelManagement_joinEngineeringContract WHERE objectid = '" + table.Rows[0]["objectId"] + "' ";
            System.Data.DataTable tableCT = request.Engine.Query.QueryTable(sqlCT, null);
            //end

            string personnelstatic = table.Rows[0]["personnelstatic"] + string.Empty; //人员状态
            sql = "SELECT * FROM I_D002033engineeringPermissions WHERE joinPersonnelManagement ='" + table.Rows[0]["objectId"] + "' AND static ='有效' ";
            System.Data.DataTable table1 = request.Engine.Query.QueryTable(sql, null);
            if(table1 != null && table1.Rows.Count > 0) {
                for(int i = 0;i < table1.Rows.Count; i++) {
                    if(Convert.ToString(table1.Rows[i]["role"]) != "超级管理员") {
                        string joinProjectEngineering = table1.Rows[i]["joinProjectEngineering"] + string.Empty;
                        sql = "SELECT objectId FROM I_D002033engineeringContrac WHERE joinProjectEngineering = '" + joinProjectEngineering + "' AND static = '有效' LIMIT 0, 1 ";  // 识别工程是否有效(工程是否有合同)
                        System.Data.DataTable table2 = request.Engine.Query.QueryTable(sql, null);
                        //工程是有效工程
                        if(table2 != null && table2.Rows.Count > 0) {
                            //jinx 20200529 
                            //添加合同过滤
                            string joinUnitType = table.Rows[0]["joinUnitType"] + string.Empty; //单位类型
                            switch(joinUnitType) {
                                case "a0afdc46-ec0f-4668-998e-e77565562a94":  //建设单位 要求甲方人员必须是员工表中的人员
                                    if(table.Rows[0]["joinEmployee"] != null && table.Rows[0]["joinEmployee"] + string.Empty != "") {
                                        string sql4 = "SELECT objectid FROM I_D002033employee WHERE objectid = '" + table.Rows[0]["joinEmployee"] + string.Empty + "' AND employee = '" + table.Rows[0]["personnelID"] + string.Empty + "' ";
                                        System.Data.DataTable table4 = request.Engine.Query.QueryTable(sql4, null);
                                        if(table4 != null && table4.Rows.Count > 0) {
                                            //建设单位员工只能看到当前所属工程下的数据
                                            andMatcher.Add(new H3.Data.Filter.ItemMatcher("joinProjectEngineering", H3.Data.ComparisonOperatorType.Equal, joinProjectEngineering));  //添加工程筛选条件
                                        }
                                        //员工表中没有当前用户
                                        else {
                                            andMatcher.Add(new H3.Data.Filter.ItemMatcher("ObjectId", H3.Data.ComparisonOperatorType.Equal, ""));  //添加筛选条件
                                        }
                                    } 
                                    //甲方员工字段为空
                                    else {
                                        andMatcher.Add(new H3.Data.Filter.ItemMatcher("ObjectId", H3.Data.ComparisonOperatorType.Equal, ""));  //添加筛选条件
                                    }
                                    break;
                                case "983c4806-0983-4484-bf6a-080edcc662b6": //监理
                                    if(!string.IsNullOrEmpty(joinProjectEngineering)){
                                        andMatcher.Add(new H3.Data.Filter.ItemMatcher("joinProjectEngineering", H3.Data.ComparisonOperatorType.Equal, joinProjectEngineering));  //添加工程筛选条件
                                    }
                                    break;
                                default:
                                    andMatcher.Add(new H3.Data.Filter.ItemMatcher("joinProjectEngineering", H3.Data.ComparisonOperatorType.Equal, joinProjectEngineering));  //添加工程筛选条件
                                    //施工能看的范围:所属工程 + 未挂合同(合同控件为空) ;所属工程 + 挂所在单位的合同(合同控件不为空, 且所挂合同包含了本单位签订的合同) ,下方代码据此修改
                                    //2020-08-13 jinx 修改施工权限
                                    if(personnelstatic != null && personnelstatic != "" && personnelstatic != "离开状态") {
                                        if(tableCT != null && tableCT.Rows.Count > 0) {
                                            List < string > tabList = new List<string>();
                                            for(int j = 0;j < tableCT.Rows.Count; j++) {
                                                //如果当前登录人所在标段中有合同是机电安装合同且合同状态为执行中或初始的有效合同则不对当前登录人做合同限制并隐藏价格
                                                string propertyvalue = tableCT.Rows[j]["propertyvalue"] + string.Empty;
                                                string sql3 = "SELECT * FROM I_D002033engineeringContrac WHERE objectid = '" + propertyvalue + "' ";
                                                sql3 += " AND joinProjectEngineering ='" + joinProjectEngineering + "' AND serviceContractType = 'd71e631a-a5d0-4010-9a77-ca7f479105f1' ";
                                                sql3 += " AND static = '有效' AND (joinContractstatic = '2b20a013-0d20-4d9b-b18c-ea147f68cb59' OR joinContractstatic = '2a20bc9f-d0b3-4854-85fa-019939c94028') "; 
                                                if(request.Engine.Query.QueryTable(sql3, null).Rows.Count > 0){
                                                    engineeringContractFlag = false;
                                                    //如果存在价格字段则隐藏
                                                    if(response.Columns.ContainsKey("price")) response.Columns.Remove("price"); //价格
                                                }
                                                tabList.Add(propertyvalue);//将用户信息表中的标段添加进过滤集合中
                                            }
                                            //如果对合同做控制 使用or连接挂接当前单位合同与未挂接合同的过滤条件
                                            if(engineeringContractFlag) {
                                                H3.Data.Filter.Or orMatcher = new H3.Data.Filter.Or();
                                                orMatcher.Add(new H3.Data.Filter.ItemMatcher("joinEngineeringContract", H3.Data.ComparisonOperatorType.Equal, null));  //将合同为空添加进过滤集合中
                                                orMatcher.Add(new H3.Data.Filter.ItemMatcher("joinEngineeringContract", H3.Data.ComparisonOperatorType.In, tabList.ToArray()));  //将合同表中该单位的合同添加进过滤集合中
                                                andMatcher.Add(orMatcher);
                                            }
                                        } 
                                        else {
                                            List < string > tabList = new List<string>();
                                            string sql2 = "SELECT objectid FROM I_D002033engineeringContrac WHERE vendor = '" + table.Rows[0]["joinCompanyUnit"] + string.Empty + "' ";   //propertyvalue 为关联表单多选 ID,在此为合同ID
                                            System.Data.DataTable table5 = request.Engine.Query.QueryTable(sql2, null);
                                            if(table5 != null && table5.Rows.Count > 0) {
                                                for(int j = 0;j < table5.Rows.Count; j++) {
                                                    tabList.Add(table5.Rows[j]["objectid"] + string.Empty);//将合同表中该单位的合同添加进过滤集合中
                                                }
                                            }
                                            //如果对合同做控制 使用or连接挂接当前单位合同与未挂接合同的过滤条件
                                            if(engineeringContractFlag) {
                                                H3.Data.Filter.Or orMatcher = new H3.Data.Filter.Or();
                                                orMatcher.Add(new H3.Data.Filter.ItemMatcher("joinEngineeringContract", H3.Data.ComparisonOperatorType.Equal, null));  //将合同为空添加进过滤集合中
                                                orMatcher.Add(new H3.Data.Filter.ItemMatcher("joinEngineeringContract", H3.Data.ComparisonOperatorType.In, tabList.ToArray()));  //将合同表中该单位的合同添加进过滤集合中
                                                andMatcher.Add(orMatcher);
                                            }
                                        }
                                    }
                                    else {
                                        andMatcher.Add(new H3.Data.Filter.ItemMatcher("ObjectId", H3.Data.ComparisonOperatorType.Equal, ""));  //添加筛选条件
                                    }
                                    break;
                            }
                        }
                        else { //未挂工程
                            //2020-08-17 jinx 无工程业主不进行工程限制
                            string joinUnitType = table.Rows[0]["joinUnitType"] + string.Empty; //单位类型
                            //如果为业主单位、监理单位人员(用户信息表的单位类型为业主单位),则可以访问
                            if(joinUnitType != "a0afdc46-ec0f-4668-998e-e77565562a94" && joinUnitType != "983c4806-0983-4484-bf6a-080edcc662b6") { 
                                andMatcher.Add(new H3.Data.Filter.ItemMatcher("joinProjectEngineering", H3.Data.ComparisonOperatorType.Equal, ""));  //添加筛选条件
                            }
                        }
                    }
                }
            }
            else {
                //2020-08-17 jinx 无工程业主不进行工程限制
                string joinUnitType = table.Rows[0]["joinUnitType"] + string.Empty; //单位类型
                //如果为业主单位、监理单位人员(用户信息表的单位类型为业主单位),则可以访问
                if(joinUnitType != "a0afdc46-ec0f-4668-998e-e77565562a94" && joinUnitType != "983c4806-0983-4484-bf6a-080edcc662b6") { 
                    andMatcher.Add(new H3.Data.Filter.ItemMatcher("joinProjectEngineering", H3.Data.ComparisonOperatorType.Equal, ""));  //添加筛选条件
                }
            };
        }
        //人员信息表中没有当前用户
        else {
            andMatcher.Add(new H3.Data.Filter.ItemMatcher("joinProjectEngineering", H3.Data.ComparisonOperatorType.Equal, ""));  //添加筛选条件
        }
        filter.Matcher = andMatcher;
        request.Filter = filter;
    }

/*=========================================================================================================================================*/

    /*
        如果登录人不是超级管理员则将thisId隐藏
        by: lins, date: 2020-09-07
     */
    public static void hiddenThisId(H3.SmartForm.ListViewRequest request, H3.SmartForm.LoadListViewResponse response){
        string userId = request.UserContext.UserId;   //获取当前用户id
        string sql = "SELECT * FROM  I_D002033personnelManagement WHERE personnel='" + userId + "' AND static ='有效' ";    //personnel   personnelID  D002033personnelManagement 用户信息
        System.Data.DataTable table = request.Engine.Query.QueryTable(sql, null);
        if(table.Rows.Count > 0 && table != null) {
            string objectId = table.Rows[0]["objectId"] + string.Empty;
            sql = "SELECT * FROM I_D002033engineeringPermissions WHERE joinPersonnelManagement ='" + objectId + "' AND static ='有效' ";
            System.Data.DataTable table1 = request.Engine.Query.QueryTable(sql, null);
            if(table1 != null && table1.Rows.Count > 0) {
                for(int i = 0;i < table1.Rows.Count; i++) {
                    if(Convert.ToString(table1.Rows[i]["role"]) != "超级管理员") {
                        if(response.Columns.ContainsKey("thisID")) response.Columns.Remove("thisID"); //thisID
                    }
                }
            }
        }
    }

/*=========================================================================================================================================*/

    /*
        修改数据标题
     */
    public static H3.SmartForm.LoadListViewResponse changeTitle(H3.SmartForm.LoadListViewResponse  response, string titleCode , string titleValue) {
        Dictionary < string, H3.SmartForm.ListViewColumn > columns=new Dictionary<string, H3.SmartForm.ListViewColumn>();
        foreach(string key in response.Columns.Keys) {
            if(key == titleCode) {
                //将Name列的列名称改成 合同编码
                H3.SmartForm.ListViewColumn newCol = new H3.SmartForm.ListViewColumn(
                    titleCode,//列编码(对应控件编码)
                    titleValue,//列名称
                    response.Columns[key].Visible,
                    response.Columns[key].Sortable,
                    response.Columns[key].Url,
                    response.Columns[key].Align,
                    response.Columns[key].IsLabel,
                    response.Columns[key].ShowMode
                );
                columns.Add(titleCode, newCol);
            }
            else {
                columns.Add(key, response.Columns[key]);
            }
        }
        response.Columns = columns;
        return response;
    }

/*=========================================================================================================================================*/

    /*
        通过关联表单获取人员单选
        或通过人员单选获取关联表单
        双向使用 
     */
    public static string getPersonnelByRelation(string relation, H3.IEngine engine){
        string sql = " SELECT objectId FROM I_D002033personnelManagement WHERE personnel = '"+relation+"' AND static = '有效' ";
        System.Data.DataTable dt = engine.Query.QueryTable(sql, null);
        string param = "";
        if(dt != null && dt.Rows.Count > 0){
            param = dt.Rows[0]["objectId"] + string.Empty;
        }
        else{
            sql = " SELECT personnel FROM I_D002033personnelManagement WHERE objectId = '"+relation+"' AND static = '有效' ";
            dt = engine.Query.QueryTable(sql, null);
            if(dt != null && dt.Rows.Count > 0){
                param = dt.Rows[0]["personnel"] + string.Empty;
            }
        }
        return param;
    }

/*=========================================================================================================================================*/

    /*
        通过部套登记表
        返回当前有设备供应合同关系的供货厂商id集
        以逗号分割
        入参: 工程, 引擎, 出参: 供货厂商id集 
     */
    public static string getManufacturerCollation(string joinProjectEngineering, IEngine engine){
        string sql = " SELECT manufacturer FROM I_D002033deviceDelivery "; 
        string result = "";
        if(!(string.IsNullOrEmpty(joinProjectEngineering))) {
            sql += " WHERE joinProjectEngineering = '"+joinProjectEngineering+"' ";
        }
        sql += " GROUP BY manufacturer ";
        System.Data.DataTable dt = engine.Query.QueryTable(sql, null);
        int count = dt.Rows.Count;
        if(dt != null && count > 0){
            for(int i=0; i<count; i++) {
                result += dt.Rows[i]["manufacturer"] + ",";
            }
        }
        return result;
    }

/*=========================================================================================================================================*/

    /*
        通过部套登记表
        返回当前有设备供应合同关系的机组号id集
        以逗号分割
        入参: 工程, 部套号, 引擎, 出参: 供货厂商id集 
     */
    public static string getJoinGeneratorUnitString(string joinProjectEngineering, string joinVendorDeviceCode, IEngine engine){
            string sql = " SELECT joinGeneratorUnit FROM I_D002033deviceDelivery "; 
            sql += " WHERE 1=1 "; 
            if(!string.IsNullOrEmpty(joinProjectEngineering)){
                sql += " AND joinProjectEngineering = '"+joinProjectEngineering+"' ";                
            }
            if(!string.IsNullOrEmpty(joinVendorDeviceCode)){
                sql += " AND joinVendorDeviceCode = '"+joinVendorDeviceCode+"' ";
            }
            sql += " GROUP BY joinGeneratorUnit ";
            System.Data.DataTable dt = engine.Query.QueryTable(sql, null);
            string result = "";
            int count = dt.Rows.Count;
            if(dt != null && count > 0){
                for(int i=0; i<count; i++) {
                    result += dt.Rows[i]["joinGeneratorUnit"] + ",";
                }
            }
            return result;
    }

/*=========================================================================================================================================*/

    /*
        根据合同和工程返回查询条件, 用and链接
        by: lins, date: 2020-12-10
     */
    public static string getProAndCon(string joinProjectEngineering, string joinEngineeringContract){
        bool proFlag = !(string.IsNullOrEmpty(joinProjectEngineering));
        bool conFlag = !(string.IsNullOrEmpty(joinEngineeringContract));
        if(proFlag && conFlag) return " AND joinProjectEngineering = '"+joinProjectEngineering+"' AND joinEngineeringContract = '"+joinEngineeringContract+"' ";
        if(!proFlag && conFlag) return " AND joinEngineeringContract = '"+joinEngineeringContract+"' ";
        if(proFlag && !conFlag) return " AND joinProjectEngineering = '"+joinProjectEngineering+"' ";
        return "";        
    }

/*=========================================================================================================================================*/

    /*
        获取交货状态
        通过状态代码获取id
        双向使用
        by: lins, date: 2020-12-10
    */
    public static string getDevicestaticId(string param, H3.IEngine engine){
        string sql = " SELECT objectId FROM I_D002033devicestatic WHERE static = 1 AND staticCode = '"+param+"' ";
        System.Data.DataTable dt = engine.Query.QueryTable(sql, null);
        if(dt != null && dt.Rows.Count > 0) return dt.Rows[0]["objectId"] + string.Empty;
        sql = " SELECT staticCode FROM I_D002033devicestatic WHERE static = 1 AND objectId = '"+param+"' ";
        dt = engine.Query.QueryTable(sql, null);
        if(dt != null && dt.Rows.Count > 0) return dt.Rows[0]["staticCode"] + string.Empty;
        return "";
    }

/*=========================================================================================================================================*/

    /*
        获取交货状态
        通过id获取状态代码
        双向使用
        by: lins, date: 2020-12-10
    */
    public static string getDevicestaticCode(string param, H3.IEngine engine){
        string sql = " SELECT staticCode FROM I_D002033devicestatic WHERE static = 1 AND objectId = '"+param+"' ";
        System.Data.DataTable dt = engine.Query.QueryTable(sql, null);
        if(dt != null && dt.Rows.Count > 0) return dt.Rows[0]["staticCode"] + string.Empty;
        return "";
    }
    
/*=========================================================================================================================================*/

    /* 
        获取最大值编码
        入参: 数据库返回集, 依据,  出参: 最大值 
        by: lins date: 2021-03-16 
    */
    public static int getMaxCode(System.Data.DataTable dt, string paramName) {
        //最大值初始值
        int max = 0;
        if(dt != null && dt.Rows.Count > 0)
        {
            for(int i = 0; i < dt.Rows.Count; i++) {
                string sourceCode = dt.Rows[i][paramName] + string.Empty;
                if(!(string.IsNullOrEmpty(sourceCode))) {
                    //如果字符串中存在'.'则执行
                    if(sourceCode.IndexOf('.') > 0) {
                        //获取编码中'.'后面的数据
                        int start = sourceCode.LastIndexOf('.') + 1; //开始下标 +1因为获取的是'.'的位置 需要+1获取'.'后面的字符
                        int len = sourceCode.Length - start; //字符长度-开始下标
                        string str = sourceCode.Substring(start, len);
                        //转换为int并和max比较, 如果大于max则赋值
                        int param = Int32.Parse(str);//Convert.ToInt32(str);
                        
                        //如果新值比最大值大则使用新值
                        if(max < param) {
                            max = param;
                        }
                    }
                    else {
                        int param = Int32.Parse(sourceCode);//Convert.ToInt32(sourceCode);
                        if(max < param) {
                            max = param;
                        }
                    }
                }
            }
        }
        max += 1;
        return max;
    }
    
    /*=========================================================================================================================================*/

    /* 
        隐藏控件
        仅隐藏空值控件
        by:lins, date: 2021-03-31
    */
    public static H3.SmartForm.LoadSmartFormResponse addHider(H3.SmartForm.SmartFormRequest request, H3.SmartForm.LoadSmartFormResponse response, List < string > controlCodes) {
        H3.DataModel.BizObject masterBo = H3.DataModel.BizObject.Load(request.UserContext.UserId, request.Engine, request.SchemaCode, request.BizObjectId, false);
        foreach(string controlCode in controlCodes) {
            //判断不为创建模式
            if(!(request.FormMode.ToString() == "Create")) {
                //子表
                if(controlCode.IndexOf("D002033") > -1) {
                    H3.DataModel.BizObject[] childBoList = (H3.DataModel.BizObject[]) masterBo[controlCode];
                    //子表内不存在数据
                    if(childBoList != null && childBoList.Length > 0) { }
                    else {
                        //获取子表结构
                        Dictionary < string, object > taskObj =(Dictionary<string, object>) response.ReturnData[controlCode].Value;
                        //获取子表列结构
                        Dictionary < string, H3.SmartForm.SmartFormResponseDataItem > taskobject = (Dictionary<string, H3.SmartForm.SmartFormResponseDataItem>) taskObj["T"];
                        foreach(string key in taskobject.Keys) {
                            taskobject[key].Visible = false; //设置子表列隐藏
                        }
                    }
                }
                //非子表
                else {
                    //判断控件内是否为空 //文本、下拉框、日期
                    if(string.IsNullOrEmpty(masterBo[controlCode] + string.Empty)) {
                        response.ReturnData[controlCode].Visible = false; //设置字段不可见
                    }
                    else if(masterBo[controlCode] is string) { }
                    else if(masterBo[controlCode] is double) { }
                    else if(masterBo[controlCode] is DateTime) { }
                    //判断控件内是否为空 //关联表单多选
                    else if(((string[]) masterBo[controlCode]).Length < 1) {
                        response.ReturnData[controlCode].Visible = false; //设置字段不可见
                    }
                }
            }
            //判断当前是否为编辑状态
            if(request.FormMode.ToString() == "Edit") {
                response.ReturnData[controlCode].Visible = true; //设置字段可见
            }
        }
        return response;
    }
}

 

posted on 2022-04-18 11:27  天涯何  阅读(98)  评论(0编辑  收藏  举报