using BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

namespace FineUIPro.Web.HJGL.TestPackageManage
{
    public partial class TestPackageManageView : PageBase
    {
        #region 定义项
        /// <summary>
        /// 试压包主键
        /// </summary>
        public string PTP_ID
        {
            get
            {
                return (string)ViewState["PTP_ID"];
            }
            set
            {
                ViewState["PTP_ID"] = value;
            }
        }

        ///// <summary>
        ///// 未通过数
        ///// </summary>
        //public int Count
        //{
        //    get
        //    {
        //        return (int)ViewState["Count"];
        //    }
        //    set
        //    {
        //        ViewState["Count"] = value;
        //    }
        //}

        /// <summary>
        /// 管线集合
        /// </summary>
        private List<Model.View_TestPackageManageAudit> isoInfos = new List<Model.View_TestPackageManageAudit>();


        public int Count1 = 0;
        public int Count2 = 0;
        public int Count3 = 0;
        public int Count4 = 0;

        #endregion

        #region 加载
        /// <summary>
        ///加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtReportDate.Text = string.Format("{0:yyyy-MM}", DateTime.Now);

                BLL.UserService.InitUserDropDownList(this.drpPTP_Finisher, this.CurrUser.LoginProjectId, true);//完工人

                this.InitTreeMenu();
            }
        }
        #endregion

        #region 加载树装置-单位-工作区
        /// <summary>
        /// 加载树
        /// </summary>
        private void InitTreeMenu()
        {
            if (!string.IsNullOrEmpty(this.txtReportDate.Text.Trim()))
            {
                DateTime? startTime = Funs.GetNewDateTime(this.txtReportDate.Text.Trim());
                DateTime? endTime = startTime.HasValue ? startTime.Value.AddMonths(1) : System.DateTime.Now;

                this.tvControlItem.Nodes.Clear();
                TreeNode rootNode = new TreeNode();
                rootNode.Text = "单位-装置-月份";
                rootNode.NodeID = "0";
                rootNode.Expanded = true;
                this.tvControlItem.Nodes.Add(rootNode);

                List<Model.Base_Unit> units = null;
                var unit = BLL.UnitService.GetUnitByUnitId(this.CurrUser.UnitId);
                if (unit == null || unit.UnitTypeId == BLL.Const.ProjectUnitType_1 || unit.UnitTypeId == BLL.Const.ProjectUnitType_3)
                {
                    if (BLL.WorkAreaService.IsSupervisor(this.CurrUser.UnitId, this.CurrUser.LoginProjectId))
                    {
                        units = (from x in Funs.DB.Base_Unit
                                 join y in Funs.DB.ProjectData_WorkArea on x.UnitId equals y.UnitId
                                 where (x.UnitId == this.CurrUser.UnitId || y.SupervisorUnitId == this.CurrUser.UnitId) && y.ProjectId == this.CurrUser.LoginProjectId
                                 select x).Distinct().ToList();
                    }
                    else
                    {
                        units = BLL.UnitService.GetUnitByProjectIdUnitTypeList(this.CurrUser.LoginProjectId, "2");
                    }
                }
                else
                {
                    units = (from x in Funs.DB.Base_Unit where x.UnitId == this.CurrUser.UnitId select x).ToList();
                }
                List<Model.TP_TestPackage> testPackageLists = new List<Model.TP_TestPackage>(); ///试压包
                if (!this.txtReportDate.Hidden)
                {
                    testPackageLists = (from x in Funs.DB.TP_TestPackage
                                        where x.ProjectId == this.CurrUser.LoginProjectId && x.PTP_AduditDate >= startTime && x.PTP_AduditDate < endTime
                                        select x).ToList();
                }
                if (units != null)
                {
                    foreach (var item in units)
                    {
                        TreeNode rootUnitNode = new TreeNode();//定义根节点
                        rootUnitNode.Text = item.UnitName;
                        rootUnitNode.NodeID = item.UnitId;
                        rootUnitNode.Expanded = true;
                        rootUnitNode.ToolTip = "施工单位";
                        rootNode.Nodes.Add(rootUnitNode);
                        var lists = testPackageLists.Where(x => x.BSU_ID == item.UnitId).ToList();
                        this.BindNodes(rootUnitNode, lists);
                    }
                }
                else
                {
                    Alert.ShowInTop("请先增加施工单位!", MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                Alert.ShowInTop("请选择试压审核月份!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion

        #region 绑定树节点
        /// <summary>
        ///  绑定树节点
        /// </summary>
        /// <param name="node"></param>
        private void BindNodes(TreeNode node, List<Model.TP_TestPackage> testPackageLists)
        {
            if (node.ToolTip == "施工单位")
            {
                var installId = (from x in testPackageLists select x.InstallationId).Distinct();
                if (installId.Count() > 0)
                {
                    var install = from x in Funs.DB.Project_Installation where installId.Contains(x.InstallationId) orderby x.InstallationCode select x;
                    foreach (var q in install)
                    {
                        TreeNode newNode = new TreeNode();
                        newNode.Text = q.InstallationCode + q.InstallationName;
                        newNode.NodeID = q.InstallationId + "|" + node.NodeID; ;
                        newNode.ToolTip = "装置";
                        newNode.Expanded = true;
                        node.Nodes.Add(newNode);
                        this.BindNodes(newNode, testPackageLists);
                    }
                }
            }
            else if (node.ToolTip == "装置")
            {
                string installationId = Funs.GetStrListByStr(node.NodeID, '|')[0];
                var listMonth = (from x in testPackageLists
                                 where x.InstallationId == installationId && x.BSU_ID == node.ParentNode.NodeID
                                 select string.Format("{0:yyyy-MM}", x.PTP_AduditDate)).Distinct();
                foreach (var item in listMonth)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item;
                    newNode.NodeID = item + "|" + node.NodeID; ;
                    newNode.ToolTip = "月份";
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, testPackageLists);
                }
            }
            else if (node.ToolTip == "月份")
            {
                string installationId = Funs.GetStrListByStr(node.ParentNode.NodeID, '|')[0];
                var days = (from x in testPackageLists
                            where x.InstallationId == installationId && x.BSU_ID == node.ParentNode.ParentNode.NodeID
                            orderby x.PTP_AduditDate descending
                            select x.PTP_AduditDate).Distinct();
                foreach (var item in days)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = string.Format("{0:yyyy-MM-dd}", item);
                    newNode.NodeID = item.ToString() + "|" + node.NodeID; ;
                    newNode.ToolTip = "日期";
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, testPackageLists);
                }
            }
            else if (node.ToolTip == "日期")
            {
                string installationId = Funs.GetStrListByStr(node.ParentNode.ParentNode.NodeID, '|')[0];
                var dReports = from x in testPackageLists
                               where x.InstallationId == installationId && x.BSU_ID == node.ParentNode.ParentNode.ParentNode.NodeID
                               && x.PTP_AduditDate == Funs.GetNewDateTime(node.Text)
                               orderby x.PTP_TestPackageNo descending
                               select x;
                foreach (var item in dReports)
                {
                    TreeNode newNode = new TreeNode();
                    if (!string.IsNullOrEmpty(item.PTP_TestPackageNo))
                    {
                        newNode.Text = item.PTP_TestPackageNo;
                    }
                    else
                    {
                        newNode.Text = "未知";
                    }
                    if (!item.PTP_FinishDate.HasValue || string.IsNullOrEmpty(item.PTP_Finisher))
                    {
                        newNode.Text = "<font color='#FF7575'>" + newNode.Text + "</font>";
                        node.Text = "<font color='#FF7575'>" + node.Text + "</font>";
                        node.ParentNode.Text = "<font color='#FF7575'>" + node.ParentNode.Text + "</font>";
                    }
                    newNode.NodeID = item.PTP_ID;
                    newNode.EnableClickEvent = true;
                    node.Nodes.Add(newNode);
                }
            }
        }
        #endregion

        #region 查询Tree
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        #endregion

        #region 点击树节点
        /// <summary>
        /// 点击树节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            this.PTP_ID = this.tvControlItem.SelectedNodeID;
            if (!string.IsNullOrEmpty(this.PTP_ID))
            {
                var testPackage = BLL.TestPackageManageEditService.GetTP_TestPackageByID(PTP_ID);
                if (testPackage != null)
                {
                    if (!string.IsNullOrEmpty(testPackage.BSU_ID))
                    {
                        this.txtUnitName.Text = BLL.UnitService.GetUnitNameByUnitId(testPackage.BSU_ID);
                    }
                    if (!string.IsNullOrEmpty(testPackage.InstallationId))
                    {
                        this.txtInstallationName.Text = BLL.Project_InstallationService.GetInstallationByInstallationId(testPackage.InstallationId).InstallationName;
                    }
                    this.txtPTP_TightnessTestTime.Text = testPackage.PTP_TightnessTestTime;
                    this.txtPTP_TestPackageNo.Text = testPackage.PTP_TestPackageNo;
                    if (!string.IsNullOrEmpty(testPackage.PTP_Modifier))
                    {
                        this.txtPTP_ModifierName.Text = BLL.UserService.GetUserNameByUserId(testPackage.PTP_Modifier);
                    }
                    this.txtPTP_LeakageTestService.Text = testPackage.PTP_LeakageTestService;
                    this.txtPTP_TestPackageName.Text = testPackage.PTP_TestPackageName;
                    this.txtPTP_ModifyDate.Text = testPackage.PTP_ModifyDate.HasValue ? string.Format("{0:yyyy-MM-dd}", testPackage.PTP_ModifyDate) : "";
                    this.txtPTP_LeakageTestPressure.Text = testPackage.PTP_LeakageTestPressure;
                    this.txtPTP_TestHeat.Text = testPackage.PTP_TestHeat;
                    this.txtPTP_TestPackageCode.Text = testPackage.PTP_TestPackageCode;
                    this.txtPTP_TightnessTestTemp.Text = testPackage.PTP_TightnessTestTemp;
                    this.txtPTP_TestService.Text = testPackage.PTP_TestService;
                    this.txtPTP_TestAmbientTemp.Text = testPackage.PTP_TestAmbientTemp;
                    this.txtPTP_VacuumTestService.Text = testPackage.PTP_VacuumTestService;
                    if (!string.IsNullOrEmpty(testPackage.PTP_TestType))
                    {
                        this.txtPTP_TestTypeName.Text = BLL.Base_PressureService.GetPressureByPressureId(testPackage.PTP_TestType).PressureName;
                    }
                    this.txtPTP_TestMediumTemp.Text = testPackage.PTP_TestMediumTemp;
                    this.txtPTP_VacuumTestPressure.Text = testPackage.PTP_VacuumTestPressure;
                    this.txtPTP_AllowSeepage.Text = testPackage.PTP_AllowSeepage;
                    this.txtPTP_TestPressure.Text = testPackage.PTP_TestPressure;
                    this.txtPTP_OperationMedium.Text = testPackage.PTP_OperationMedium;
                    this.txtPTP_FactSeepage.Text = testPackage.PTP_FactSeepage;
                    this.txtPTP_TestPressureTemp.Text = testPackage.PTP_TestPressureTemp;
                    this.txtPTP_PurgingMedium.Text = testPackage.PTP_PurgingMedium;
                    if (!string.IsNullOrEmpty(testPackage.PTP_Tabler))
                    {
                        this.txtPTP_TablerName.Text = BLL.UserService.GetUserNameByUserId(testPackage.PTP_Tabler);
                    }
                    this.txtPTP_TestPressureTime.Text = testPackage.PTP_TestPressureTime;
                    this.txtPTP_CleaningMedium.Text = testPackage.PTP_CleaningMedium;
                    this.txtPTP_TableDate.Text = testPackage.PTP_TableDate.HasValue ? string.Format("{0:yyyy-MM-dd}", testPackage.PTP_TableDate) : "";
                    this.txtPTP_TightnessTest.Text = testPackage.PTP_TightnessTest;
                    this.txtPTP_Remark.Text = testPackage.PTP_Remark;
                    if (!string.IsNullOrEmpty(testPackage.PTP_Auditer))
                    {
                        this.txtPTP_AuditerName.Text = BLL.UserService.GetUserNameByUserId(testPackage.PTP_Auditer);
                    }
                    this.txtPTP_AduditDate.Text = testPackage.PTP_AduditDate.HasValue ? string.Format("{0:yyyy-MM-dd}", testPackage.PTP_AduditDate) : "";
                    if (!string.IsNullOrEmpty(testPackage.PTP_Finisher))
                    {
                        this.drpPTP_Finisher.SelectedValue = testPackage.PTP_Finisher;
                    }
                    if (testPackage.PTP_FinishDate.HasValue)
                    {
                        this.btnCancelAudit.Hidden = false;
                        this.btnAudit.Hidden = true;
                        this.txtPTP_FinishDate.Text = String.Format("{0:yyyy-MM-dd}", testPackage.PTP_FinishDate);
                    }
                    else
                    {
                        this.btnCancelAudit.Hidden = true;
                        this.btnAudit.Hidden = false;
                        this.txtPTP_FinishDate.Text = String.Format("{0:yyyy-MM-dd}", DateTime.Now);
                    }

                    isoInfos.Clear();
                    isoInfos = BLL.TestPackageManageAuditService.GetTestPackageManageAuditByPTP_ID(PTP_ID);
                    if (isoInfos.Count > 0)
                    {
                        this.Grid1.DataSource = isoInfos;
                        this.Grid1.DataBind();
                    }
                }
            }
        }
        #endregion

        #region 审核
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAudit_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnAuditing))
            {
                if (!string.IsNullOrEmpty(this.PTP_ID))
                {
                    var updateTestPackage = BLL.TestPackageManageEditService.GetTP_TestPackageByID(this.PTP_ID);
                    if (updateTestPackage != null)
                    {
                        if (!string.IsNullOrEmpty(this.txtPTP_FinishDate.Text) && this.drpPTP_Finisher.SelectedValue != BLL.Const._Null && !string.IsNullOrEmpty(this.drpPTP_Finisher.SelectedValue))
                        {
                            updateTestPackage.PTP_FinishDate = Funs.GetNewDateTime(this.txtPTP_FinishDate.Text);
                            updateTestPackage.PTP_Finisher = this.drpPTP_Finisher.SelectedValue;
                            updateTestPackage.FinishDef = this.txtFinishDef.Text.Trim();
                            BLL.TestPackageManageAuditService.AuditFinishDef(updateTestPackage);
                            ShowNotify("试压包完工审核完成!", MessageBoxIcon.Success);
                            this.btnCancelAudit.Hidden = false;
                            this.btnAudit.Hidden = true;
                        }
                        else
                        {
                            Alert.ShowInTop("请填写完工人和完工日期!", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    else
                    {
                        Alert.ShowInTop("请选择要审核的单据!", MessageBoxIcon.Warning);
                        return;
                    }
                }
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 取消审核
        /// <summary>
        /// 取消审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancelAudit_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnCancelAuditing))
            {
                if (!string.IsNullOrEmpty(this.PTP_ID))
                {
                    var updateTestPackage = BLL.TestPackageManageEditService.GetTP_TestPackageByID(PTP_ID);
                    if (updateTestPackage != null)
                    {
                        updateTestPackage.PTP_Finisher = null;
                        updateTestPackage.PTP_FinishDate = null;
                        updateTestPackage.FinishDef = null;
                        BLL.TestPackageManageAuditService.AuditFinishDef(updateTestPackage);
                        ShowNotify("取消审核完成!", MessageBoxIcon.Success);
                        this.btnAudit.Hidden = false;
                        this.btnCancelAudit.Hidden = true;
                    }
                }
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region Grid行绑定事件
        /// <summary>
        /// Grid行绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            foreach (var item in isoInfos)
            {
                if (item.ISO_ID == e.RowID)
                {
                    decimal Rate = 0;
                    int? isoInfoCount = item.IsoInfoCount;//总焊口
                    int? isoInfoCountT = item.IsoInfoCountT;//完成总焊口
                    int? countS = item.CountS; //合格数
                    int? countU = item.CountU;//不合格数
                    bool convertible = decimal.TryParse(item.NDTR_Rate, out Rate);//应检测比例
                    decimal? Ratio = item.RatioC;//对接实际检测比例
                    decimal? RatioJ = item.RatioCJ;//承插实际检测比例


                    if (isoInfoCount > isoInfoCountT)//未焊完
                    {
                        Count1 += 1;
                        e.RowCssClass = "color1";
                    }
                    else if (Rate > Ratio && Rate > RatioJ)//已焊完,未达检测比例
                    {
                        Count2 += 1;
                        e.RowCssClass = "color2";
                    }
                    else if (countU > 0)////已焊完,已达检测比例,但有不合格
                    {
                        Count3 += 1;
                        e.RowCssClass = "color3";
                    }
                    else //已通过
                    {
                        Count4 += 1;
                        e.RowCssClass = "color4";
                    }
                }
            }
            //Count = Count1 + Count2 + Count3;
            this.lab1.Text = Count1.ToString();
            this.lab2.Text = Count2.ToString();
            this.lab3.Text = Count3.ToString();
            this.lab4.Text = Count4.ToString();
        }
        #endregion

        #region 获取按钮权限
        /// <summary>
        /// 获取按钮权限
        /// </summary>
        /// <param name="button"></param>
        /// <returns></returns>
        private bool GetButtonPower(string button)
        {
            return BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HJGL_TestPackageManageViewMenuId, button);
        }

        #endregion
    }
}