using System;
using System.Linq;
using System.Web.UI.WebControls;
using BLL;
using NPOI.Util;
using System.Collections.Generic;
using System.Data;
using FineUIPro.Web.DataShow;
using System.Data.SqlClient;
using System.Threading;
namespace FineUIPro.Web.SysManage
{
    public partial class UnitCleanupMerge : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.btnClose.OnClientClick = ActiveWindow.GetHideReference();
                ////权限按钮方法
                this.GetButtonPower();
                BindGrid();
                BindGrid2();
            }
        }
        #region 加载合并后的单位
        /// 
        /// 加载合并后的单位
        /// 
        private void BindGrid()
        {
            var list = (from x in Funs.DB.Base_Unit
                        join y in Funs.DB.Base_UnitType on x.UnitTypeId equals y.UnitTypeId into yGroup
                        from y in yGroup.DefaultIfEmpty()
                        orderby x.UnitName descending
                        select new
                        {
                            x.UnitId,
                            x.UnitCode,
                            x.UnitName,
                            x.ShortUnitName,
                            y.UnitTypeName
                        }).ToList();
            string codeName = ttbUnitNameCodeSearch.Text.Trim();
            if (!string.IsNullOrWhiteSpace(codeName))
            {
                //list = list.Where(x => !string.IsNullOrWhiteSpace(x.UnitCode) && !string.IsNullOrWhiteSpace(x.UnitName)).ToList();
                list = list.Where(x => (!string.IsNullOrWhiteSpace(x.UnitCode) && x.UnitCode.Contains(codeName)) || (!string.IsNullOrWhiteSpace(x.UnitName) && x.UnitName.Contains(codeName)) || (!string.IsNullOrWhiteSpace(x.ShortUnitName) && x.ShortUnitName.Contains(codeName))).ToList();
            }
            // 1.设置总项数(特别注意:数据库分页一定要设置总记录数RecordCount)
            Grid1.RecordCount = list.Count();
            // 2.获取当前分页数据
            DataTable table = Funs.LINQToDataTable(list);
            // 3.绑定到Grid
            //Grid1.DataSource = table;
            Grid1.DataSource = this.GetPagedDataTable(Grid1, table);
            Grid1.DataBind();
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid();
        }
        protected void ttbUnitNameCodeSearch_Trigger1Click(object sender, EventArgs e)
        {
            ttbUnitNameCodeSearch.Text = string.Empty;
            ttbUnitNameCodeSearch.ShowTrigger1 = false;
            BindGrid();
        }
        protected void ttbUnitNameCodeSearch_Trigger2Click(object sender, EventArgs e)
        {
            ttbUnitNameCodeSearch.ShowTrigger1 = true;
            BindGrid();
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 加载需要合并的单位
        /// 
        /// 加载需要合并的单位
        /// 
        private void BindGrid2()
        {
            var list = (from x in Funs.DB.Base_Unit
                        join y in Funs.DB.Base_UnitType on x.UnitTypeId equals y.UnitTypeId into yGroup
                        from y in yGroup.DefaultIfEmpty()
                        where x.UnitId != Const.UnitId_CWCEC && x.UnitId != Const.UnitId_Con
                        orderby x.UnitName descending
                        select new
                        {
                            x.UnitId,
                            x.UnitCode,
                            x.UnitName,
                            x.ShortUnitName,
                            y.UnitTypeName
                        }).ToList();
            //string unitId = this.drpUnitId.SelectedValue;
            string unitId = this.drpUnitBox.Value;
            if (!string.IsNullOrWhiteSpace(unitId))
            {
                list = list.Where(x => x.UnitId != unitId).ToList();
            }
            string codeName = ttbMergeUnitNameCodeSearch.Text.Trim();
            if (!string.IsNullOrWhiteSpace(codeName))
            {
                //list = list.Where(x => !string.IsNullOrWhiteSpace(x.UnitCode) && !string.IsNullOrWhiteSpace(x.UnitName)).ToList();
                list = list.Where(x => (!string.IsNullOrWhiteSpace(x.UnitCode) && x.UnitCode.Contains(codeName)) || (!string.IsNullOrWhiteSpace(x.UnitName) && x.UnitName.Contains(codeName)) || (!string.IsNullOrWhiteSpace(x.ShortUnitName) && x.ShortUnitName.Contains(codeName))).ToList();
            }
            // 1.设置总项数(特别注意:数据库分页一定要设置总记录数RecordCount)
            Grid2.RecordCount = list.Count();
            // 2.获取当前分页数据
            DataTable table = Funs.LINQToDataTable(list);
            // 3.绑定到Grid
            //Grid2.DataSource = table;
            Grid2.DataSource = this.GetPagedDataTable(Grid2, table);
            Grid2.DataBind();
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid2();
        }
        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid2();
        }
        protected void ttbMergeUnitNameCodeSearch_Trigger1Click(object sender, EventArgs e)
        {
            ttbMergeUnitNameCodeSearch.Text = string.Empty;
            ttbMergeUnitNameCodeSearch.ShowTrigger1 = false;
            BindGrid2();
        }
        protected void ttbMergeUnitNameCodeSearch_Trigger2Click(object sender, EventArgs e)
        {
            ttbMergeUnitNameCodeSearch.ShowTrigger1 = true;
            BindGrid2();
        }
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void MergeTextBox_TextChanged(object sender, EventArgs e)
        {
            BindGrid2();
        }
        #endregion
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string unitId = string.Empty;
            string unitMergeId = string.Empty;
            string unitName = string.Empty;
            string unitMergeName = string.Empty;
            if (!string.IsNullOrWhiteSpace(this.drpUnitBox.Text))
            {
                unitId = this.drpUnitBox.Value.Trim();
                unitName = this.drpUnitBox.Text;
            }
            else
            {
                Alert.ShowInParent("请选择合并后单位!", MessageBoxIcon.Warning);
                return;
            }
            if (!string.IsNullOrWhiteSpace(this.drpMergeUnitBox.Text))
            {
                unitMergeId = this.drpMergeUnitBox.Value.Trim();
                unitMergeName = this.drpMergeUnitBox.Text;
                if (unitMergeId == unitId)
                {
                    Alert.ShowInParent("两个单位为同一个单位,无需合并!", MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                Alert.ShowInParent("请选择需要合并的单位!", MessageBoxIcon.Warning);
                return;
            }
            List unitMergeIds = unitMergeId.Split(',').ToList();
            unitMergeIds = unitMergeIds.Where(x => x != unitId).ToList();
            //db.DataIdMove.DeleteAllOnSubmit();
            Model.SGGLDB db = Funs.DB;
            var clist = db.DataIdMove.Where(x => x.ColumType == "Unit" && x.NewIds == unitId).ToList();
            db.DataIdMove.DeleteAllOnSubmit(clist);
            db.SubmitChanges();
            List list = new List();
            foreach (var mergeId in unitMergeIds)
            {
                list.Add(new Model.DataIdMove { OldId = mergeId.Trim(), NewIds = unitId.Trim(), ColumType = "Unit" });
            }
            db.DataIdMove.InsertAllOnSubmit(list);
            db.SubmitChanges();
            string strSql = $"exec SP_DataIdMove 'Unit','{unitId}'";
            BLL.SQLHelper.ExecutSql(strSql);
            //SqlParameter[] parameters = {
            //    new SqlParameter("@colums", "Unit"),
            //    new SqlParameter("@returnVal", SqlDbType.Int)
            //};
            //BLL.SQLHelper.ExecuteNonQueryStoredProcedure("SP_DataIdMove", parameters);
            //int succ = BLL.SQLHelper.ExecuteProcedure("SP_DataIdMove", parameters);
            //Thread.Sleep(30000); // 等待30秒,30000毫秒等于30秒
            string txtRemark = this.txtRemark.Text.Trim();
            //其他数据表单位数据合并后,删除单位表冗余单位
            foreach (var mergeId in unitMergeIds)
            {
                string uId = mergeId.Trim();
                var unit = BLL.UnitService.GetUnitByUnitId(uId);
                if (unit != null)
                {
                    UnitService.DeleteUnitById(uId);
                    string op = $"单位合并清理后,{Const.BtnDelete};备注:{txtRemark}";
                    LogService.AddSys_Log(this.CurrUser, unit.UnitCode, unit.UnitId, Const.UnitMenuId, op);
                }
            }
            db.DataIdMove.DeleteAllOnSubmit(list);
            db.SubmitChanges();
            PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
        }
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (this.CurrUser.UserId == Const.sysglyId || this.CurrUser.UserId == Const.hfnbdId || this.CurrUser.UserId == Const.fuweiId || this.CurrUser.UserId == Const.shenyinhangId)
            {//系统管理员、合肥诺必达、付伟、申银行
                this.btnSave.Hidden = false;
            }
        }
        #endregion        
    }
}