using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QMFrameWork.WebUI.Attribute;
using QMAPP.MD.Web.Models;
using QMFrameWork.Data;
using QMAPP.ServicesAgent;
using QMAPP.Entity;
using QMAPP.Common.Web.Controllers;
using QMFrameWork.WebUI.DataSource;
using QMFrameWork.Common.Serialization;
using QMAPP.MD.Entity;
using QMAPP.MD.Web;
namespace QMAPP.MD.Web.Controllers
{
    /// <summary>
    /// 模块名称:Bom信息
    /// 作    者:郭兆福
    /// 编写日期:2017年05月10日
    /// </summary>
    public class PbomController : QController
    {
        public string EmptyItemTitle = " ";

        #region 获取列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult List(bool? callBack)
        {
            PbomModel seachModel = new PbomModel();
            if (callBack == true)
                TryGetSelectBuffer<PbomModel>(out seachModel);
            seachModel.rownumbers = false;
            seachModel.url = "/Pbom/GetList";
            return View("PbomList", seachModel);
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="callBack">是否回调</param>
        /// <returns>列表</returns>
        [HandleException]
        public ActionResult GetList(bool? callBack)
        {
            PbomModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            Pbom condition = null;
            DataResult<DataPage> pageResult = new DataResult<DataPage>();
            try
            {
                //获取查询对象
                seachModel = GetModel<PbomModel>();
                #region 获取缓存值
                if (callBack != null)
                {
                    TryGetSelectBuffer<PbomModel>(out seachModel);
                }
                else
                {
                    //保存搜索条件
                    SetSelectBuffer<PbomModel>(seachModel);
                }
                #endregion
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<Pbom, PbomModel>(seachModel);
                #region wcf服务统一接口
                pageResult = wcfAgent.InvokeServiceFunction<DataResult<DataPage>>("PbomBLL_GetList", condition, page);
                if (pageResult.IsSuccess == false)
                {
                    SetMessage(pageResult.Msg);
                    return List(true);
                }
                DateGridResult<Pbom> result = new DateGridResult<Pbom>();
                result.Total = pageResult.Result.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<Pbom>>(pageResult.Result.Result.ToString());
                #endregion
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑载入
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult PbomEdit()
        {
            PbomModel model = new PbomModel();
            try
            {
                return View("PbomEdit", model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [HandleException]
        [ValidateInput(false)]
        public ActionResult Save(PbomModel saveModel)
        {
            Pbom Entity = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                Entity = CopyToModel<Pbom, PbomModel>(saveModel);
                if (string.IsNullOrEmpty(Entity.PID) == true)
                {
                    //新增
                    result = wcfAgent.InvokeServiceFunction<DataResult<int>>("PbomBLL_Insert", Entity);
                }
                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return View("PbomEdit", saveModel);
                }
                return this.GetJsViewResult(string.Format("parent.List(1);parent.showTitle('{0}');parent.closeAppWindow1();", AppResource.SaveMessge));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult PbomDelete()//ProductionLineModel saveMode
        {
            string selectKey = Request.Form["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("PbomBLL_Delete", selectKey);
                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return List(true);
                }
                SetMessage(AppResource.DeleteMessage);
                return List(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 配置Bom明细


        /// <summary>
        /// 加载列表
        /// </summary>
        /// <param name="callBack"></param>
        /// <returns></returns>
        public ActionResult PbomItem(bool? callBack)
        {
            PbomItemModel pblomItemModel = new PbomItemModel();
            string pbomCode = Request.Params["PBOM_CODE_PAR"];
            string materialCode = Request.Params["MATERIAL_CODE_PAR"];
            if (callBack == true)
                TryGetSelectBuffer<PbomItemModel>(out pblomItemModel);
     
            pblomItemModel.rownumbers = false;
            pblomItemModel.url = "/Pbom/PbomItemList?PBOM_CODE_PAR=" + pbomCode + "&MATERIAL_CODE_PAR=" + materialCode;
            pblomItemModel.PBOM_CODE = pbomCode;
            pblomItemModel.MATERIAL_CODE = materialCode;
       
            return View("PbomItemList", pblomItemModel);
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="callBack"></param>
        /// <returns></returns>
        public ActionResult PbomItemList(bool? callBack)
        {
            PbomItemModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            PbomItem condition = null;
            DataResult<DataPage> pageResult = new DataResult<DataPage>();
            string pbomCode = Request.Params["PBOM_CODE_PAR"];
            string materialCode = Request.Params["MATERIAL_CODE_PAR"];
            try
            {
                //获取查询对象
                seachModel = GetModel<PbomItemModel>();
                #region 获取缓存值
                if (callBack != null)
                {
                    TryGetSelectBuffer<PbomItemModel>(out seachModel);
                }
                else
                {
                    //保存搜索条件
                    SetSelectBuffer<PbomItemModel>(seachModel);
                }
                #endregion
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                if (string.IsNullOrEmpty(seachModel.PBOM_CODE))
                {
                    seachModel.PBOM_CODE = pbomCode;
                }
                condition = CopyToModel<PbomItem, PbomItemModel>(seachModel);
                #region wcf服务统一接口
                pageResult = wcfAgent.InvokeServiceFunction<DataResult<DataPage>>("PbomBLL_GetPbomItemList", condition, page);
                if (pageResult.IsSuccess == false)
                {
                    SetMessage(pageResult.Msg);
                    return PbomItem(true);
                }
                DateGridResult<PbomItem> result = new DateGridResult<PbomItem>();
                result.Total = pageResult.Result.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<PbomItem>>(pageResult.Result.Result.ToString());
                #endregion
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 配置Bom明细添加页面
        /// </summary>
        /// <returns></returns>
        public ActionResult PbomItemEdit()
        {
            PbomItemModel model = new PbomItemModel();
            model = GetModel<PbomItemModel>();
            model.PBOM_CODE = Request.Params["PBOM_CODE_PAR"];
            try
            {
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                DataResult<MaterialRoute> result = agent.InvokeServiceFunction<DataResult<MaterialRoute>>("PbomBLL_GetRouteByMaterialCode", new MaterialRoute() { MATERIAL_CODE = Request.Params["MATERIAL_CODE_PAR"] });
                model.ROUTE_CODE = result.Result.ROUTE_CODE;
               
                return View("PbomItemEdit", model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 保存Bom明细
        /// </summary>
        /// <returns></returns>
        public ActionResult PbomItemSave(PbomItemModel saveModel)
        {
            PbomItem entity = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            string pbomCode = Request.Params["PBOM_CODE"];
            try
            {
                entity = CopyToModel<PbomItem, PbomItemModel>(saveModel);
                if (string.IsNullOrEmpty(pbomCode))
                {
                    entity.PBOM_CODE = pbomCode;
                }
                if (string.IsNullOrEmpty(entity.PID) == true)
                {
                    //新增
                    result = wcfAgent.InvokeServiceFunction<DataResult<int>>("PbomBLL_PbomItemSave", entity);
                }
                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return View("PbomItemEdit", saveModel);
                }
                return this.GetJsViewResult(string.Format("parent.List(1);parent.showTitle('{0}');parent.closeAppWindow1();", AppResource.SaveMessge));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult PbomItemDelete()
        {
            string selectKey = Request.Form["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("PbomBLL_DeletePbomItem", selectKey);
                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return PbomItem(true);
                }
                SetMessage(AppResource.DeleteMessage);
                return PbomItem(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region PBOM树




        #region 获取数

        public ActionResult PbomItemTree()
        {
            PbomItemModel pblomItemModel = new PbomItemModel();
            string pbomCode = Request.Params["PBOM_CODE_PAR"];
            string routeCode = Request.Params["ROUTE_CODE"];
            var factory = Request.Params["FACTORY_CODE"];

            //pblomItemModel.rownumbers = false;
            //pblomItemModel.url = "/Pbom/PbomItemTreeList?PBOM_CODE_PAR=" + pbomCode + "&MATERIAL_CODE_PAR=" + materialCode;
            pblomItemModel.PBOM_CODE = pbomCode;
            pblomItemModel.ROUTE_CODE = routeCode;
            pblomItemModel.FACTORY_CODE = factory;

            //TryGetSelectBuffer<PbomItemModel>(out pblomItemModel);

            return View(pblomItemModel);
        }
        public ActionResult GetTreeData()
        {

            string pbomCode = Request.Params["PBOM_CODE"];
            string materialCode = Request.Params["MATERIAL_CODE_PAR"];

            List<TreeNodeResult> list = new List<TreeNodeResult>();
            PbomItem pi = new PbomItem();
            ////orga.UP_SQ_NUM = 0;
            //查询全部
            pi.UP_SQ_NUM = -1;
            pi.PBOM_CODE = pbomCode;
            QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
            List<PbomItem> pbomItems = agent.InvokeServiceFunction<List<PbomItem>>("PbomBLL_GetPbomItemAllList", pi);
            //查询根数据
            pi.UP_SQ_NUM = 0;
            List<PbomItem> pbomItemList = agent.InvokeServiceFunction<List<PbomItem>>("PbomBLL_GetPbomItemAllList", pi);


            //添加第一级机构
            //pbomItems = pbomItems.Where(p => string.IsNullOrWhiteSpace(p.OrgaParent)).ToList();

            //添加第一级机构
            foreach (PbomItem child in pbomItemList)
            {
                TreeNodeResult treenode = new TreeNodeResult();
                treenode.Tid = child.PID;
                treenode.Ttext = child.MATERIAL_NAME;
                treenode.Tcode = child.MATERIAL_CODE;
                //添加子机构
                this.BuildChildItemsPbom(child, treenode, pbomItems);
                list.Add(treenode);

                
            }

            return Content(TreeNodeResult.GetResultJosnS(list.ToArray()));
        }
        public ActionResult GetTreeGrid()
        {

            string pbomCode = Request.Params["PBOM_CODE"];
            string materialCode = Request.Params["MATERIAL_CODE_PAR"];

            PbomItem pi = new PbomItem();
            ////orga.UP_SQ_NUM = 0;
            //查询全部
            pi.UP_SQ_NUM = -1;
            pi.PBOM_CODE = pbomCode;
            QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
            List<PbomItem> pbomItems = agent.InvokeServiceFunction<List<PbomItem>>("PbomBLL_GetPbomItemAllList", pi);
            //查询根数据
            pi.UP_SQ_NUM = 0;
            List<PbomItem> pbomItemList = agent.InvokeServiceFunction<List<PbomItem>>("PbomBLL_GetPbomItemAllList", pi);

            List<PbomItemModel> trees = new List<PbomItemModel>();

            //添加第一级机构
            //pbomItems = pbomItems.Where(p => string.IsNullOrWhiteSpace(p.OrgaParent)).ToList();

            //添加第一级机构
            foreach (PbomItem child in pbomItemList)
            {

                var subnode = new PbomItemModel
                {
                    PID = child.PID,
                    Id = child.MATERIAL_CODE,
                    Text = child.MATERIAL_NAME,
                    PBOM_CODE = child.PBOM_CODE,
                    SEQ_NUM = child.SEQ_NUM,
                    UP_SQ_NUM = child.UP_SQ_NUM,
                    UNIT_SUM = child.UNIT_SUM,
                    children = new List<PbomItemModel>()
                };
                AppendTreeGrid(subnode, pbomItems);
                trees.Add(subnode);
                //if (subnode.children.Count > 0)
                //{
                //    trees.Add(subnode);
                //}
            }

            //return Content(TreeNodeResult.GetResultJosnS(list.ToArray()));
            return Json(trees, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 创建子组织机构
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="childPowers">子权限</param>
        private void BuildChildItemsPbom(PbomItem pbomItem, TreeNodeResult tnr, List<PbomItem> list)
        {
            //PbomItem corga = new PbomItem();
            //PbomItemModel corgaModel = new PbomItemModel();
            //corga.UP_SQ_NUM = orga.SEQ_NUM;

            List<PbomItem> subList = list.Where(p => p.PBOM_CODE == pbomItem.PBOM_CODE && p.UP_SQ_NUM == pbomItem.SEQ_NUM ).ToList();

            if (subList.Count > 0)
            {

                foreach (PbomItem child in subList)
                {
                    TreeNodeResult cTreeNode = new TreeNodeResult();
                    cTreeNode.Tid = child.PID;
                    cTreeNode.Ttext = child.MATERIAL_NAME;
                    cTreeNode.Tcode = child.MATERIAL_CODE;


                    //添加子菜单
                    this.BuildChildItemsPbom(child, cTreeNode, list);

                    tnr.AddchildNode(cTreeNode);

                }
            }

        }
        private void AppendTreeGrid(PbomItemModel pbomItem, List<PbomItem> list)
        {
            //PbomItem corga = new PbomItem();
            //PbomItemModel corgaModel = new PbomItemModel();
            //corga.UP_SQ_NUM = orga.SEQ_NUM;

            List<PbomItem> subList = list.Where(p => p.PBOM_CODE == pbomItem.PBOM_CODE && p.UP_SQ_NUM == pbomItem.SEQ_NUM).ToList();

            if (subList.Count > 0)
            {

                foreach (PbomItem child in subList)
                {
                    var subnode = new PbomItemModel
                    {
                        PID = child.PID,
                        Id = child.MATERIAL_CODE,
                        Text = child.MATERIAL_NAME,
                        PBOM_CODE = child.PBOM_CODE,
                        SEQ_NUM = child.SEQ_NUM,
                        UP_SQ_NUM = child.UP_SQ_NUM,
                        UNIT_SUM = child.UNIT_SUM,
                        children = new List<PbomItemModel>()
                    };
                    AppendTreeGrid(subnode, list);

                    pbomItem.children.Add(subnode);

                }
            }

        }


        #endregion




        #region 编辑

        /// <summary>
        /// 编辑载入
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult PbomItemTreeEdit()
        {
            PbomItemModel model = new PbomItemModel();
            string PID = Request.Params["PID"];
            //0 :初始化(第一条添加) 1 :树已经存在添加 2 :修改
            string isEdit = Request.Params["isEdit"];
            string ROUTE_CODE = Request.Params["ROUTE_CODE"];
            PbomItem pi = new PbomItem();
            ServiceAgent agent = this.GetServiceAgent();
            try
            {
                switch (isEdit)
                {
                    case "0":
                        model.PBOM_CODE = PID;
                        model.MATERIAL_CODE = null;
                        model.GMP = null;
                        model.UNIT_SUM = 1;
                        break;
                    case "1":
                        pi.PID = PID;
                        var pbomItem1 = agent.InvokeServiceFunction<PbomItem>("PbomBLL_GetPbomItemOne", pi);
                        if (pbomItem1 != null)
                        {
                            model = CopyToModel<PbomItemModel, PbomItem>(pbomItem1);
                        }
                        model.MATERIAL_CODE = null;
                        model.GMP = null;
                        model.UNIT_SUM = 1;
                        break;
                    case "2":
                        pi.PID = PID;
                        var pbomItem2 = agent.InvokeServiceFunction<PbomItem>("PbomBLL_GetPbomItemOne", pi);
                        if (pbomItem2 != null)
                        {
                            model = CopyToModel<PbomItemModel, PbomItem>(pbomItem2);
                        }
                        break;
                }
                model.isEdit = isEdit;
                model.ROUTE_CODE = ROUTE_CODE;

                return View(model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




        #endregion

        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns>处理结果</returns>        
        [HttpPost]
        [HandleException]
        public ActionResult PbomItemTreeSave(PbomItemModel saveModel)
        {
            PbomItem pbom = null;
            try
            {
                pbom = CopyToModel<PbomItem, PbomItemModel>(saveModel);



                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();


                int maxSeqNum = agent.InvokeServiceFunction<int>("PbomBLL_GetMaxSeqNum", pbom);

                switch (saveModel.isEdit)
                {
                    case "0":
                        pbom.UP_SQ_NUM = 0;
                        //pbom.SEQ_NUM = 1;
                        pbom.SEQ_NUM = (maxSeqNum + 1);
                        //新增
                        agent.InvokeServiceFunction("PbomBLL_InsertPbomItem", pbom);
                        break;
                    case "1":
                        pbom.UP_SQ_NUM = pbom.SEQ_NUM;
                        pbom.SEQ_NUM = (maxSeqNum + 1);
                        //新增
                        agent.InvokeServiceFunction("PbomBLL_InsertPbomItem", pbom);
                        break;
                    case "2":
                        var pbomItem = agent.InvokeServiceFunction<PbomItem>("PbomBLL_GetPbomItemOne", pbom);
                        pbomItem.MATERIAL_CODE = pbom.MATERIAL_CODE;
                        //修改
                        agent.InvokeServiceFunction("PbomBLL_UpdatePbomItem", pbomItem);
                        break;
                }


                return this.GetJsViewResult(string.Format("parent.List();parent.showTitle('{0}');parent.closeAppWindow1();", AppResource.SaveMessge));

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 删除

        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult PbomItemTreeDelete()
        {
            string PID = Request.Params["PID"];
            DataResult<int> result = new DataResult<int>();
            try
            {
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                result = agent.InvokeServiceFunction<DataResult<int>>("PbomBLL_DelPbomItem", PID);

                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return PbomItemTree();
                }
                SetMessage(AppResource.DeleteMessage);

                return PbomItemTree();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        


        #endregion
       
    }
}