protected void bt_AddProduct_Click(object sender, EventArgs e)
    {
        SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);
        int product = 0;
        if (int.TryParse(select_Product.SelectValue, out product) && product > 0)
        {
            PDT_Product pdt = new PDT_ProductBLL(product).Model;
            if (pdt == null) return;
            int quantity = int.Parse(tbx_Q1.Text) * pdt.ConvertFactor + int.Parse(tbx_Q2.Text);
            if (quantity == 0) return;
            SVM_InventoryDifferences_Detail _detail = bll.Items.FirstOrDefault(m => m.Product == product);
            if (_detail == null)
            {
                _detail = new SVM_InventoryDifferences_Detail();
                decimal factoryprice = 0, price = 0;
                PDT_ProductPriceBLL.GetPriceByClientAndType((int)ViewState["ClientID"], product, 2, out factoryprice, out price);
                _detail.FactoryPrice = factoryprice;
                _detail.Product = pdt.ID;
                _detail.Quantity = quantity;
                _detail.InventoryID = (int)ViewState["InventoryID"];
                bll.AddDetail(_detail);
            }
            else
            {
                _detail.Quantity = quantity;
                bll.UpdateDetail(_detail);
            }

            BindGrid();
        }
    }
 protected decimal GetCompute(string differenceID)
 {
     int ID = 0; decimal computeinventory = 0;
     if (int.TryParse(differenceID, out  ID))
     {
         SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL(ID);
         DataTable dtCompute = SVM_JXCSummaryBLL.GetSummaryListByClient(bll.Model.AccountMonth, bll.Model.AccountMonth, 1, bll.Model.Client, 1);
         computeinventory = dtCompute.Rows.Count > 0 ? Convert.ToDecimal(dtCompute.Rows[0]["ComputInventory"]) : 0;
         return computeinventory;
     }
     return computeinventory;
 }
    protected decimal GetCompute(string differenceID)
    {
        int ID = 0; decimal computeinventory = 0;

        if (int.TryParse(differenceID, out ID))
        {
            SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL(ID);
            DataTable dtCompute             = SVM_JXCSummaryBLL.GetSummaryListByClient(bll.Model.AccountMonth, bll.Model.AccountMonth, 1, bll.Model.Client, 1);
            computeinventory = dtCompute.Rows.Count > 0 ? Convert.ToDecimal(dtCompute.Rows[0]["ComputInventory"]) : 0;
            return(computeinventory);
        }
        return(computeinventory);
    }
    protected string GetDifferenceRate(string differenceID)
    {
        int ID = 0;

        if (int.TryParse(differenceID, out ID))
        {
            SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL(ID);
            decimal computeinventory        = GetCompute(differenceID);
            return(computeinventory == 0 ? "0" : (Math.Abs(bll.GetTotalFactoryPriceValue() - computeinventory) / computeinventory).ToString());
        }
        else
        {
            return("");
        }
    }
    protected void btn_Inventory_Click(object sender, EventArgs e)
    {
        #region 创建空的销量列表
        MCSSelectControl select_Client = (MCSSelectControl)UC_DetailView1.FindControl("SVM_InventoryDifferences_Client");
        DropDownList     ddl_Month     = (DropDownList)UC_DetailView1.FindControl("SVM_InventoryDifferences_AccountMonth");

        if (select_Client.SelectValue != "")
        {
            TextBox tbx_InventoryDate = (TextBox)UC_DetailView1.FindControl("SVM_InventoryDifferences_InventoryDate");
            if (tbx_InventoryDate != null)
            {
                int id = SVM_InventoryDifferencesBLL.InitProductList(int.Parse(ddl_Month.SelectedValue), int.Parse(select_Client.SelectValue), DateTime.Parse(tbx_InventoryDate.Text), (int)Session["UserID"], (bool)ViewState["IsCXP"]); //空的

                Response.Redirect("InventoryDifferenceInput.aspx?InventoryID=" + id.ToString() + "&Flag=1&IsCXP=" + ((bool)ViewState["IsCXP"] ? "1" : "0"));
            }
        }
        #endregion
    }
    protected void bt_Submit_Click(object sender, EventArgs e)
    {
        Save();

        if ((int)ViewState["InventoryID"] > 0)
        {
            SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);
            if (bll.Model["TaskID"] != "" && bll.Model["SubmitFlag"] == "1")
            {
                return;
            }
            CM_Client client = new CM_ClientBLL(bll.Model.Client).Model;

            NameValueCollection dataobjects = new NameValueCollection();
            dataobjects.Add("ID", bll.Model.ID.ToString());
            dataobjects.Add("AccountMonth", bll.Model.AccountMonth.ToString());
            dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());

            dataobjects.Add("ClientID", bll.Model.Client.ToString());
            dataobjects.Add("ClientFullName", client.FullName);
            dataobjects.Add("ClientType", client.ClientType.ToString());
            dataobjects.Add("DIClassify", client["DIClassify"]);
            dataobjects.Add("RTClassify", client["RTClassify"]);
            dataobjects.Add("RTChannel", client["RTChannel"]);

            dataobjects.Add("ComputeInventory", ((decimal)ViewState["ComputeInventory"]).ToString("0.0"));
            dataobjects.Add("TotalDiffValue", ((decimal)ViewState["TotalDiffValue"]).ToString("0.0"));
            dataobjects.Add("TotalAbsDiffValue", ((decimal)ViewState["TotalAbsDiffValue"]).ToString("0.0"));
            dataobjects.Add("AbsDiffRate", ((decimal)ViewState["AbsDiffRate"]).ToString("0.00") + "%");
            dataobjects.Add("ISCXP", bll.Model["IsCXP"]);

            int TaskID = EWF_TaskBLL.NewTask("SVM_InventoryDifferences_Flow", (int)Session["UserID"], "客户名称:" + client.FullName, "~/SubModule/SVM/InventoryDifferenceInput.aspx?InventoryID=" + ViewState["InventoryID"].ToString(), dataobjects);
            if (TaskID > 0)
            {
                bt_Submit.Visible       = false;
                bll.Model["TaskID"]     = TaskID.ToString();
                bll.Model["SubmitFlag"] = "1";
                bll.Update();
                new EWF_TaskBLL(TaskID).Start();        //直接启动流程
            }

            Response.Redirect("~/SubModule/EWF/TaskDetail.aspx?TaskID=" + TaskID.ToString());
        }
    }
    protected void Save()
    {
        SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);
        DropDownList ddl_Month          = (DropDownList)UC_DetailView1.FindControl("SVM_InventoryDifferences_AccountMonth");

        bll.Model.InventoryDate = DateTime.Now.Date;
        bll.Model.AccountMonth  = int.Parse(ddl_Month.SelectedValue);
        bll.Model["SubmitFlag"] = bll.Model["SubmitFlag"] == "" ? "2" : bll.Model["SubmitFlag"];
        bll.Update();
        foreach (GridViewRow gr in gv_List.Rows)
        {
            int id = (int)gv_List.DataKeys[gr.RowIndex][0];
            SVM_InventoryDifferences_Detail item = bll.GetDetailModel(id);

            item.Quantity = int.Parse(((TextBox)gr.FindControl("tbx_Quantity1")).Text) * new PDT_ProductBLL(item.Product).Model.ConvertFactor +
                            int.Parse(((TextBox)gr.FindControl("tbx_Quantity2")).Text);
            item.Remark    = ((TextBox)gr.FindControl("tbx_Remark")).Text;
            item.LotNumber = ((DropDownList)gr.FindControl("ddl_DifferencesReason")).SelectedValue;
            bll.UpdateDetail(item);
        }
    }
    protected void bt_AddProduct_Click(object sender, EventArgs e)
    {
        SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);
        int product = 0;

        if (int.TryParse(select_Product.SelectValue, out product) && product > 0)
        {
            PDT_Product pdt = new PDT_ProductBLL(product).Model;
            if (pdt == null)
            {
                return;
            }
            int quantity = int.Parse(tbx_Q1.Text) * pdt.ConvertFactor + int.Parse(tbx_Q2.Text);
            if (quantity == 0)
            {
                return;
            }
            SVM_InventoryDifferences_Detail _detail = bll.Items.FirstOrDefault(m => m.Product == product);
            if (_detail == null)
            {
                _detail = new SVM_InventoryDifferences_Detail();
                decimal factoryprice = 0, price = 0;
                PDT_ProductPriceBLL.GetPriceByClientAndType((int)ViewState["ClientID"], product, 2, out factoryprice, out price);
                _detail.FactoryPrice = factoryprice;
                _detail.Product      = pdt.ID;
                _detail.Quantity     = quantity;
                _detail.InventoryID  = (int)ViewState["InventoryID"];
                bll.AddDetail(_detail);
            }
            else
            {
                _detail.Quantity = quantity;
                bll.UpdateDetail(_detail);
            }

            BindGrid();
        }
    }
    private void ComputDiffInfo(SVM_InventoryDifferencesBLL bll)
    {
        #region 计算差异率
        decimal computeinventory = 0, totaldiffvalue = 0, totalabsdiffvalue = 0, absdiffrate = 0, lastdiffvalue = 0;

        DataTable dt = SVM_JXCSummaryBLL.GetSummaryListByClient(bll.Model.AccountMonth, bll.Model.AccountMonth, 1, bll.Model.Client, bll.Model["IsCXP"] == "2" ? 1 : 9);
        computeinventory = dt.Rows.Count > 0 ? Convert.ToDecimal(dt.Rows[0]["ComputInventory"]) : 0;
        totaldiffvalue   = bll.Items.Sum(p => p.FactoryPrice * p.Quantity);

        totalabsdiffvalue = bll.Items.Sum(p => p.FactoryPrice * Math.Abs(p.Quantity));
        absdiffrate       = computeinventory == 0 ? 0 : (totalabsdiffvalue / computeinventory) * 100;

        lastdiffvalue = bll.GetOPIInventory();

        ViewState["ComputeInventory"]  = computeinventory;
        ViewState["TotalDiffValue"]    = totaldiffvalue;
        ViewState["TotalAbsDiffValue"] = totalabsdiffvalue;  //绝对差异额
        ViewState["AbsDiffRate"]       = absdiffrate;        //绝对差异率
        ViewState["LastDiffValue"]     = lastdiffvalue;

        lb_DifferenceInfo.Text = string.Format("实时库存额:{0:0.00},上期(截止20日)库存额:{2:0.00},本次盈亏额:{1:0.00}", computeinventory, totaldiffvalue, lastdiffvalue);
        #endregion
    }
    private void BindData()
    {
        SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);

        ViewState["ClientID"] = bll.Model.Client;
        ViewState["IsCXP"]    = bll.Model["IsCXP"] == "1";

        UC_DetailView1.BindData(bll.Model);
        UC_DetailView1.SetControlsEnable(false);

        #region 根据状态设定界面控件可见属性
        if (bll.Model.ApproveFlag == 1 || bll.Model["SubmitFlag"] == "1")
        {
            gv_List.SetControlsEnable(false);
            cb_OnlyDisplayUnZero.Checked = true;
            bt_Save.Visible       = false;
            bt_Submit.Visible     = false;
            bt_Del.Visible        = false;
            tb_AddProduct.Visible = false;
            bt_Submit.Visible     = false;

            if (bll.Model.ApproveFlag == 1)
            {
                bt_Approve.Visible = false;                                 //未提交
            }
        }
        else
        {
            bt_Del.Visible     = (int)Session["UserID"] == bll.Model.InsertStaff;
            bt_Approve.Visible = false;
        }
        #endregion
        ComputDiffInfo(bll);

        BindGrid();
    }
    private void ComputDiffInfo(SVM_InventoryDifferencesBLL bll)
    {
        #region 计算差异率
        decimal computeinventory = 0, totaldiffvalue = 0, totalabsdiffvalue = 0, absdiffrate = 0,lastdiffvalue=0;

        DataTable dt = SVM_JXCSummaryBLL.GetSummaryListByClient(bll.Model.AccountMonth, bll.Model.AccountMonth, 1, bll.Model.Client, bll.Model["IsCXP"] == "2" ? 1 : 9);
        computeinventory = dt.Rows.Count > 0 ? Convert.ToDecimal(dt.Rows[0]["ComputInventory"]) : 0;
        totaldiffvalue = bll.Items.Sum(p => p.FactoryPrice * p.Quantity);

        totalabsdiffvalue = bll.Items.Sum(p => p.FactoryPrice * Math.Abs(p.Quantity));
        absdiffrate = computeinventory == 0 ? 0 : (totalabsdiffvalue / computeinventory) * 100;

        lastdiffvalue=bll.GetOPIInventory();

        ViewState["ComputeInventory"] = computeinventory;
        ViewState["TotalDiffValue"] = totaldiffvalue;
        ViewState["TotalAbsDiffValue"] = totalabsdiffvalue;  //绝对差异额
        ViewState["AbsDiffRate"] = absdiffrate;              //绝对差异率
        ViewState["LastDiffValue"] = lastdiffvalue;

        lb_DifferenceInfo.Text = string.Format("实时库存额:{0:0.00},上期(截止20日)库存额:{2:0.00},本次盈亏额:{1:0.00}", computeinventory, totaldiffvalue, lastdiffvalue);
        #endregion
    }
    private void BindData()
    {
        SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);

        ViewState["ClientID"] = bll.Model.Client;
        ViewState["IsCXP"] = bll.Model["IsCXP"] == "1";

        UC_DetailView1.BindData(bll.Model);
        UC_DetailView1.SetControlsEnable(false);

        #region 根据状态设定界面控件可见属性
        if (bll.Model.ApproveFlag == 1 || bll.Model["SubmitFlag"] == "1")
        {
            gv_List.SetControlsEnable(false);
            cb_OnlyDisplayUnZero.Checked = true;
            bt_Save.Visible = false;
            bt_Submit.Visible = false;
            bt_Del.Visible = false;
            tb_AddProduct.Visible = false;
            bt_Submit.Visible = false;

            if (bll.Model.ApproveFlag == 1) bt_Approve.Visible = false;     //未提交
        }
        else
        {
            bt_Del.Visible = (int)Session["UserID"] == bll.Model.InsertStaff;
            bt_Approve.Visible = false;
        }
        #endregion
        ComputDiffInfo(bll);

        BindGrid();
    }
    protected void Save()
    {
        SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);
        DropDownList ddl_Month = (DropDownList)UC_DetailView1.FindControl("SVM_InventoryDifferences_AccountMonth");
        bll.Model.InventoryDate = DateTime.Now.Date;
        bll.Model.AccountMonth = int.Parse(ddl_Month.SelectedValue);
        bll.Model["SubmitFlag"] = bll.Model["SubmitFlag"] == "" ? "2" : bll.Model["SubmitFlag"];
        bll.Update();
        foreach (GridViewRow gr in gv_List.Rows)
        {
            int id = (int)gv_List.DataKeys[gr.RowIndex][0];
            SVM_InventoryDifferences_Detail item = bll.GetDetailModel(id);

            item.Quantity = int.Parse(((TextBox)gr.FindControl("tbx_Quantity1")).Text) * new PDT_ProductBLL(item.Product).Model.ConvertFactor +
                int.Parse(((TextBox)gr.FindControl("tbx_Quantity2")).Text);
            item.Remark = ((TextBox)gr.FindControl("tbx_Remark")).Text;
            item.LotNumber = ((DropDownList)gr.FindControl("ddl_DifferencesReason")).SelectedValue;
            bll.UpdateDetail(item);
        }
    }
    protected void bt_Submit_Click(object sender, EventArgs e)
    {
        Save();

        if ((int)ViewState["InventoryID"] > 0)
        {
            SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL((int)ViewState["InventoryID"]);
            if (bll.Model["TaskID"] != "" && bll.Model["SubmitFlag"] == "1") return;
            CM_Client client = new CM_ClientBLL(bll.Model.Client).Model;

            NameValueCollection dataobjects = new NameValueCollection();
            dataobjects.Add("ID", bll.Model.ID.ToString());
            dataobjects.Add("AccountMonth", bll.Model.AccountMonth.ToString());
            dataobjects.Add("OrganizeCity", bll.Model.OrganizeCity.ToString());

            dataobjects.Add("ClientID", bll.Model.Client.ToString());
            dataobjects.Add("ClientFullName", client.FullName);
            dataobjects.Add("ClientType", client.ClientType.ToString());
            dataobjects.Add("DIClassify", client["DIClassify"]);
            dataobjects.Add("RTClassify", client["RTClassify"]);
            dataobjects.Add("RTChannel", client["RTChannel"]);

            dataobjects.Add("ComputeInventory", ((decimal)ViewState["ComputeInventory"]).ToString("0.0"));
            dataobjects.Add("TotalDiffValue", ((decimal)ViewState["TotalDiffValue"]).ToString("0.0"));
            dataobjects.Add("TotalAbsDiffValue", ((decimal)ViewState["TotalAbsDiffValue"]).ToString("0.0"));
            dataobjects.Add("AbsDiffRate", ((decimal)ViewState["AbsDiffRate"]).ToString("0.00")+"%");
            dataobjects.Add("ISCXP", bll.Model["IsCXP"]);

            int TaskID = EWF_TaskBLL.NewTask("SVM_InventoryDifferences_Flow", (int)Session["UserID"], "客户名称:" + client.FullName, "~/SubModule/SVM/InventoryDifferenceInput.aspx?InventoryID=" + ViewState["InventoryID"].ToString(), dataobjects);
            if (TaskID > 0)
            {
                bt_Submit.Visible = false;
                bll.Model["TaskID"] = TaskID.ToString();
                bll.Model["SubmitFlag"] = "1";
                bll.Update();
                new EWF_TaskBLL(TaskID).Start();        //直接启动流程
            }

            Response.Redirect("~/SubModule/EWF/TaskDetail.aspx?TaskID=" + TaskID.ToString());
        }
    }
 protected string GetDifferenceCost(string differenceID)
 {
     int ID = 0;
     if (int.TryParse(differenceID, out  ID))
     {
         SVM_InventoryDifferencesBLL bll = new SVM_InventoryDifferencesBLL(ID);
         decimal computeinventory = GetCompute(differenceID);
         return Math.Abs(bll.GetTotalFactoryPriceValue() - computeinventory).ToString();
     }
     else
     {
         return "";
     }
 }
    private void BindGrid()
    {
        if (tr_detail.Visible)
        {
            string condition = " 1=1 ";

            #region 组织查询条件
            //管理片区及所有下属管理片区
            if (select_Client.SelectValue == "" && tr_OrganizeCity.SelectValue != "1")
            {
                Addr_OrganizeCityBLL orgcity = new Addr_OrganizeCityBLL(int.Parse(tr_OrganizeCity.SelectValue));
                string orgcitys = orgcity.GetAllChildNodeIDs();
                if (orgcitys != "")
                {
                    orgcitys += ",";
                }
                orgcitys += tr_OrganizeCity.SelectValue;

                condition += " AND SVM_InventoryDifferences.OrganizeCity IN (" + orgcitys + ")";
            }

            if (ddl_IsCXP.SelectedValue != "0")
            {
                condition += " AND MCS_SYS.dbo.UF_Spilt2('MCS_SVM.dbo.SVM_InventoryDifferences',SVM_InventoryDifferences.ExtPropertys,'IsCXP')=" + ddl_IsCXP.SelectedValue;
            }
            //会计月条件
            condition += " AND SVM_InventoryDifferences.AccountMonth BETWEEN " + ddl_BeginMonth.SelectedValue + " AND " + ddl_EndMonth.SelectedValue;

            if (select_Client.SelectValue != "")
            {
                condition += " AND SVM_InventoryDifferences.Client = " + select_Client.SelectValue;
            }
            else
            {
                condition += " AND CM_Client.ClientType=" + ViewState["ClientType"].ToString();
                if ((int)ViewState["ClientType"] == 2 && ViewState["DIClassify"] != null)
                {
                    condition += " AND MCS_SYS.dbo.UF_Spilt(CM_Client.ExtPropertys,'|',7)='" + ViewState["DIClassify"].ToString() + "'";
                }
            }
            if (rbl_ApproveFlag.SelectedValue != "0")
            {
                condition += " AND SVM_InventoryDifferences.ApproveFlag=" + rbl_ApproveFlag.SelectedValue;
            }
            #endregion

            gv_List.ConditionString = condition;
            gv_List.BindGrid();
        }
        else
        {
            int organizecity = int.Parse(tr_OrganizeCity.SelectValue);
            int client       = select_Client.SelectValue == "" ? 0 : int.Parse(select_Client.SelectValue);
            if (organizecity == 0)
            {
                organizecity = 1;
            }
            DataTable dt = SVM_InventoryDifferencesBLL.GetSummary(organizecity, client, int.Parse(ddl_BeginMonth.SelectedValue), int.Parse(ddl_EndMonth.SelectedValue), int.Parse(ViewState["ClientType"].ToString()));
            DataRow   dr = dt.NewRow();
            dr["ProductCode"]       = "合计";
            dr["SumQuantity"]       = dt.Compute("Sum(SumQuantity)", "true");;
            dr["SumMoney"]          = dt.Compute("Sum(SumMoney)", "true");;
            dr["SumComput"]         = dt.Compute("Sum(SumComput)", "true");
            dr["SumDifferenceCost"] = dt.Compute("Sum(SumDifferenceCost)", "true");
            dt.Columns.Add(new DataColumn("SumDifferenceRate", Type.GetType("System.Decimal")));
            dt.Rows.Add(dr);
            if (dt.Rows.Count > 1)
            {
                foreach (DataRow row in dt.Rows)
                {
                    row["SumDifferenceRate"] = decimal.Parse(row["SumComput"].ToString()) == 0 ? "0" : (decimal.Parse(row["SumDifferenceCost"].ToString()) / decimal.Parse(row["SumComput"].ToString())).ToString("#,#.#");
                }
            }
            gv_Summary.DataSource = dt;
            gv_Summary.DataBind();
        }
    }