using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web.CQMS.Information
{
    public partial class CostReportEdit : PageBase
    {
        #region 定义变量
        /// 
        /// 方案审查主键
        /// 
        public string CostReportId
        {
            get
            {
                return (string)ViewState["CostReportId"];
            }
            set
            {
                ViewState["CostReportId"] = value;
            }
        }
        #endregion
        #region 定义集合
        /// 
        /// 定义会签意见集合
        /// 
        public static List approves = new List();
        #endregion
        public int ContactImg
        {
            get
            {
                return Convert.ToInt32(ViewState["ContactImg"]);
            }
            set
            {
                ViewState["ContactImg"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BLL.SecretLevelService.InitSecretLevelDropDownList(drpSecretLevel, true);
                UnitService.InitUnitByProjectIdUnitTypeDropDownList(drpUnit, CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, true);
                ContactImg = 0;
                //CommonService.GetAllButtonList(CurrUser.LoginProjectId, CurrUser.UserId, Const.CostReportMenuId);
                txtCompileDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                CostReportId = Request.Params["costReportId"];
                if (!string.IsNullOrWhiteSpace(CostReportId))
                {
                    HFCostReportId.Text = CostReportId;
                    Model.CQMS_CostReport costReport = CostReportService.GetCostReportByCostReportId(CostReportId);
                    txtCostReportCode.Text = costReport.CostReportCode;
                    if (!string.IsNullOrEmpty(costReport.SecretLevelId))
                    {
                        drpSecretLevel.SelectedValue = costReport.SecretLevelId;
                    }
                    if (!string.IsNullOrEmpty(costReport.UnitId))
                    {
                        drpUnit.SelectedValue = costReport.UnitId;
                    }
                    if (!string.IsNullOrEmpty(costReport.ConfirmFormIds))
                    {
                        string[] strs = costReport.ConfirmFormIds.Split(',');
                        List list = new List();
                        foreach (var item in strs)
                        {
                            Model.CQMS_ConfirmForm confirmForm = BLL.ConfirmFormService.GetConfirmFormByConfirmFormId(item);
                            if (confirmForm != null)
                            {
                                list.Add(confirmForm);
                            }
                        }
                        drpConfirmFormIds.DataValueField = "ConfirmFormId";
                        drpConfirmFormIds.DataTextField = "ConfirmFormCode";
                        drpConfirmFormIds.DataSource = list;
                        drpConfirmFormIds.DataBind();
                        this.drpConfirmFormIds.SelectedValueArray = strs;
                    }
                    this.txtContractNo.Text = costReport.ContractNo;
                    this.txtContractContent.Text = costReport.ContractContent;
                    if (costReport.CompileDate != null)
                    {
                        txtCompileDate.Text = string.Format("{0:yyyy-MM-dd}", costReport.CompileDate);
                    }
                    if (costReport.Edition != null)
                    {
                        txtEdition.Text = costReport.Edition.ToString();
                    }
                    this.Grid1.DataSource = BLL.CostReportDetailService.GetViewLists(CostReportId);
                    this.Grid1.DataBind();
                    bindApprove();
                    if (costReport.State == Const.CostReport_Compile)
                    {
                        agree.Hidden = true;
                        options.Hidden = true;
                        optio.Hidden = true;
                        CostReportService.Init(drpHandleType, Const.CostReport_Compile, false);
                        UserService.InitUserProjectIdUnitTypeDropDownList(drpHandleMan, CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_1, false);
                    }
                    else if (costReport.State == Const.CostReport_ReCompile)
                    {
                        this.trNext.Hidden = true;
                        agree.Hidden = true;
                        options.Hidden = true;
                        optio.Hidden = true;
                        if (costReport.PlanCost != null)
                        {
                            this.txtPlanCost.Text = costReport.PlanCost.ToString();
                        }
                    }
                    else if (costReport.State == Const.CostReport_Audit1)
                    {
                        NoEdit();
                        this.trNext.Hidden = true;
                        this.trPlanCost.Hidden = false;
                        if (costReport.PlanCost != null)
                        {
                            this.txtPlanCost.Text = costReport.PlanCost.ToString();
                        }
                    }
                    else if (costReport.State == Const.CostReport_Audit2 || costReport.State == Const.CostReport_Audit3)
                    {
                        NoEdit();
                        this.trNext.Hidden = true;
                        this.trPlanCost.Hidden = false;
                        if (costReport.PlanCost != null)
                        {
                            this.txtPlanCost.Text = costReport.PlanCost.ToString();
                        }
                        this.txtPlanCost.Enabled = false;
                        this.trAuditCost.Hidden = false;
                        if (costReport.AuditCost != null)
                        {
                            this.txtAuditCost.Text = costReport.AuditCost.ToString();
                        }
                    }
                    else if (costReport.State == Const.CostReport_Audit4)
                    {
                        NoEdit();
                        this.trNext.Hidden = true;
                        this.trPlanCost.Hidden = false;
                        if (costReport.PlanCost != null)
                        {
                            this.txtPlanCost.Text = costReport.PlanCost.ToString();
                        }
                        this.txtPlanCost.Enabled = false;
                        this.trAuditCost.Hidden = false;
                        if (costReport.AuditCost != null)
                        {
                            this.txtAuditCost.Text = costReport.AuditCost.ToString();
                        }
                        this.txtAuditCost.Enabled = false;
                        this.trRealCost.Hidden = false;
                        if (costReport.RealCost != null)
                        {
                            this.txtRealCost.Text = costReport.RealCost.ToString();
                        }
                    }
                }
                else
                {
                    agree.Hidden = true;
                    txtEdition.Text = "0";
                    options.Hidden = true;
                    optio.Hidden = true;
                    plApprove2.Hidden = true;
                    CostReportService.Init(drpHandleType, Const.CostReport_Compile, false);
                    //UserService.InitUserProjectIdUnitTypeDropDownList(drpHandleMan, CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_1, false);
                    //txtCostReportCode.Text = SQLHelper.RunProcNewId2("SpGetNewCode3ByProjectId", "dbo.CQMS_CostReport", "Code", CurrUser.LoginProjectId);
                }
            }
            else
            {
                if (GetRequestEventArgument() == "UPDATE_SUMMARY")
                {
                    // 页面要求重新计算合计行的值
                    OutputSummaryData();
                }
            }
        }
        private void NoEdit()
        {
            txtCostReportCode.Enabled = false;
            drpSecretLevel.Enabled = false;
            drpUnit.Enabled = false;
            txtContractNo.Enabled = false;
            drpConfirmFormIds.Enabled = false;
            txtContractContent.Enabled = false;
            txtCompileDate.Enabled = false;
            txtEdition.Enabled = false;
            ContactImg = -1;
        }
        #region 计算合计
        /// 
        /// 计算合计
        /// 
        private void OutputSummaryData()
        {
            decimal totalPlanCost = 0;
            int i = 0;
            JArray mergedData = Grid1.GetMergedData();
            if (mergedData.Count > 0)
            {
                foreach (JObject mergedRow in mergedData)
                {
                    JObject values = mergedRow.Value("values");
                    if (!string.IsNullOrEmpty(values.Value("RealCost")))
                    {
                        totalPlanCost += Funs.GetNewDecimalOrZero(values.Value("RealCost"));
                    }
                    else
                    {
                        totalPlanCost += 0;
                    }
                }
                this.txtPlanCost.Text = totalPlanCost.ToString();
            }
        }
        #endregion
        /// 
        /// 审批列表
        /// 
        private void bindApprove()
        {
            var list = CostReportApproveService.getListData(CostReportId);
            gvApprove.DataSource = list;
            gvApprove.DataBind();
        }
        public string man(Object man)
        {
            string appman = string.Empty;
            if (UserService.GetUserByUserId(man.ToString()) != null)
            {
                appman = UserService.GetUserByUserId(man.ToString()).UserName;
            }
            return appman;
        }
        #region 保存/提交
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //validate(Const.BtnSave, "save");
            if (CommonService.GetAllButtonPowerList(CurrUser.LoginProjectId, CurrUser.UserId, Const.CostReportMenuId, Const.BtnSave))
            {
                SaveCostReport("save");
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                Alert.ShowInTop("保存成功!", MessageBoxIcon.Success);
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            validate(Const.BtnSubmit, "submmit");
        }
        /// 
        /// 保存验证
        /// 
        /// 
        /// 
        public void validate(string buttonName, string tip)
        {
            if (CommonService.GetAllButtonPowerList(CurrUser.LoginProjectId, CurrUser.UserId, Const.CostReportMenuId, buttonName))
            {
                string err = string.Empty;
                if (this.drpSecretLevel.SelectedValue == BLL.Const._Null)
                {
                    err += "请选择密级,";
                }
                if (this.drpUnit.SelectedValue == BLL.Const._Null)
                {
                    err += "请选择分包单位,";
                }
                if (this.trPlanCost.Hidden == false && string.IsNullOrEmpty(this.txtPlanCost.Text.Trim()) && this.rblIsAgree.SelectedValue == "true")
                {
                    err += "请输入申报签证费用,";
                }
                if (this.trAuditCost.Hidden == false && string.IsNullOrEmpty(this.txtAuditCost.Text.Trim()) && this.rblIsAgree.SelectedValue == "true")
                {
                    err += "请输入确认签证费用,";
                }
                if (this.trRealCost.Hidden == false && string.IsNullOrEmpty(this.txtRealCost.Text.Trim()) && this.rblIsAgree.SelectedValue == "true")
                {
                    err += "请输入同意签证费用,";
                }
                //if (!AttachFileService.Getfile(HFCostReportId.Text, Const.CostReportMenuId))
                //{
                //    err += "请上传附件,";
                //}
                //if (trOne.Nodes[0].Nodes.Count == 0 && trTwo.Nodes.Count == 0 && trThree.Nodes.Count == 0 &&
                //    trFour.Nodes.Count == 0 && trFive.Nodes.Count == 0 && trSixe.Nodes.Count == 0)
                //{
                //    err += "请选择总包会签人员,";
                //}
                if (!string.IsNullOrWhiteSpace(err))
                {
                    err = err.Substring(0, err.LastIndexOf(","));
                    err += "!";
                }
                if (!string.IsNullOrWhiteSpace(err))
                {
                    Alert.ShowInTop(err, MessageBoxIcon.Warning);
                    return;
                }
                if (!string.IsNullOrWhiteSpace(CostReportId))
                {//更新时操作
                    if (tip == "save")
                    {
                        EditConstructSol("save");
                    }
                    else
                    {
                        EditConstructSol("submit");
                    }
                }
                else
                {
                    if (tip == "save")
                    {
                        SaveCostReport("save");
                    }
                    else
                    {
                        SaveCostReport("submit");
                    }
                    //添加时操作           
                }
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                if (tip == "save")
                {
                    tip = "保存成功!";
                }
                else
                {
                    tip = "提交成功!";
                }
                Alert.ShowInTop(tip, MessageBoxIcon.Success);
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        /// 
        /// 编辑时候保存
        /// 
        private void EditConstructSol(string saveType)
        {
            Model.CQMS_CostReport costReport = new Model.CQMS_CostReport();
            costReport.CostReportCode = txtCostReportCode.Text.Trim();
            costReport.SecretLevelId = this.drpSecretLevel.SelectedValue;
            costReport.ProjectId = CurrUser.LoginProjectId;
            costReport.UnitId = this.drpUnit.SelectedValue;
            costReport.ContractNo = this.txtContractNo.Text.Trim();
            costReport.ContractContent = this.txtContractContent.Text.Trim();
            if (!string.IsNullOrEmpty(this.drpConfirmFormIds.SelectedValue))
            {
                string str = string.Empty;
                foreach (var item in this.drpConfirmFormIds.SelectedValueArray)
                {
                    str += item + ",";
                }
                if (!string.IsNullOrEmpty(str))
                {
                    str = str.Substring(0, str.Length - 1);
                }
                costReport.ConfirmFormIds = str;
            }
            int edtion = Convert.ToInt32(txtEdition.Text);
            costReport.Edition = edtion;
            if (!string.IsNullOrEmpty(txtCompileDate.Text.Trim()))
            {
                costReport.CompileDate = Convert.ToDateTime(txtCompileDate.Text.Trim());
            }
            if (!string.IsNullOrEmpty(CostReportId))
            {
                costReport.CostReportId = CostReportId;
                Model.CQMS_CostReport costReport1 = CostReportService.GetCostReportByCostReportId(CostReportId);
                BLL.CostReportDetailService.DeleteCostReportDetailByCostReportId(costReport.CostReportId);
                var details = GetDetails();
                foreach (var item in details)
                {
                    item.CostReportId = costReport.CostReportId;
                    BLL.CostReportDetailService.AddCostReportDetail(item);
                }
                if (saveType == "submit")
                {
                    Model.CQMS_CostReportApprove approve = CostReportApproveService.GetConstructSoluAppByApproveMan(CostReportId, CurrUser.UserId, Convert.ToInt32(costReport1.Edition));
                    if (approve != null)
                    {
                        approve.IsAgree = Convert.ToBoolean(this.rblIsAgree.SelectedValue);
                        approve.ApproveIdea = this.txtOptions.Text.Trim();
                        approve.ApproveDate = DateTime.Now;
                        CostReportApproveService.UpdateCostReportApprove(approve);
                    }
                    if (costReport1.State == BLL.Const.CostReport_Compile)
                    {
                        costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                        costReport.State = this.drpHandleType.SelectedValue;
                        Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                        reApprove.CostReportId = costReport.CostReportId;
                        reApprove.ApproveMan = this.drpHandleMan.SelectedValue;
                        reApprove.ApproveType = this.drpHandleType.SelectedValue;
                        reApprove.Edition = edtion;
                        CostReportApproveService.AddCostReportApprove(reApprove);
                    }
                    else if (costReport1.State == BLL.Const.CostReport_ReCompile)
                    {
                        //获取上个版次不同意的审批记录
                        List lastNotAggreeApproves = BLL.CostReportApproveService.GetNotAggreeApprovesByCostReportIdAndEdtion(CostReportId, costReport1.Edition.Value - 1);
                        costReport.PlanCost = costReport1.PlanCost;
                        costReport.AuditCost = costReport1.AuditCost;
                        costReport.RealCost = costReport1.RealCost;
                        costReport.State = lastNotAggreeApproves[0].ApproveType;
                        foreach (var item in lastNotAggreeApproves)
                        {
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            reApprove.ApproveMan = item.ApproveMan;
                            reApprove.ApproveType = item.ApproveType;
                            reApprove.Edition = edtion;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                    }
                    else if (costReport1.State == BLL.Const.CostReport_Audit1)
                    {
                        if (this.rblIsAgree.SelectedValue == "true")    //同意
                        {
                            costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            costReport.State = BLL.Const.CostReport_Audit2;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            var users = (from x in Funs.DB.Sys_User
                                         join y in Funs.DB.Project_ProjectUnit
                                         on x.UnitId equals y.UnitId
                                         join p in Funs.DB.Project_ProjectUser
                                         on x.UserId equals p.UserId
                                         where p.RoleId.Contains(Const.ControlEngineer)
                                         && y.UnitType == Const.ProjectUnitType_1 && p.ProjectId == CurrUser.LoginProjectId && y.ProjectId == CurrUser.LoginProjectId
                                         select x).ToList();
                            if (users.Count() > 0)
                            {
                                reApprove.ApproveMan = users[0].UserId;
                            }
                            reApprove.ApproveType = BLL.Const.CostReport_Audit2;
                            reApprove.Edition = edtion;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                        else   //不同意
                        {
                            if (!string.IsNullOrEmpty(this.txtPlanCost.Text.Trim()))
                            {
                                costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            }
                            costReport.State = Const.Statement_ReCompile;
                            costReport.Edition = edtion + 1;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            reApprove.ApproveMan = costReport1.CompileMan;
                            reApprove.ApproveType = Const.CostReport_ReCompile;
                            reApprove.Edition = edtion + 1;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                    }
                    else if (costReport1.State == BLL.Const.CostReport_Audit2)
                    {
                        if (this.rblIsAgree.SelectedValue == "true")    //同意
                        {
                            costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            costReport.AuditCost = Funs.GetNewDecimalOrZero(this.txtAuditCost.Text.Trim());
                            costReport.State = BLL.Const.CostReport_Audit3;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            var users = (from x in Funs.DB.Sys_User
                                         join y in Funs.DB.Project_ProjectUnit
                                         on x.UnitId equals y.UnitId
                                         join p in Funs.DB.Project_ProjectUser
                                         on x.UserId equals p.UserId
                                         where p.RoleId.Contains(Const.ControlManager)
                                         && y.UnitType == Const.ProjectUnitType_1 && p.ProjectId == CurrUser.LoginProjectId && y.ProjectId == CurrUser.LoginProjectId
                                         select x).ToList();
                            if (users.Count() > 0)
                            {
                                reApprove.ApproveMan = users[0].UserId;
                            }
                            reApprove.ApproveType = BLL.Const.CostReport_Audit3;
                            reApprove.Edition = edtion;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                        else   //不同意
                        {
                            if (!string.IsNullOrEmpty(this.txtPlanCost.Text.Trim()))
                            {
                                costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            }
                            if (!string.IsNullOrEmpty(this.txtAuditCost.Text.Trim()))
                            {
                                costReport.AuditCost = Funs.GetNewDecimalOrZero(this.txtAuditCost.Text.Trim());
                            }
                            costReport.State = Const.Statement_ReCompile;
                            costReport.Edition = edtion + 1;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            reApprove.ApproveMan = costReport1.CompileMan;
                            reApprove.ApproveType = Const.CostReport_ReCompile;
                            reApprove.Edition = edtion + 1;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                    }
                    else if (costReport1.State == BLL.Const.CostReport_Audit3)
                    {
                        if (this.rblIsAgree.SelectedValue == "true")    //同意
                        {
                            costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            costReport.AuditCost = Funs.GetNewDecimalOrZero(this.txtAuditCost.Text.Trim());
                            costReport.State = BLL.Const.CostReport_Audit4;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            var users = (from x in Funs.DB.Sys_User
                                         join y in Funs.DB.Project_ProjectUnit
                                         on x.UnitId equals y.UnitId
                                         join p in Funs.DB.Project_ProjectUser
                                         on x.UserId equals p.UserId
                                         where p.RoleId.Contains(Const.ProjectManager)
                                         && y.UnitType == Const.ProjectUnitType_1 && p.ProjectId == CurrUser.LoginProjectId && y.ProjectId == CurrUser.LoginProjectId
                                         select x).ToList();
                            if (users.Count() > 0)
                            {
                                reApprove.ApproveMan = users[0].UserId;
                            }
                            reApprove.ApproveType = BLL.Const.CostReport_Audit4;
                            reApprove.Edition = edtion;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                        else   //不同意
                        {
                            if (!string.IsNullOrEmpty(this.txtPlanCost.Text.Trim()))
                            {
                                costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            }
                            if (!string.IsNullOrEmpty(this.txtAuditCost.Text.Trim()))
                            {
                                costReport.AuditCost = Funs.GetNewDecimalOrZero(this.txtAuditCost.Text.Trim());
                            }
                            costReport.State = Const.Statement_ReCompile;
                            costReport.Edition = edtion + 1;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            reApprove.ApproveMan = costReport1.CompileMan;
                            reApprove.ApproveType = Const.CostReport_ReCompile;
                            reApprove.Edition = edtion + 1;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                    }
                    else if (costReport1.State == BLL.Const.CostReport_Audit4)
                    {
                        if (this.rblIsAgree.SelectedValue == "true")    //同意
                        {
                            costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            costReport.AuditCost = Funs.GetNewDecimalOrZero(this.txtAuditCost.Text.Trim());
                            costReport.RealCost = Funs.GetNewDecimalOrZero(this.txtRealCost.Text.Trim());
                            costReport.State = BLL.Const.CostReport_Complete;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            reApprove.ApproveType = BLL.Const.CostReport_Complete;
                            reApprove.Edition = edtion;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                        else   //不同意
                        {
                            if (!string.IsNullOrEmpty(this.txtPlanCost.Text.Trim()))
                            {
                                costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
                            }
                            if (!string.IsNullOrEmpty(this.txtAuditCost.Text.Trim()))
                            {
                                costReport.AuditCost = Funs.GetNewDecimalOrZero(this.txtAuditCost.Text.Trim());
                            }
                            if (!string.IsNullOrEmpty(this.txtRealCost.Text.Trim()))
                            {
                                costReport.RealCost = Funs.GetNewDecimalOrZero(this.txtRealCost.Text.Trim());
                            }
                            costReport.State = Const.Statement_ReCompile;
                            costReport.Edition = edtion + 1;
                            Model.CQMS_CostReportApprove reApprove = new Model.CQMS_CostReportApprove();
                            reApprove.CostReportId = costReport.CostReportId;
                            reApprove.ApproveMan = costReport1.CompileMan;
                            reApprove.ApproveType = Const.CostReport_ReCompile;
                            reApprove.Edition = edtion + 1;
                            CostReportApproveService.AddCostReportApprove(reApprove);
                        }
                    }
                    CostReportService.UpdateCostReport(costReport);
                }
                LogService.AddSys_Log(CurrUser, costReport.CostReportCode, CostReportId, Const.CostReportMenuId, "修改工程签证费用报审表");
            }
        }
        #endregion
        #region 添加时候的保存
        /// 
        /// 保存方案审查
        /// 
        /// 保存类型
        private void SaveCostReport(string saveType)
        {
            //if (tvHSE.CheckedNodes.Count == 0 || (tvHSE.CheckedNodes.Count > 0 && tvHSE.CheckedNodes[0].Value == "0"))
            //{
            //    ScriptManager.RegisterStartupScript(this, typeof(string), "_alert", "alert('请选择HSE会签人员!')", true);
            //    return;
            //}
            Model.CQMS_CostReport costReport = new Model.CQMS_CostReport();
            costReport.CostReportCode = txtCostReportCode.Text.Trim();
            costReport.SecretLevelId = this.drpSecretLevel.SelectedValue;
            costReport.ProjectId = CurrUser.LoginProjectId;
            costReport.UnitId = this.drpUnit.SelectedValue;
            costReport.ContractNo = this.txtContractNo.Text.Trim();
            costReport.ContractContent = this.txtContractContent.Text.Trim();
            if (!string.IsNullOrEmpty(this.drpConfirmFormIds.SelectedValue))
            {
                string str = string.Empty;
                foreach (var item in this.drpConfirmFormIds.SelectedValueArray)
                {
                    str += item + ",";
                }
                if (!string.IsNullOrEmpty(str))
                {
                    str = str.Substring(0, str.Length - 1);
                }
                costReport.ConfirmFormIds = str;
            }
            costReport.PlanCost = Funs.GetNewDecimalOrZero(this.txtPlanCost.Text.Trim());
            int edtion = Convert.ToInt32(txtEdition.Text);
            costReport.Edition = edtion;
            if (!string.IsNullOrEmpty(txtCompileDate.Text.Trim()))
            {
                costReport.CompileDate = Convert.ToDateTime(txtCompileDate.Text.Trim());
            }
            if (saveType == "submit")
            {
                costReport.State = Const.CostReport_Audit1;
            }
            else
            {
                costReport.State = Const.CostReport_Compile;
            }
            if (!string.IsNullOrEmpty(HFCostReportId.Text))
            {
                costReport.CostReportId = HFCostReportId.Text;
            }
            else
            {
                costReport.CostReportId = SQLHelper.GetNewID(typeof(Model.CQMS_CostReport));
            }
            costReport.CompileMan = CurrUser.UserId;
            costReport.Edition = Convert.ToInt32(txtEdition.Text);
            //if (!string.IsNullOrEmpty(HFCostReportId.Text))
            //{
            //    CostReportService.UpdateCostReport(costReport);
            //}
            //else
            //{
                CostReportService.AddCostReport(costReport);
            //}
            if (saveType == "submit")
            {
                Model.CQMS_CostReportApprove approve1 = new Model.CQMS_CostReportApprove();
                approve1.CostReportId = costReport.CostReportId;
                approve1.ApproveDate = DateTime.Now;
                approve1.ApproveMan = this.CurrUser.UserId;
                approve1.ApproveType = Const.CostReport_Compile;
                approve1.Edition = Convert.ToInt32(txtEdition.Text);
                CostReportApproveService.AddCostReportApprove(approve1);
                Model.CQMS_CostReportApprove approve2 = new Model.CQMS_CostReportApprove();
                approve2.CostReportId = costReport.CostReportId;
                approve2.ApproveMan = this.drpHandleMan.SelectedValue;
                approve2.ApproveType = Const.CostReport_Audit1;
                approve2.Edition = Convert.ToInt32(txtEdition.Text);
                CostReportApproveService.AddCostReportApprove(approve2);
            }
            else
            {
                Model.CQMS_CostReportApprove approve1 = new Model.CQMS_CostReportApprove();
                approve1.CostReportId = costReport.CostReportId;
                approve1.ApproveMan = this.CurrUser.UserId;
                approve1.ApproveType = Const.CostReport_Compile;
                approve1.Edition = Convert.ToInt32(txtEdition.Text);
                CostReportApproveService.AddCostReportApprove(approve1);
            }
            BLL.CostReportDetailService.DeleteCostReportDetailByCostReportId(costReport.CostReportId);
            var details = GetDetails();
            foreach (var item in details)
            {
                item.CostReportId = costReport.CostReportId;
                BLL.CostReportDetailService.AddCostReportDetail(item);
            }
            LogService.AddSys_Log(CurrUser, costReport.CostReportCode, CostReportId, Const.CostReportMenuId, "添加工程签证费用报审表");
            //}
            //提交
            //if (saveType == "submit")
            //{
            //    countersign(costReport.CostReportId);
            //}
            //LogService.AddSys_Log(CurrUser, costReport.CostReportCode, CostReportId, Const.CostReportMenuId, "编制工程签证费用报审表");
        }
        #endregion
        protected void imgBtnFile_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(HFCostReportId.Text))   //新增记录
            {
                HFCostReportId.Text = SQLHelper.GetNewID(typeof(Model.CQMS_CostReport));
            }
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(
            String.Format("../../AttachFile/webuploader.aspx?type={0}&toKeyId={1}&path=FileUpload/CostReport&menuId={2}",
            ContactImg, HFCostReportId.Text, Const.CostReportMenuId)));
        }
        protected void btnapprove_Click(object sender, EventArgs e)
        {
            //HFCostReportId.Text
            var approve = CostReportApproveService.GetCostReportApproveByApproveMan(HFCostReportId.Text, CurrUser.UserId);
            if (approve != null)
            {
                var approveId = approve.CostReportApproveId;
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(
                String.Format("../../AttachFile/webuploader.aspx?type={0}&toKeyId={1}&path=FileUpload/CostReport&menuId={2}",
                0, approveId, Const.CostReportMenuId)));
            }
        }
        protected void gvApprove_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] keys = gvApprove.DataKeys[e.RowIndex];
            string fileId = string.Empty;
            if (keys == null)
            {
                return;
            }
            else
            {
                fileId = keys[0].ToString();
            }
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(
                 String.Format("../../AttachFile/webuploader.aspx?type={0}&toKeyId={1}&path=FileUpload/CostReport&menuId={2}",
                 -1, fileId, Const.CostReportMenuId)));
        }
        protected void drpHandleType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.drpHandleType.SelectedValue == BLL.Const.CostReport_Complete) //审批完成
            {
                this.drpHandleMan.Enabled = false;
                this.drpHandleMan.Required = false;
                this.drpHandleMan.Items.Clear();
            }
            else
            {
                this.drpHandleMan.Enabled = true;
                this.drpHandleMan.Required = true;
                UserService.InitUserProjectIdUnitTypeDropDownList(drpHandleMan, CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_1, false);
            }
        }
        protected void rblIsAgree_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.rblIsAgree.SelectedValue == "false")
            {
                this.drpHandleType.SelectedValue = BLL.Const.CostReport_ReCompile;
                this.drpHandleMan.Enabled = true;
                this.drpHandleMan.Required = true;
                Model.CQMS_CostReportApprove approve = BLL.CostReportApproveService.GetCompile(this.CostReportId);
                if (approve != null)
                {
                    List list = new List();
                    Model.Sys_User compileMan = BLL.UserService.GetUserByUserId(approve.ApproveMan);
                    list.Add(compileMan);
                    drpHandleMan.DataValueField = "UserId";
                    drpHandleMan.DataTextField = "UserName";
                    this.drpHandleMan.DataSource = list;
                    this.drpHandleMan.DataBind();
                }
            }
            else
            {
                this.drpHandleType.SelectedValue = BLL.Const.CostReport_Complete;
                this.drpHandleMan.Enabled = false;
                this.drpHandleMan.Required = false;
                this.drpHandleMan.Items.Clear();
            }
        }
        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                UserService.InitUserProjectIdUnitIdDropDownList(drpHandleMan, CurrUser.LoginProjectId, this.drpUnit.SelectedValue, false);
                ConfirmFormService.InitConfirmFormList2(drpConfirmFormIds, this.CurrUser.LoginProjectId, this.drpUnit.SelectedValue, false);
            }
            else
            {
                drpHandleMan.Items.Clear();
            }
        }
        protected void drpConfirmFormIds_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.drpConfirmFormIds.SelectedValue))
            {
                decimal d = 0;
                List details = new List();
                foreach (var item in this.drpConfirmFormIds.SelectedValueArray)
                {
                    Model.CQMS_ConfirmForm confirmForm = BLL.ConfirmFormService.GetConfirmFormByConfirmFormId(item);
                    Model.View_CQMS_CostReportDetail detail = new Model.View_CQMS_CostReportDetail();
                    detail.CostReportDetailId = SQLHelper.GetNewID();
                    detail.ConfirmFormId = item;
                    detail.ConfirmFormCode = confirmForm.ConfirmFormCode;
                    detail.TaskTheme = confirmForm.TaskTheme;
                    Model.CQMS_Statement statement = BLL.StatementService.GetStatementByConfirmFormId(item);
                    if (statement != null)
                    {
                        detail.PlanCost = statement.PlanCost;
                        detail.RealCost = statement.RealCost;
                        if (statement.RealCost != null)
                        {
                            d += statement.RealCost.Value;
                        }
                    }
                    details.Add(detail);
                }
                Grid1.DataSource = details;
                Grid1.DataBind();
                this.txtPlanCost.Text = d.ToString();
            }
            else
            {
                Grid1.DataSource = null;
                Grid1.DataBind();
                this.txtPlanCost.Text = string.Empty;
            }
        }
        /// 
        /// 检查并保存集合
        /// 
        private List GetDetails()
        {
            List details = new List();
            foreach (JObject mergedRow in Grid1.GetMergedData())
            {
                JObject values = mergedRow.Value("values");
                int i = mergedRow.Value("index");
                Model.CQMS_CostReportDetail detail = new Model.CQMS_CostReportDetail();
                detail.CostReportDetailId = this.Grid1.Rows[i].DataKeys[0].ToString();
                detail.ConfirmFormId = this.Grid1.Rows[i].RowID;
                detail.SortIndex = i;
                detail.PlanCost = Funs.GetNewDecimalOrZero(values.Value("PlanCost"));
                detail.RealCost = Funs.GetNewDecimalOrZero(values.Value("RealCost"));
                detail.Remark = values.Value("Remark");
                details.Add(detail);
            }
            return details;
        }
    }
}