using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using SysCore;
using SysCore.Control;

public class DepartmentDAL
{
    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="m">实体</param>
    public void Add(Department m)
    {
        string sql = @"insert Base_Department(dep_code,dep_name,parent_id,is_workshop,dep_wh_id,is_stop,
                        sdefine1,sdefine2,sdefine3,sdefine4,sdefine5,
                        ndefine1,ndefine2,ndefine3,ndefine4,ndefine5)
                        select @dep_code,@dep_name,@parent_id,@is_workshop,@dep_wh_id,@is_stop,
                        @sdefine1,@sdefine2,@sdefine3,@sdefine4,@sdefine5,
                        @ndefine1,@ndefine2,@ndefine3,@ndefine4,@ndefine5";
        SqlParameter[] par = {
            new SqlParameter("@dep_code",m.dep_code),
            new SqlParameter("@dep_name",m.dep_name),
            new SqlParameter("@parent_id",m.parent_id),
            new SqlParameter("@is_workshop",m.is_workshop),
            new SqlParameter("@dep_wh_id",XTools.IntToDBNull(m.dep_wh_id)),
            new SqlParameter("@is_stop",m.is_stop),
            new SqlParameter("@sdefine1",XTools.StringToDBNull(m.sdefine1)),
            new SqlParameter("@sdefine2",XTools.StringToDBNull(m.sdefine2)),
            new SqlParameter("@sdefine3",XTools.StringToDBNull(m.sdefine3)),
            new SqlParameter("@sdefine4",XTools.StringToDBNull(m.sdefine4)),
            new SqlParameter("@sdefine5",XTools.StringToDBNull(m.sdefine5)),
            new SqlParameter("@ndefine1",XTools.DecimalToDBNull(m.ndefine1)),
            new SqlParameter("@ndefine2",XTools.DecimalToDBNull(m.ndefine2)),
            new SqlParameter("@ndefine3",XTools.DecimalToDBNull(m.ndefine3)),
            new SqlParameter("@ndefine4",XTools.DecimalToDBNull(m.ndefine4)),
            new SqlParameter("@ndefine5",XTools.DecimalToDBNull(m.ndefine5))
        };
        new SqlUtil().ExecuteNonQuery(sql, par);
    }
    /// <summary>
    /// 得到实体
    /// </summary>
    /// <param name="主键id">dep_id</param>
    /// <returns>Department</returns>
    public Department Get(int dep_id)
    {
        Department m = new Department();
        string sql = @"select *
                      from Base_Department where dep_id=@dep_id";
        SqlParameter[] par = {
                new SqlParameter("@dep_id",dep_id)
            };
        SqlUtil su = new SqlUtil();
        using (DataSet dt = su.GetDataSet(sql, par))
        {
            foreach (DataRow r in dt.Tables[0].Rows)
            {
                m.dep_id = Convert.ToInt32(r["dep_id"]);
                m.dep_code = r["dep_code"].ToString();
                m.dep_name = r["dep_name"].ToString();
                m.parent_id = XTools.DBNullToInt(r["parent_id"]);
                if (r["parent_id"] != DBNull.Value)
                {
                    m.parent = Get(Convert.ToInt32(r["parent_id"]));
                }
                m.dep_wh_id = XTools.DBNullToInt(r["dep_wh_id"]);
                if (r["dep_wh_id"] != DBNull.Value)
                {
                    m.warehouse = new WarehouseDAL().Get(Convert.ToInt32(r["dep_wh_id"]));
                }
                m.is_workshop = XTools.DBNullToInt(r["is_workshop"]);
                m.is_stop = XTools.DBNullToInt(r["is_stop"]);
                m.sdefine1 = r["sdefine1"].ToString();
                m.sdefine2 = r["sdefine2"].ToString();
                m.sdefine3 = r["sdefine3"].ToString();
                m.sdefine4 = r["sdefine4"].ToString();
                m.sdefine5 = r["sdefine5"].ToString();
                m.ndefine1 = XTools.DBNullToDecimal(r["ndefine1"]);
                m.ndefine2 = XTools.DBNullToDecimal(r["ndefine2"]);
                m.ndefine3 = XTools.DBNullToDecimal(r["ndefine3"]);
                m.ndefine4 = XTools.DBNullToDecimal(r["ndefine4"]);
                m.ndefine5 = XTools.DBNullToDecimal(r["ndefine5"]);
            }
        }
        return m;
    }
    /// <summary>
    /// 通过编码得到ID
    /// </summary>
    /// <param name="编码">vc_code</param>
    /// <returns>int</returns>
    public int GetIdByCode(string dep_code)
    {
        string sql = @"select dep_id
                      from Base_Department where dep_code=@dep_code";
        SqlParameter[] par = {
                new SqlParameter("@dep_code",dep_code)
            };
        return Convert.ToInt32(new SqlUtil().ExecuteScalar(sql, par));
    }
    /// <summary>
    /// 通过ID得到编码
    /// </summary>
    /// <param name="ID">dep_id</param>
    /// <returns>int</returns>
    public string GetCodeById(int dep_id)
    {
        string sql = @"select dep_code
                      from Base_Department where dep_id=@dep_id";
        SqlParameter[] par = {
                new SqlParameter("@dep_id",dep_id)
            };
        return new SqlUtil().ExecuteScalar(sql, par).ToString();
    }
    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="m">实体</param>
    public void Update(Department m)
    {
        string sql = @"update Base_Department set 
                        dep_code=@dep_code,
                        dep_name=@dep_name,
                        is_workshop=@is_workshop,
                        parent_id=@parent_id,
                        dep_wh_id=@dep_wh_id,
                        is_stop=@is_stop,
                        sdefine1=@sdefine1,
                        sdefine2=@sdefine2,
                        sdefine3=@sdefine3,
                        sdefine4=@sdefine4,
                        sdefine5=@sdefine5,
                        ndefine1=@ndefine1,
                        ndefine2=@ndefine2,
                        ndefine3=@ndefine3,
                        ndefine4=@ndefine4,
                        ndefine5=@ndefine5
                       where dep_id=@dep_id";
        SqlParameter[] par = {
                new SqlParameter("@dep_code",m.dep_code),
                new SqlParameter("@dep_name",m.dep_name),
                new SqlParameter("@is_workshop",m.is_workshop),
                new SqlParameter("@is_stop",m.is_stop),
                new SqlParameter("@parent_id",m.parent_id),
                new SqlParameter("@dep_wh_id",XTools.IntToDBNull(m.dep_wh_id)),
                new SqlParameter("@dep_id",m.dep_id),
                new SqlParameter("@sdefine1",XTools.StringToDBNull(m.sdefine1)),
                new SqlParameter("@sdefine2",XTools.StringToDBNull(m.sdefine2)),
                new SqlParameter("@sdefine3",XTools.StringToDBNull(m.sdefine3)),
                new SqlParameter("@sdefine4",XTools.StringToDBNull(m.sdefine4)),
                new SqlParameter("@sdefine5",XTools.StringToDBNull(m.sdefine5)),
                new SqlParameter("@ndefine1",XTools.DecimalToDBNull(m.ndefine1)),
                new SqlParameter("@ndefine2",XTools.DecimalToDBNull(m.ndefine2)),
                new SqlParameter("@ndefine3",XTools.DecimalToDBNull(m.ndefine3)),
                new SqlParameter("@ndefine4",XTools.DecimalToDBNull(m.ndefine4)),
                new SqlParameter("@ndefine5",XTools.DecimalToDBNull(m.ndefine5))
            };
        new SqlUtil().ExecuteNonQuery(sql, par);
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id">ID</param>
    public void Delete(int dep_id)
    {
        Department m = new Department();
        string sql = "delete Base_Department where dep_id in (@dep_id)";
        SqlParameter[] par = {
                new SqlParameter("@dep_id",dep_id)
            };
        new SqlUtil().ExecuteNonQuery(sql, par);
    }
    /// <summary>
    /// 得到所有部门
    /// </summary>
    /// <returns>DataTable</returns>
    public DataTable GetListAll(string where)
    {
        string sql = @"select * from Base_Department @where order by dep_code";
        sql = sql.Replace("@where", where);
        DataTable dt = new SqlUtil().GetDataTable(sql, null);
        return dt;
    }
    /// <summary>
    /// 快速下拉查询
    /// </summary>
    /// <returns>DataTable</returns>
    public DataTable GetList_FastSearch(string keyword)
    {
        string sql = @"select top 10 dep_id,dep_code,dep_name from Base_Department where isnull(is_stop,0)=0 and dep_id not in (select parent_id from base_department) and (dep_code like '%'+@keyword+'%' or dep_name like '%'+@keyword+'%') ";
        //当前用户是否管理员
        bool is_admin = new AuthUI().CheckLoginUserIsAdmin();
        if (!is_admin)
        {
            //值为1代表启用部门权限控制
            string system_dep_auth = new ConfigReader().GetConfig("system_dep_auth");
            if (system_dep_auth.Equals("1"))
            {
                //只有客户专管业务员或业务主管才有权限看到
                sql += " and dep_id in (" + new AuthEx().GetSqlForMyDepartment() + ")";
            }
        }
        sql += " order by dep_code";
        SqlParameter[] par ={
            new SqlParameter("@keyword",keyword)
        };
        DataTable dt = new SqlUtil().GetDataTable(sql, par);
        return dt;
    }
    //列表查询用的sql
    string sql_list = @"
                    select d.*,dp.dep_code as parent_code,dp.dep_name as parent_name,
                    case when isnull(d.is_workshop,0)=1 then '是' else '否' end as is_workshop_name,
                    wh.wh_name as dep_wh_name
                    from Base_Department d 
                    left join Base_Department dp on d.parent_id=dp.dep_id
                    left join Base_Warehouse wh on wh.wh_id=d.dep_wh_id";
    /// <summary>
    /// 得到列表
    /// </summary>
    /// <param name="sql_select_field">格式定义指定显示列</param>
    /// <returns>DataTable</returns>
    public DataTable GetList(Hashtable pg, string sql_select_field)
    {
        string order_field = pg["order_field"].ToString();
        string sql = @"select ROW_NUMBER() OVER(@order_field) AS row_num,@sql_select_field
                from(@sql_list)t
                where 1=1 ";
        sql = sql.Replace("@sql_list", sql_list)
                 .Replace("@order_field", order_field)
                 .Replace("@sql_select_field", sql_select_field);

        //分页处理与查询条件
        PageHelper ph = new PageHelper();
        sql = ph.GetPageSQL(sql, pg, true);//得到分页后的SQL
        DataTable dt = new SqlUtil().GetDataTable(sql, null);
        return dt;
    }
    /// <summary>
    /// 得到总记录数
    /// </summary>
    /// <returns>int</returns>
    public int GetList_TotalNumbers(Hashtable pg)
    {
        string sql = "select count(1) from (" + sql_list + ") t where 1=1 ";
        //分页处理与查询条件
        PageHelper ph = new PageHelper();
        sql = ph.GetPageSQL(sql, pg, false);//得到分页SQL
        int total_numbers = (int)new SqlUtil().ExecuteScalar(sql, null);
        return total_numbers;
    }
    /// <summary>
    /// 验证编码是否存在
    /// </summary>
    /// <param name="dep_code">编码</param>
    /// <returns>bool</returns>
    public bool CheckExist(string dep_code)
    {
        string sql = "select count(1) from Base_Department where dep_code=@dep_code";
        SqlParameter[] par ={
                new SqlParameter("@dep_code", dep_code)
            };
        int rows = Convert.ToInt32(new SqlUtil().ExecuteScalar(sql, par));
        if (rows > 0)
            return true;
        return false;
    }
    /// <summary>
    /// 验证是否有子类
    /// </summary>
    /// <param name="dep_id">主键id</param>
    /// <returns>bool</returns>
    public bool CheckHasChild(int dep_id)
    {
        string sql = "select count(1) from Base_Department where parent_id=@dep_id";
        SqlParameter[] par ={
                new SqlParameter("@dep_id", dep_id)
            };
        int rows = Convert.ToInt32(new SqlUtil().ExecuteScalar(sql, par));
        if (rows > 0)
            return true;
        return false;
    }
    /// <summary>
    /// 验证编码是否与父级部门一致
    /// </summary>
    /// <param name="dep_code">编码</param>
    /// <returns>bool</returns>
    public bool CheckLikeParent(string dep_code, string parent_code)
    {
        bool like = false;
        //父级部门编码与当前部门编码的前几位不一样，代表规则不一致
        if (dep_code.Length <= parent_code.Length) return false;
        if (dep_code.Substring(0, parent_code.Length).Equals(parent_code))
            like = true;
        //如果除父级部门编码外，还有规则与当前编码一样的且长度大于父级编码的,代表规则不对
        string sql = @"select count(1) from Base_Department 
                        where  @dep_code like dep_code+'%'
                        and dep_code not in (@parent_code,@dep_code)
                        and len(dep_code)>len(@parent_code)";
        SqlParameter[] par = {
                new SqlParameter("@dep_code",dep_code),
                new SqlParameter("@parent_code",parent_code)
            };
        int rows = Convert.ToInt32(new SqlUtil().ExecuteScalar(sql, par));
        if (rows > 0)
            like = false;
        return like;
    }
    /// <summary>
    /// 更新分类级次
    /// </summary>
    /// <param name="parent_id">当前ID</param>
    /// <param name="layer">当前级次</param>
    public void FetchNodeAndUpdateLayer(int parent_id, int layer)
    {
        DataTable dt = GetListAll("where isnull(parent_id,0)=" + parent_id);
        SqlUtil su = new SqlUtil();
        foreach (DataRow dr in dt.Rows)
        {
            int cur_id = Convert.ToInt32(dr["dep_id"]);
            string dep_name = dr["dep_name"].ToString();
            string sql = "update Base_Department set layer=" + layer + " where dep_id=" + cur_id;
            su.ExecuteNonQuery(sql, null);
            bool has_child = CheckHasChild(cur_id);
            if (has_child)
            {
                FetchNodeAndUpdateLayer(cur_id, layer + 1);
            }
        }
    }
}
