using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using BLL;
using Newtonsoft.Json;
using RestSharp;
using Model;

namespace FineUIPro.Web.SysManage
{
    public partial class SysConstSet : PageBase
    {
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //if (this.CurrUser.UserId == BLL.Const.sysglyId || this.CurrUser.UserId == BLL.Const.hfnbdId)
                //{
                //    this.btnArrowRefresh.Hidden = false;
                //}
                /// TAB1加载页面方法
                this.LoadTab1Data();
                ConstValue.InitConstValueDropDownList(this.drpSuperMenu, this.rblMenuType.SelectedValue, true);
                /// TAB2加载页面方法
                this.LoadTab2Data();
                /// TAB2加载页面方法
                this.LoadTab3Data();
                ///产值
                this.LoadTab4Data();
            }
        }
        #region 多附件转换
        #region 附件路径多附件转化
        /// <summary>
        /// 附件路径多附件转化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnArrowRefresh_Click(object sender, EventArgs e)
        {
            ///设备材料报验
            var InspectionEquipmentList = from x in Funs.DB.Comprehensive_InspectionEquipment select x;
            if (InspectionEquipmentList.Count() > 0)
            {
                foreach (var item in InspectionEquipmentList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.InspectionEquipmentId, item.AttachUrl, BLL.Const.InspectionEquipmentMenuId);
                    }
                }
            }
            ///人员报验
            var InspectionPersonList = from x in Funs.DB.Comprehensive_InspectionPerson select x;
            if (InspectionPersonList.Count() > 0)
            {
                foreach (var item in InspectionPersonList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.InspectionPersonId, item.AttachUrl, BLL.Const.InspectionPersonMenuId);
                    }
                }
            }
            ///机具报验
            var InspectionMachineList = from x in Funs.DB.Comprehensive_InspectionMachine select x;
            if (InspectionMachineList.Count() > 0)
            {
                foreach (var item in InspectionMachineList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.InspectionMachineId, item.AttachUrl, BLL.Const.InspectionMachineMenuId);
                    }
                }
            }
            ///设计变更单
            var DesignChangeOrderList = from x in Funs.DB.Comprehensive_DesignChangeOrder select x;
            if (DesignChangeOrderList.Count() > 0)
            {
                foreach (var item in DesignChangeOrderList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.DesignChangeOrderId, item.AttachUrl, BLL.Const.DesignChangeOrderMenuId);
                    }
                }
            }
            ///现场签证
            var SiteVisaManagementList = from x in Funs.DB.Comprehensive_SiteVisaManagement select x;
            if (SiteVisaManagementList.Count() > 0)
            {
                foreach (var item in SiteVisaManagementList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.VisaId, item.AttachUrl, BLL.Const.SiteVisaManagementMenuId);
                    }
                }
            }
            ///设计交底
            var DesignDetailsList = from x in Funs.DB.Comprehensive_DesignDetails select x;
            if (DesignDetailsList.Count() > 0)
            {
                foreach (var item in DesignDetailsList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.DesignDetailsId, item.AttachUrl, BLL.Const.DesignDetailsMenuId);
                    }
                }
            }
            ///施工组织设计及施工方案
            var GeneralPlanApprovalList = from x in Funs.DB.Comprehensive_GeneralPlanApproval select x;
            if (GeneralPlanApprovalList.Count() > 0)
            {
                foreach (var item in GeneralPlanApprovalList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.GeneralPlanApprovalId, item.AttachUrl, BLL.Const.GeneralPlanApprovalMenuId);
                    }
                }
            }
            ///超过一定规模的危大施工方案
            var MajorPlanApprovalList = from x in Funs.DB.Comprehensive_MajorPlanApproval select x;
            if (MajorPlanApprovalList.Count() > 0)
            {
                foreach (var item in MajorPlanApprovalList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.MajorPlanApprovalId, item.AttachUrl, BLL.Const.MajorPlanApprovalMenuId);
                    }
                }
            }
            ///NCR
            var NCRManagementList = from x in Funs.DB.Comprehensive_NCRManagement select x;
            if (NCRManagementList.Count() > 0)
            {
                foreach (var item in NCRManagementList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.NCRManagementId, item.AttachUrl, BLL.Const.NCRManagementMenuId);
                    }
                }
            }
            ///质量事故处理记录
            var QualityAccidentList = from x in Funs.DB.Comprehensive_QualityAccident select x;
            if (QualityAccidentList.Count() > 0)
            {
                foreach (var item in QualityAccidentList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.QualityAccidentId, item.AttachUrl, BLL.Const.QualityAccidentMenuId);
                    }
                }
            }
            ///资料接收登记
            var DataReceivingList = from x in Funs.DB.Comprehensive_DataReceiving select x;
            if (DataReceivingList.Count() > 0)
            {
                foreach (var item in DataReceivingList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.DataReceivingId, item.AttachUrl, BLL.Const.DataReceivingMenuId);
                    }
                }
            }
            ///资料发放登记
            var DataDistributionList = from x in Funs.DB.Comprehensive_DataDistribution select x;
            if (DataDistributionList.Count() > 0)
            {
                foreach (var item in DataDistributionList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.DataDistributionId, item.AttachUrl, BLL.Const.DataDistributionMenuId);
                    }
                }
            }
            ///共检通知单
            var InspectionManagementList = from x in Funs.DB.ProcessControl_InspectionManagement select x;
            if (InspectionManagementList.Count() > 0)
            {
                foreach (var item in InspectionManagementList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.InspectionId, item.AttachUrl, BLL.Const.InspectionNoticeMenuId);
                    }
                }
            }
            ///ITP清单
            var ITPListProjectList = from x in Funs.DB.CQMS_Foreign_ITPListProject select x;
            if (ITPListProjectList.Count() > 0)
            {
                foreach (var item in ITPListProjectList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.ITPListId, item.AttachUrl, BLL.Const.ITPListProjectMenuId);
                    }
                }
            }
            ///国外项目控制点检查检测
            var ControlPointCheckList = from x in Funs.DB.CQMS_Foreign_ControlPointCheck select x;
            if (ControlPointCheckList.Count() > 0)
            {
                foreach (var item in ControlPointCheckList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.ControlPointCheckId, item.AttachUrl, BLL.Const.ControlPointCheckMenuId);
                    }
                }
            }
            ///资料库
            var FileList = from x in Funs.DB.DataBase_File select x;
            if (FileList.Count() > 0)
            {
                foreach (var item in FileList)
                {
                    if (!string.IsNullOrEmpty(item.AttachUrl))
                    {
                        this.InsertAttachFile(item.FileId, item.AttachUrl, BLL.Const.DataBaseProjectMenuId);
                    }
                }
            }
            ShowNotify("转化成功!", MessageBoxIcon.Success);
        }
        #endregion
        #region 多附件转化方法
        /// <summary>
        /// 多附件转化方法
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="attachUrl"></param>
        private void InsertAttachFile(string ID, string attachUrl, string menuId)
        {
            var att = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == ID);
            if (att == null)
            {
                Model.AttachFile newAttachFile = new Model.AttachFile
                {
                    AttachFileId = SQLHelper.GetNewID(typeof(Model.AttachFile)),
                    ToKeyId = ID,
                    AttachSource = BLL.UploadFileService.GetSourceByAttachUrl(attachUrl, 100, string.Empty),
                    AttachUrl = attachUrl,
                    MenuId = menuId
                };
                Funs.DB.AttachFile.InsertOnSubmit(newAttachFile);
                Funs.DB.SubmitChanges();
            }
            else
            {
                if (string.IsNullOrEmpty(att.MenuId))
                {
                    att.MenuId = menuId;
                    Funs.DB.SubmitChanges();
                }
            }
        }
        #endregion 
        #endregion

        #region TAB1加载页面方法
        /// <summary>
        /// 加载页面方法
        /// </summary>
        private void LoadTab1Data()
        {
            //var sysSet = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_Synchronization).FirstOrDefault();
            //if (sysSet != null)
            //{
            //    if (sysSet.ConstValue == "1")
            //    {
            //        this.ckSynchronization.Checked = true;
            //    }
            //    else
            //    {
            //        this.ckSynchronization.Checked = false;
            //    }
            //}
            var sysSet2 = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_IsMonthReportGetAVG).FirstOrDefault();
            if (sysSet2 != null)
            {
                if (sysSet2.ConstValue == "1")
                {
                    this.ckIsMonthReportGetAVG.Checked = true;
                }
                else
                {
                    this.ckIsMonthReportGetAVG.Checked = false;
                }
            }
            var sysSet3 = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_MonthReportFreezeDay).FirstOrDefault();
            if (sysSet3 != null)
            {
                this.txtMonthReportFreezeDay.Text = sysSet3.ConstValue;
            }

            var sysSet4 = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_MenuFlowOperate).FirstOrDefault();
            if (sysSet4 != null)
            {
                if (sysSet4.ConstValue == "1")
                {
                    this.ckMenuFlowOperate.Checked = true;
                }
                else
                {
                    this.ckMenuFlowOperate.Checked = false;
                }
            }
            var sysSet5 = (from x in Funs.DB.Sys_Const where x.ConstText == "员工绩效考核第一季度生成时间" select x).ToList().FirstOrDefault();
            if (sysSet5 != null)
            {
                string[] str = sysSet5.ConstValue.Split('|');
                if (str.Length > 0)
                {
                    this.txtMarch.Text = (str[0] == null ? "" : str[0]).ToString();
                    this.txtMarchday.Text = (str[1] == null ? "" : str[1]).ToString();
                }
            }
            var sysSet6 = (from x in Funs.DB.Sys_Const where x.ConstText == "员工绩效考核第二季度生成时间" select x).ToList().FirstOrDefault();
            if (sysSet6 != null)
            {
                string[] str = sysSet6.ConstValue.Split('|');
                if (str.Length > 0)
                {
                    this.txtJune.Text = (str[0] == null ? "" : str[0]).ToString();
                    this.txtJuneday.Text = (str[1] == null ? "" : str[1]).ToString();
                }
            }
            var sysSet7 = (from x in Funs.DB.Sys_Const where x.ConstText == "员工绩效考核第三季度生成时间" select x).ToList().FirstOrDefault();
            if (sysSet7 != null)
            {
                string[] str = sysSet7.ConstValue.Split('|');
                if (str.Length > 0)
                {
                    this.txtSeptember.Text = (str[0] == null ? "" : str[0]).ToString();
                    this.txtSeptemberday.Text = (str[1] == null ? "" : str[1]).ToString();
                }
            }
            var sysSet8 = (from x in Funs.DB.Sys_Const where x.ConstText == "员工绩效考核第四季度生成时间" select x).ToList().FirstOrDefault();
            if (sysSet8 != null)
            {
                string[] str = sysSet8.ConstValue.Split('|');
                if (str.Length > 0)
                {
                    this.txtDecember.Text = (str[0] == null ? "" : str[0]).ToString();
                    this.txtDecemberday.Text = (str[1] == null ? "" : str[1]).ToString();
                }
            }
            var sysSet9 = (from x in Funs.DB.Sys_Set where x.SetName == "集团接口地址" select x).ToList().FirstOrDefault();
            if (sysSet9 != null)
            {
                txtSerVerUrl.Text = sysSet9.SetValue;
            }
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var db = new Model.SGGLDB(Funs.ConnString);
            //var sysSet = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_Synchronization).FirstOrDefault();
            //if (sysSet != null)
            //{
            //    if (this.ckSynchronization.Checked == true)
            //    {
            //        sysSet.ConstValue = "1";
            //    }
            //    else
            //    {
            //        sysSet.ConstValue = "0";
            //    }
            //    Funs.DB.SubmitChanges();
            //}
            var sysSet2 = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_IsMonthReportGetAVG).FirstOrDefault();
            if (sysSet2 != null)
            {
                if (this.ckIsMonthReportGetAVG.Checked == true)
                {
                    sysSet2.ConstValue = "1";
                }
                else
                {
                    sysSet2.ConstValue = "0";
                }
                db.SubmitChanges();
            }
            var sysSet3 = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_MonthReportFreezeDay).FirstOrDefault();
            if (sysSet3 != null)
            {
                sysSet3.ConstValue = this.txtMonthReportFreezeDay.Text.Trim();
                Funs.DB.SubmitChanges();
            }

            var sysSet4 = BLL.ConstValue.drpConstItemList(BLL.ConstValue.Group_MenuFlowOperate).FirstOrDefault();
            if (sysSet4 != null)
            {
                if (this.ckMenuFlowOperate.Checked == true)
                {
                    sysSet4.ConstValue = "1";
                }
                else
                {
                    sysSet4.ConstValue = "0";
                }
                db.SubmitChanges();
            }
            Model.Sys_Const sysSet5 = db.Sys_Const.FirstOrDefault(x => x.ConstText == "员工绩效考核第一季度生成时间");
            if (sysSet5 != null)
            {
                if (!string.IsNullOrEmpty(this.txtMarch.Text.Trim()))
                {
                    sysSet5.ConstValue = this.txtMarch.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtMarchday.Text.Trim()))
                {
                    sysSet5.ConstValue += "|" + this.txtMarchday.Text.Trim();
                }
                Funs.DB.SubmitChanges();
            }
            else
            {
                Model.Sys_Const newSysSet5 = new Model.Sys_Const();
                newSysSet5.ID = SQLHelper.GetNewID();
                if (!string.IsNullOrEmpty(this.txtMarch.Text.Trim()))
                {
                    newSysSet5.ConstValue = this.txtMarch.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtMarchday.Text.Trim()))
                {
                    newSysSet5.ConstValue += "|" + this.txtMarchday.Text.Trim();
                }
                newSysSet5.ConstText = "员工绩效考核第一季度生成时间";
                newSysSet5.SortIndex = 1;
                newSysSet5.GroupId = "PersonQuarterCheck";
                Funs.DB.Sys_Const.InsertOnSubmit(newSysSet5);
                Funs.DB.SubmitChanges();
            }
            var sysSet6 = db.Sys_Const.FirstOrDefault(x => x.ConstText == "员工绩效考核第二季度生成时间");
            if (sysSet6 != null)
            {
                if (!string.IsNullOrEmpty(this.txtJune.Text.Trim()))
                {
                    sysSet6.ConstValue = this.txtJune.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtJuneday.Text.Trim()))
                {
                    sysSet6.ConstValue += "|" + this.txtJuneday.Text.Trim();
                }
                db.SubmitChanges();
            }
            else
            {
                Model.Sys_Const newSysSet6 = new Model.Sys_Const();
                newSysSet6.ID = SQLHelper.GetNewID();
                if (!string.IsNullOrEmpty(this.txtJune.Text.Trim()))
                {
                    newSysSet6.ConstValue = this.txtJune.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtJuneday.Text.Trim()))
                {
                    newSysSet6.ConstValue += "|" + this.txtJuneday.Text.Trim();
                }
                newSysSet6.ConstText = "员工绩效考核第二季度生成时间";
                newSysSet6.SortIndex = 2;
                newSysSet6.GroupId = "PersonQuarterCheck";
                Funs.DB.Sys_Const.InsertOnSubmit(newSysSet6);
                Funs.DB.SubmitChanges();
            }
            var sysSet7 = db.Sys_Const.FirstOrDefault(x => x.ConstText == "员工绩效考核第三季度生成时间");
            if (sysSet7 != null)
            {
                if (!string.IsNullOrEmpty(this.txtSeptember.Text.Trim()))
                {
                    sysSet7.ConstValue = this.txtSeptember.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtSeptemberday.Text.Trim()))
                {
                    sysSet7.ConstValue += "|" + this.txtSeptemberday.Text.Trim();
                }
                db.SubmitChanges();
            }
            else
            {
                Model.Sys_Const newSysSet7 = new Model.Sys_Const();
                newSysSet7.ID = SQLHelper.GetNewID();
                if (!string.IsNullOrEmpty(this.txtSeptember.Text.Trim()))
                {
                    newSysSet7.ConstValue = this.txtSeptember.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtSeptemberday.Text.Trim()))
                {
                    newSysSet7.ConstValue += "|" + this.txtSeptemberday.Text.Trim();
                }
                newSysSet7.ConstText = "员工绩效考核第三季度生成时间";
                newSysSet7.SortIndex = 3;
                newSysSet7.GroupId = "PersonQuarterCheck";
                Funs.DB.Sys_Const.InsertOnSubmit(newSysSet7);
                Funs.DB.SubmitChanges();
            }
            var sysSet8 = db.Sys_Const.FirstOrDefault(x => x.ConstText == "员工绩效考核第四季度生成时间");
            if (sysSet8 != null)
            {
                if (!string.IsNullOrEmpty(this.txtDecember.Text.Trim()))
                {
                    sysSet8.ConstValue = this.txtDecember.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtDecemberday.Text.Trim()))
                {
                    sysSet8.ConstValue += "|" + this.txtDecemberday.Text.Trim();
                }
                db.SubmitChanges();
            }
            else
            {
                Model.Sys_Const newSysSet8 = new Model.Sys_Const();
                newSysSet8.ID = SQLHelper.GetNewID();
                if (!string.IsNullOrEmpty(this.txtDecember.Text.Trim()))
                {
                    newSysSet8.ConstValue = this.txtDecember.Text.Trim();
                }
                if (!string.IsNullOrEmpty(this.txtDecemberday.Text.Trim()))
                {
                    newSysSet8.ConstValue += "|" + this.txtDecemberday.Text.Trim();
                }
                newSysSet8.ConstText = "员工绩效考核第四季度生成时间";
                newSysSet8.SortIndex = 4;
                newSysSet8.GroupId = "PersonQuarterCheck";
                Funs.DB.Sys_Const.InsertOnSubmit(newSysSet8);
                Funs.DB.SubmitChanges();
            }
            Model.Sys_Set sysSet9 = db.Sys_Set.FirstOrDefault(x => x.SetName == "集团接口地址");
            if (sysSet9 != null)
            {
                if (!string.IsNullOrEmpty(this.txtSerVerUrl.Text.Trim()))
                {
                    sysSet9.SetValue = this.txtSerVerUrl.Text.Trim();
                }
                db.SubmitChanges();
            }
            else
            {
                Model.Sys_Set newSysSet9 = new Model.Sys_Set();
                if (!string.IsNullOrEmpty(this.txtSerVerUrl.Text.Trim()))
                {
                    newSysSet9.SetValue = this.txtSerVerUrl.Text.Trim();
                }
                newSysSet9.SetName = "集团接口地址";
                Funs.DB.Sys_Set.InsertOnSubmit(newSysSet9);
                Funs.DB.SubmitChanges();
            }
            ShowNotify("保存成功!", MessageBoxIcon.Success);
            BLL.LogService.AddSys_Log(this.CurrUser, "修改系统环境设置!", string.Empty, BLL.Const.SysConstSetMenuId, BLL.Const.BtnModify);
        }

        #endregion

        #region TAB2加载页面方法
        /// <summary>
        /// TAB2加载页面方法
        /// </summary>
        private void LoadTab2Data()
        {
            this.treeMenu.Nodes.Clear();
            var sysMenu = BLL.SysMenuService.GetMenuListByMenuType(this.drpSuperMenu.SelectedValue);
            if (sysMenu.Count() > 0)
            {
                this.InitTreeMenu(sysMenu, null);
            }
        }

        #region 加载菜单下拉框树
        /// <summary>
        /// 加载菜单下拉框树
        /// </summary>
        private void InitTreeMenu(List<Model.Sys_Menu> menusList, TreeNode node)
        {
            string supMenu = "0";
            if (node != null)
            {
                supMenu = node.NodeID;
            }
            var menuItemList = menusList.Where(x => x.SuperMenu == supMenu).OrderBy(x => x.SortIndex);    //获取菜单列表
            if (menuItemList.Count() > 0)
            {
                foreach (var item in menuItemList)
                {
                    TreeNode newNode = new TreeNode
                    {
                        Text = item.MenuName,
                        NodeID = item.MenuId,
                    };

                    if (node == null)
                    {
                        this.treeMenu.Nodes.Add(newNode);
                    }
                    else
                    {
                        node.Nodes.Add(newNode);
                    }
                    if (!item.IsEnd.HasValue || item.IsEnd == false)
                    {
                        InitTreeMenu(menusList, newNode);
                    }
                }
            }
        }
        #endregion

        #region 下拉框回发事件
        /// <summary>
        /// 下拉框回发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void drpMenu_TextChanged(object sender, EventArgs e)
        {
            string menuId = this.drpMenu.Value;
            ///加载流程列表
            this.BindGrid();
            var sysMenu = BLL.SysMenuService.GetSysMenuByMenuId(menuId);
            if (sysMenu != null && sysMenu.IsEnd == true)
            {
                var codeTemplateRule = BLL.SysConstSetService.GetCodeTemplateRuleByMenuId(sysMenu.MenuId);
                if (codeTemplateRule != null)
                {
                    if (codeTemplateRule.IsProjectCode == true)
                    {
                        this.ckProjectCode.Checked = true;
                    }
                    else
                    {
                        this.ckProjectCode.Checked = false;
                    }
                    this.txtPrefix.Text = codeTemplateRule.Prefix;
                    if (codeTemplateRule.IsUnitCode == true)
                    {
                        this.ckUnitCode.Checked = true;
                    }
                    else
                    {
                        this.ckUnitCode.Checked = false;
                    }
                    this.txtDigit.Text = codeTemplateRule.Digit.ToString();
                    this.txtTemplate.Text = HttpUtility.HtmlDecode(codeTemplateRule.Template);
                    this.txtSymbol.Text = codeTemplateRule.Symbol;
                }
                else
                {
                    this.ckProjectCode.Checked = true;
                    this.txtDigit.Text = "4";
                    this.txtSymbol.Text = "-";
                    this.txtPrefix.Text = string.Empty;
                    this.ckUnitCode.Checked = false;
                    this.txtTemplate.Text = HttpUtility.HtmlDecode(string.Empty);
                }
            }
            else
            {
                this.drpMenu.Text = string.Empty;
                this.drpMenu.Value = string.Empty;
                if (sysMenu != null)
                {
                    ShowNotify("请选择末级菜单操作!", MessageBoxIcon.Warning);
                }
            }
        }
        #endregion

        #region 流程列表绑定数据
        /// <summary>
        /// 流程列表绑定数据
        /// </summary>
        private void BindGrid()
        {
            string strSql = @"SELECT flow.FlowOperateId,flow.MenuId,flow.FlowStep,flow.GroupNum,flow.OrderNum,flow.AuditFlowName,flow.RoleId,flow.IsFlowEnd"
                + @" FROM dbo.Sys_MenuFlowOperate AS flow "
                + @" WHERE flow.MenuId=@MenuId";
            List<SqlParameter> listStr = new List<SqlParameter>();
            string menuId = string.Empty;
            if (!string.IsNullOrEmpty(this.drpMenu.Value))
            {
                menuId = this.drpMenu.Value;
            }
            listStr.Add(new SqlParameter("@MenuId", menuId));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }

        /// <summary>
        /// 得到角色名称字符串
        /// </summary>
        /// <param name="bigType"></param>
        /// <returns></returns>
        protected string ConvertRole(object roleIds)
        {
            return BLL.RoleService.getRoleNamesRoleIds(roleIds);
        }

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 增加编辑事件
        /// <summary>
        /// 增加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFlowOperateNew_Click(object sender, EventArgs e)
        {
            var sysMenu = SysMenuService.GetSysMenuByMenuId(this.drpMenu.Value);
            if (sysMenu != null && sysMenu.IsEnd == true)
            {
                var getMenuFlowOperate = Funs.DB.Sys_MenuFlowOperate.FirstOrDefault(x => x.MenuId == sysMenu.MenuId && x.IsFlowEnd == true);
                if (getMenuFlowOperate == null)
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("MenuFlowOperateEdit.aspx?MenuId={0}&FlowOperateId={1}", sysMenu.MenuId, string.Empty, "增加 - ")));
                }
                else
                {
                    Alert.ShowInParent("流程已存在结束步骤!", MessageBoxIcon.Warning);
                }

            }
        }

        /// <summary>
        /// Grid双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            var sysMenu = BLL.SysMenuService.GetSysMenuByMenuId(this.drpMenu.Value);
            if (sysMenu != null && sysMenu.IsEnd == true)
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("MenuFlowOperateEdit.aspx?MenuId={0}&FlowOperateId={1}", sysMenu.MenuId, Grid1.SelectedRowID, "编辑 - ")));
            }
        }
        #endregion

        #region  删除数据
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFlowOperateDelete_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                if (LicensePublicService.lisenWorkList.Contains(this.drpMenu.Value))
                {
                    foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                    {
                        string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                        BLL.SysConstSetService.DeleteMenuFlowOperateLicense(rowID);
                    }
                }
                else
                {
                    foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                    {
                        string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                        BLL.SysConstSetService.DeleteMenuFlowOperateByFlowOperateId(rowID);
                    }
                }

                BLL.MenuFlowOperateService.SetSortIndex(this.drpMenu.Value);
                BindGrid();
                BLL.LogService.AddSys_Log(this.CurrUser, "删除审批流程信息!", null, BLL.Const.SysConstSetMenuId, BLL.Const.BtnDelete);
                ShowNotify("删除数据成功!");
            }
        }
        #endregion

        #region 关闭弹出窗口
        /// <summary>
        /// 关闭弹出窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #endregion        

        #region TAB2保存按钮
        /// <summary>
        /// TAB2保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnTab2Save_Click(object sender, EventArgs e)
        {
            var sysMenu = BLL.SysMenuService.GetSysMenuByMenuId(this.drpMenu.Value);
            if (sysMenu != null && sysMenu.IsEnd == true)
            {
                this.SaveData2(sysMenu.MenuId);
                BLL.LogService.AddSys_Log(this.CurrUser, "修改菜单编码模板设置!", null, BLL.Const.SysConstSetMenuId, BLL.Const.BtnModify);
                ShowNotify("保存成功!", MessageBoxIcon.Success);
            }
            else
            {
                ShowNotify("请选择菜单!", MessageBoxIcon.Warning);
                return;
            }
        }

        /// <summary>
        /// TAB2保存方法
        /// </summary>
        private void SaveData2(string menuId)
        {
            Model.Sys_CodeTemplateRule newCodeTemplateRule = new Model.Sys_CodeTemplateRule
            {
                MenuId = menuId,
                Template = HttpUtility.HtmlEncode(this.txtTemplate.Text),
                Symbol = this.txtSymbol.Text.Trim(),
                IsProjectCode = this.ckProjectCode.Checked,
                Prefix = this.txtPrefix.Text.Trim(),
                IsUnitCode = this.ckUnitCode.Checked,
                Digit = Funs.GetNewInt(this.txtDigit.Text),
            };
            var getCodeTemplateRule = BLL.SysConstSetService.GetCodeTemplateRuleByMenuId(menuId);
            if (getCodeTemplateRule != null)
            {
                newCodeTemplateRule.CodeTemplateRuleId = getCodeTemplateRule.CodeTemplateRuleId;
                BLL.SysConstSetService.UpdateCodeTemplateRule(newCodeTemplateRule);
            }
            else
            {
                BLL.SysConstSetService.AddCodeTemplateRule(newCodeTemplateRule);
            }
        }
        #endregion
        #endregion

        #region TAB3加载页面方法
        /// <summary>
        /// 加载页面方法
        /// </summary>
        private void LoadTab3Data()
        {
            var sysTestRule = Funs.DB.Sys_TestRule.FirstOrDefault();
            if (sysTestRule != null)
            {
                this.txtDuration.Text = sysTestRule.Duration.ToString();
                this.txtSValue.Text = sysTestRule.SValue.ToString();
                this.txtMValue.Text = sysTestRule.MValue.ToString();
                this.txtJValue.Text = sysTestRule.JValue.ToString();
                this.txtSCount.Text = sysTestRule.SCount.ToString();
                this.txtMCount.Text = sysTestRule.MCount.ToString();
                this.txtJCount.Text = sysTestRule.JCount.ToString();
                txtTab3_TextChanged(null, null);
                this.txtPassingScore.Text = sysTestRule.PassingScore.ToString();
            }
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnTab3Save_Click(object sender, EventArgs e)
        {
            var getTestRule = from x in Funs.DB.Sys_TestRule select x;
            if (getTestRule.Count() > 0)
            {
                Funs.DB.Sys_TestRule.DeleteAllOnSubmit(getTestRule);
            }

            Model.Sys_TestRule newTestRule = new Model.Sys_TestRule
            {
                TestRuleId = SQLHelper.GetNewID(),
                Duration = Funs.GetNewIntOrZero(this.txtDuration.Text),
                SValue = Funs.GetNewIntOrZero(this.txtSValue.Text),
                MValue = Funs.GetNewIntOrZero(this.txtMValue.Text),
                JValue = Funs.GetNewIntOrZero(this.txtJValue.Text),
                SCount = Funs.GetNewIntOrZero(this.txtSCount.Text),
                MCount = Funs.GetNewIntOrZero(this.txtMCount.Text),
                JCount = Funs.GetNewIntOrZero(this.txtJCount.Text),
                PassingScore = Funs.GetNewIntOrZero(this.txtPassingScore.Text),
            };

            Funs.DB.Sys_TestRule.InsertOnSubmit(newTestRule);
            Funs.DB.SubmitChanges();

            ShowNotify("保存成功!", MessageBoxIcon.Success);
            LogService.AddSys_Log(this.CurrUser, "修改考试规则设置!", string.Empty, Const.SysConstSetMenuId, Const.BtnModify);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtTab3_TextChanged(object sender, EventArgs e)
        {
            int SValue = Funs.GetNewIntOrZero(this.txtSValue.Text);
            int MValue = Funs.GetNewIntOrZero(this.txtMValue.Text);
            int JValue = Funs.GetNewIntOrZero(this.txtJValue.Text);
            int SCount = Funs.GetNewIntOrZero(this.txtSCount.Text);
            int MCount = Funs.GetNewIntOrZero(this.txtMCount.Text);
            int JCount = Funs.GetNewIntOrZero(this.txtJCount.Text);
            this.lbTotalScore.Text = (SCount * SValue + MCount * MValue + JCount * JValue).ToString();
            this.lbTotalCount.Text = (SCount + MCount + JCount).ToString();
        }
        #endregion

        /// <summary>
        ///  选择菜单类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rblMenuType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.drpSuperMenu.Items.Clear();
            ConstValue.InitConstValueDropDownList(this.drpSuperMenu, this.rblMenuType.SelectedValue, true);
            this.LoadTab2Data();
            this.drpMenu.Text = string.Empty;
            this.drpMenu.Value = string.Empty;
        }

        protected void drpSuperMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.LoadTab2Data();
            this.drpMenu.Text = string.Empty;
            this.drpMenu.Value = string.Empty;
        }

        #region LoadTab4Data
        #region 产值页面数据显示
        /// <summary>
        /// 初始化产值页面
        /// </summary>
        private void LoadTab4Data()
        {
            BLL.ConstValue.InitConstValueDropDownList(this.drpYear, ConstValue.Group_0008, false);
            this.drpYear.SelectedValue = DateTime.Now.Year.ToString();
            BLL.ConstValue.InitConstValueDropDownList(this.drpMonth, ConstValue.Group_0009, false);
            this.drpMonth.SelectedValue = DateTime.Now.Month.ToString();
            ShowTab4();
            BindGridOutPut();
        }
        /// <summary>
        ///  总产值绑定
        /// </summary>
        private void ShowTab4()
        {
            this.txtYearPlanOutPutValue.Text = string.Empty;
            this.txtYearActualOutPutValue.Text = string.Empty;
            var getOutputValue = Funs.DB.Sys_OutputValue.FirstOrDefault(x => x.Year.ToString() == this.drpYear.SelectedValue);
            if (getOutputValue != null)
            {
                this.txtYearPlanOutPutValue.Text = getOutputValue.YearPlanOutPutValue.ToString();
                this.txtYearActualOutPutValue.Text = getOutputValue.YearActualOutPutValue.ToString();
            }
        }

        /// <summary>
        ///  项目月产值绑定
        /// </summary>
        private void BindGridOutPut()
        {
            string strSql = @"SELECT O.OutputValueProjectId,O.ProjectId,P.ProjectCode,P.ProjectName,O.Month,O.Year,O.PlanOutPutValue,O.ActualOutPutValue
                        FROM Sys_OutputValueProject AS O
                        LEFT JOIN Base_Project AS P ON O.ProjectId=P.ProjectId 
                        WHERE O.Year=@Year AND O.Month=@Month";
            List<SqlParameter> listStr = new List<SqlParameter>
            {
                new SqlParameter("@Year", Funs.GetNewIntOrZero(this.drpYear.SelectedValue)),
                new SqlParameter("@Month", Funs.GetNewIntOrZero(this.drpMonth.SelectedValue))
            };
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            GridOutPut.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(GridOutPut, tb);
            GridOutPut.DataSource = table;
            GridOutPut.DataBind();
        }
        #endregion

        #region 年月下拉框事件
        /// <summary>
        /// 年下拉框事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowTab4();
            BindGridOutPut();
        }
        /// <summary>
        /// 月下拉框事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void drpMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridOutPut();
        }
        #endregion

        #region  年度施工产值保存
        /// <summary>
        /// 年度施工产值保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnYearOutPutValue_Click(object sender, EventArgs e)
        {
            int year = Funs.GetNewIntOrZero(this.drpYear.SelectedValue);
            if (year > 0)
            {
                SysConstSetService.SetYearOutputValue(this.drpYear.SelectedValue);
                //var getOutputValue = Funs.DB.Sys_OutputValue.FirstOrDefault(x => x.Year.ToString() == this.drpYear.SelectedValue);
                //if (getOutputValue != null)
                //{
                //    getOutputValue.YearPlanOutPutValue = Funs.GetNewDecimalOrZero(this.txtYearPlanOutPutValue.Text);
                //    getOutputValue.YearActualOutPutValue = Funs.GetNewDecimalOrZero(this.txtYearActualOutPutValue.Text);
                //    Funs.DB.SubmitChanges();
                //}
                //else
                //{
                //    Model.Sys_OutputValue newOutPutValue = new Model.Sys_OutputValue()
                //    {
                //        OutPutValueId = SQLHelper.GetNewID(),
                //        Year = year,
                //        YearPlanOutPutValue = Funs.GetNewDecimalOrZero(this.txtYearPlanOutPutValue.Text),
                //        YearActualOutPutValue = Funs.GetNewDecimalOrZero(this.txtYearActualOutPutValue.Text),
                //    };
                //    Funs.DB.Sys_OutputValue.InsertOnSubmit(newOutPutValue);
                //    Funs.DB.SubmitChanges();
                //}
                ShowNotify("刷新成功!", MessageBoxIcon.Success);
                return;
            }
            else
            {
                Alert.ShowInParent("请选择年度!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion

        #region GridOutPut 删除
        /// <summary>
        ///  GridOutPut 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOutPutDel_Click(object sender, EventArgs e)
        {
            if (GridOutPut.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in GridOutPut.SelectedRowIndexArray)
                {
                    string rowID = GridOutPut.DataKeys[rowIndex][0].ToString();
                    var getOutputValueProject = Funs.DB.Sys_OutputValueProject.FirstOrDefault(x => x.OutputValueProjectId == rowID);
                    if (getOutputValueProject != null)
                    {
                        Funs.DB.Sys_OutputValueProject.DeleteOnSubmit(getOutputValueProject);
                        Funs.DB.SubmitChanges();
                    }
                }
                BindGridOutPut();
                BLL.LogService.AddSys_Log(this.CurrUser, "删除项目施工产值!", null, BLL.Const.SysConstSetMenuId, BLL.Const.BtnDelete);
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridOutPut_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            var getOutP = Funs.DB.Sys_OutputValueProject.FirstOrDefault(x => x.OutputValueProjectId == GridOutPut.SelectedRowID);
            if (getOutP != null)
            {
                PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("OutputValueProject.aspx?OutputValueProjectId={0}", GridOutPut.SelectedRowID, "编辑 - ")));
            }
            else
            {
                Alert.ShowInParent("请选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOutPutAdd_Click(object sender, EventArgs e)
        {
            int year = Funs.GetNewIntOrZero(this.drpYear.SelectedValue);
            int month = Funs.GetNewIntOrZero(this.drpMonth.SelectedValue);
            if (year > 0 && month > 0)
            {
                PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("OutputValueProject.aspx?Year={0}&Month={1}", year, month, "增加 - ")));
            }
            else
            {
                Alert.ShowInParent("请选择年度月份!", MessageBoxIcon.Warning);
                return;
            }
        }

        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            this.ShowTab4();
            this.BindGridOutPut();
        }
        #endregion

        protected void btnApply_Click(object sender, EventArgs e)
        {
            string CNCECPath = SysConstSetService.CNCECPath;

            string baseurl = CNCECPath + "/api/Common/ApplyToken";
            var client = new RestClient(baseurl);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            var thisUnit = BLL.UnitService.GetUnitByUnitId(BLL.Const.UnitId_CD);
            request.AddParameter("UnitName", thisUnit.UnitName);
            request.AddParameter("CollCropCode", thisUnit.CollCropCode);
            IRestResponse response = client.Execute(request);
            var responeData = JsonConvert.DeserializeObject<Model.ResponeData>(response.Content.ToString());
            TokenItem tokenItem = new TokenItem();
            if (responeData.code == 1)
            {
                var token = JsonConvert.DeserializeObject<Model.TokenItem>(responeData.data.ToString());
                tokenItem.Token = token.Token.ToString();
                tokenItem.ExpiryTime = token.ExpiryTime.ToString();
                SysConstSetService.SetToken(tokenItem.Token);
                SysConstSetService.SetTokenExpirationTime(tokenItem.ExpiryTime);
            }
            Alert.Show(response.Content);


        }
    }
}