using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QMFrameWork.WebUI.Attribute;
using QMAPP.Common.Web.Controllers;
using QMAPP.FJC.Web.Models.Stocktaking;
using QMFrameWork.Data;
using QMAPP.ServicesAgent;
using QMAPP.FJC.Entity.Stocktaking;
using QMFrameWork.WebUI.DataSource;
using QMFrameWork.Common.Serialization;
using QMAPP.FJC.Entity.Basic;
using QMAPP.FJC.Web.Models.Basic;
using System.Data;
using QMAPP.MD.Entity;
using System.Runtime.Serialization.Json;
using QMAPP.Entity;
using QMAPP.MD.Web.Models;

namespace QMAPP.FJC.Web.Controllers
{
    public class StocktakingManageController : QController
    {
        #region 主界面加载列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult List(bool? callBack)
        {
            StocktakingSearchModel seachModel = new StocktakingSearchModel();
            if (callBack == true)
                TryGetSelectBuffer<StocktakingSearchModel>(out seachModel);
            seachModel.rownumbers = false;
            seachModel.url = "/StocktakingManage/GetList";
            return View("List", seachModel);
        }
        #endregion

        #region 主界面获取列表
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="callBack">是否回调</param>
        /// <returns>列表</returns>
        [HandleException]
        public ActionResult GetList(bool? callBack)
        {
            StocktakingSearchModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            Countingplaninfo condition = null;
            try
            {
                //获取查询对象
                seachModel = GetModel<StocktakingSearchModel>();

                #region 获取缓存值
                if (callBack != null)
                {
                    TryGetSelectBuffer<StocktakingSearchModel>(out seachModel);
                }
                else
                {
                    //保存搜索条件
                    SetSelectBuffer<StocktakingSearchModel>(seachModel);
                }
                #endregion

                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<Countingplaninfo, StocktakingSearchModel>(seachModel);

                #region wcf服务统一接口
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<DataPage>>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_GetList.ToString(), condition, page);

                //通过返回dataResult判断
                if (dataResult.Ex != null)
                {
                    throw dataResult.Ex;
                }
                else if (dataResult.IsSuccess)
                {
                    page = dataResult.Result;
                }

                DateGridResult<Countingplaninfo> result = new DateGridResult<Countingplaninfo>();
                result.Total = page.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<Countingplaninfo>>(page.Result.ToString());
                #endregion

                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion 

        #region 编辑载入(点击添加,修改)
        /// <summary>
        /// 编辑载入
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult Edit()
        {
            StocktakingSearchModel model = new StocktakingSearchModel();
            Countingplaninfo entity = new Countingplaninfo();
            string PID = Request.Params["PID"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<Countingplaninfo> result = new DataResult<Countingplaninfo>();
            try
            {
                if (string.IsNullOrEmpty(PID) == false)
                {
                    //修改获取原数据
                    entity.PID = PID;
                    result = wcfAgent.InvokeServiceFunction<DataResult<Countingplaninfo>>("StocktakingBLL_Get", entity);
                    if (result.IsSuccess == false)
                    {
                        SetMessage(result.Msg);
                        return View("E", model);
                    }
                    model = CopyToModel<StocktakingSearchModel, Countingplaninfo>(result.Result);
                    return View("E", model);
                }
                else
                {
                    return View("A", model);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 保存(添加,编辑)
        /// <summary>
        /// 新增界面保存 
        /// </summary>
        /// <param name="model"></param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [HandleException]
        [ValidateInput(false)]
        public ActionResult StocktingPlanSave(StocktakingSearchModel saveModel)
        {
            Countingplaninfo entity = new Countingplaninfo();
            QMAPP.MD.Entity.Material condition = new MD.Entity.Material();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();

            string materials = "('" + saveModel.MaterialCodes.Replace(";", "','") + "')";

            condition.MaterialCodes = materials;

            //获取物料信息
            List<QMAPP.MD.Entity.Material> machinelist = wcfAgent.InvokeServiceFunction<List<QMAPP.MD.Entity.Material>>("MaterialBLL_GetMaterialInfoList", condition);

            if (saveModel.EDITFLAG == null)
            {
                entity.PID = Guid.NewGuid().ToString();
                entity.COUNTTYPE = saveModel.COUNTTYPE;
                entity.PLAN_DATE = saveModel.PLAN_DATE;
                entity.REMARK = saveModel.REMARK;

                #region 计划单号
                object PLAN_NO = wcfAgent.InvokeServiceFunction<object>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_GetPlanNoByDate.ToString(), saveModel.PLAN_DATE.ToString("yyyyMMdd"));
                if (PLAN_NO == null)
                {
                    entity.PLAN_NO = entity.PLAN_DATE.ToString("yyyyMMdd") + "01";
                }
                else
                {
                    string PLAN_NO_Now = DateTime.Now.ToString("yyyyMMdd");
                    if (PLAN_NO_Now.ToString() == PLAN_NO.ToString().Substring(0, 8))
                    {
                        int resultSum = Convert.ToInt32(PLAN_NO.ToString().Substring(PLAN_NO.ToString().Length - 2, 2)) + 1;
                        string AddNumber = "";
                        if (resultSum.ToString().Length == 1)
                        {
                            AddNumber = "0" + resultSum.ToString();
                        }
                        entity.PLAN_NO = PLAN_NO.ToString().Substring(0, 8) + AddNumber.ToString();
                    }
                    else
                    {
                        entity.PLAN_NO = DateTime.Now.ToString("yyyyMMdd") + "01";
                    }
                }
                #endregion


                //T_PP_COUNTINGPLAN插入
                int result1 = wcfAgent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_Insert.ToString(), entity);

                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("StocktakingBLL_InsertStocktakingDeail", entity, machinelist);

            }
            //编辑时保存
            else
            {
                //当前修改信息日期和计划号不一致时
                if (saveModel.PLAN_DATE.ToString("yyyyMMdd") != saveModel.PLAN_NO.ToString().Substring(0, 8))
                {
                    #region 计划单号
                    object PLAN_NO = wcfAgent.InvokeServiceFunction<object>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_GetPlanNoByDate.ToString(), saveModel.PLAN_DATE);
                        string PLAN_NO_Now = DateTime.Now.ToString("yyyyMMdd");
                        if (PLAN_NO_Now.ToString() == PLAN_NO.ToString().Substring(0, 8))
                        {
                            int resultSum = Convert.ToInt32(PLAN_NO.ToString().Substring(PLAN_NO.ToString().Length - 2, 2)) + 1;
                            string AddNumber = "";
                            if (resultSum.ToString().Length == 1)
                            {
                                AddNumber = "0" + resultSum.ToString();
                            }
                            entity.PLAN_NO = PLAN_NO.ToString().Substring(0, 8) + AddNumber.ToString();
                        }
                        else
                        {
                            entity.PLAN_NO = DateTime.Now.ToString("yyyyMMdd") + "01";
                        }
                    #endregion
                }
                else
                {
                    entity.PLAN_NO = saveModel.PLAN_NO;
                }

                entity = CopyToModel<Countingplaninfo, StocktakingSearchModel>(saveModel);


                //修改
                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("StocktakingBLL_Update", entity);

                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("StocktakingBLL_EditInsertStocktakingDeail", entity, machinelist);

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

        #region 点击设备下拉界面保存(提交)
        /// <summary>
        /// 编辑界面填充设备信息
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult AddMaterialDetail(CountingdetailViewModel saveMode)
        {

            var materialcode = Request.QueryString["MATERIAL_CODE"];
            string kkk=materialcode.Substring(1, materialcode.Length-1);
            string materialCodes = "('" + kkk.Replace(",", "','") + "')";

            //物料发货明细实体
            QMAPP.MD.Entity.Material detail = new QMAPP.MD.Entity.Material()
            {
                //MATERIAL_CODE = materialcode,
                MaterialCodes = materialCodes,
            };
            try
            {
                //实例化服务
                ServiceAgent wcfAgent = this.GetServiceAgent();

                //通过服务调用ProductOffLineBLL中的CheckRfid方法校验填写的RFID是否合法
                //QMAPP.MD.Entity.Material dataResult = wcfAgent.InvokeServiceFunction<QMAPP.MD.Entity.Material>("StocktakingBLL_GetMachineInfo", detail);
                List<QMAPP.MD.Entity.Material> dataResult = wcfAgent.InvokeServiceFunction<List<QMAPP.MD.Entity.Material>>("StocktakingBLL_GetMachineInfo", detail);

                //dataResult.CREATEUSERNAME = AccountController.GetLoginInfo().UserName.Trim().ToString();
                for (var i = 0; i < dataResult.Count(); i++)
                {
                    dataResult[i].CREATEUSERNAME = AccountController.GetLoginInfo().UserName.Trim().ToString();
                }
                return Json(dataResult, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        #endregion

        #region 编辑时删除物料信息
        /// <summary>
        /// 编辑时删除物料信息
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult EditDelete(CountingdetailViewModel saveMode)
        {
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("StocktakingBLL_EditDelete",saveMode);
                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return Edit();
                }
                SetMessage(AppResource.DeleteMessage);
                return Edit();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 编辑界面填充物料信息

        /// <summary>
        /// 编辑界面填充物料信息
        /// </summary>
        /// <param name="callBack">是否回调</param>
        /// <returns>列表</returns>
        [HandleException]
        public ActionResult GetMaterialGridList(bool? callBack)
        {
            CountingdetailViewModel seachModel = null;
            DataResult<DataPage> pageResult = new DataResult<DataPage>();
            DataPage page = new DataPage();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            CountingdetailInfo condition = null;
            try
            {
                //获取查询对象
                seachModel = GetModel<CountingdetailViewModel>();
                #region 获取缓存值
                if (callBack != null)
                {
                    TryGetSelectBuffer<CountingdetailViewModel>(out seachModel);
                }
                else
                {
                    //保存搜索条件
                    SetSelectBuffer<CountingdetailViewModel>(seachModel);
                }
                #endregion
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<CountingdetailInfo, CountingdetailViewModel>(seachModel);

                condition.PLANID = seachModel.PLANID;

                #region wcf服务统一接口
                pageResult = wcfAgent.InvokeServiceFunction<DataResult<DataPage>>("StocktakingBLL_GetMaterialGridList", condition, page);
                if (pageResult.IsSuccess == false)
                {
                    SetMessage(pageResult.Msg);
                    return List(true);
                }
                DateGridResult<CountingdetailInfo> result = new DateGridResult<CountingdetailInfo>();
                result.Total = pageResult.Result.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<CountingdetailInfo>>(pageResult.Result.Result.ToString());
                #endregion
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 当前盘点计划下手持明细加载列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult PanDetail(bool? callBack)
        {
            CountSheetModel seachModel = new CountSheetModel();

            if (callBack == true)
                TryGetSelectBuffer<CountSheetModel>(out seachModel);

            seachModel.rownumbers = false;
            string PID = Request.Params["PID"];
            seachModel.PLANID = PID;
            seachModel.url = "/StocktakingManage/PanDetailList?PID=" + PID;
            return View("PanDetail", seachModel);
        }
        #endregion

        #region 盘点明细查询(手持明细查询)
        /// <summary>
        /// 盘点明细查询
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult PanDetailList()
        {
            try
            {
                QMAPP.FJC.Web.Models.Stocktaking.CountSheetModel model = new QMAPP.FJC.Web.Models.Stocktaking.CountSheetModel();
                DataTable tbl = null;
                string PID = Request.QueryString["PID"];
                ServiceAgent wcfAgent = this.GetServiceAgent();
                DataPage page = null;
                //获取前台分页设置信息
                CountSheetModel seachModel = null;

                //获取查询对象
                seachModel = GetModel<CountSheetModel>();

                page = this.GetDataPage(seachModel);
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<DataPage>>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_GetPanDetail.ToString(), PID, page);
                //通过返回dataResult判断
                if (dataResult.Ex != null)
                {
                    throw dataResult.Ex;
                }
                else if (dataResult.IsSuccess)
                {
                    page = dataResult.Result;
                }
                DateGridResult<CountSheetInfo> result = new DateGridResult<CountSheetInfo>();
                result.Total = page.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<CountSheetInfo>>(page.Result.ToString());
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion 

        #region 盘点比对
        /// <summary>
        /// 盘点比对
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult detailCompareResult()
        {
            string selectKey = Request.Form["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();

            try
            {

                result = wcfAgent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_detailCompareResult.ToString(), selectKey, AccountController.GetLoginInfo().UserName.Trim().ToString());

                if (result.Result <= 0)
                {

                    SetMessage("比对失败!");
                }

                return List(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 加载盘点对比结果列表
        /// <summary>
        /// 加载盘点对比信息列表
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult PanCompareResultDetail(bool? callBack)
        {
            CountSheetModel seachModel = new CountSheetModel();

            if (callBack == true)
                TryGetSelectBuffer<CountSheetModel>(out seachModel);

            seachModel.rownumbers = false;
            string PID = Request.Params["PID"];
            seachModel.PLANID = PID;
            seachModel.url = "/StocktakingManage/PanCompareResultDetailList?PID=" + PID;
            return View("PanCompareResultDetail", seachModel);
        }
        #endregion

        #region 对比结果查询
        /// <summary>
        /// 对比结果查询
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult PanCompareResultDetailList()
        {
            try
            {
                QMAPP.FJC.Web.Models.Stocktaking.CountResultModel model = new QMAPP.FJC.Web.Models.Stocktaking.CountResultModel();
                DataTable tbl = null;
                string PID = Request.QueryString["PID"];
                ServiceAgent wcfAgent = this.GetServiceAgent();
                DataPage page = null;
                //获取前台分页设置信息
                CountResultModel seachModel = null;
                //获取查询对象
                seachModel = GetModel<CountResultModel>();
                page = this.GetDataPage(seachModel);
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<DataPage>>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_GetPanResultDetail.ToString(), PID, page);
                //  通过返回dataResult判断
                if (dataResult.Ex != null)
                {
                    throw dataResult.Ex;
                }
                else if (dataResult.IsSuccess)
                {
                    page = dataResult.Result;
                }
                DateGridResult<CountResultInfo> result = new DateGridResult<CountResultInfo>();
                result.Total = page.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<CountResultInfo>>(page.Result.ToString());
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion 

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult Delete()
        {
            string selectKey = Request.Form["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            DataResult<int> result2 = new DataResult<int>();
            try
            {

                result = wcfAgent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_Delete.ToString(), selectKey);
                result2 = wcfAgent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_SubDelete.ToString(), selectKey);

                if (result.IsSuccess == false | result2.IsSuccess == false)
                {
                    SetMessage("信息有关联,删除失败!");
                    return List(true);
                }
                SetMessage(AppResource.DeleteMessage);
                return List(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 导出excel
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult ExportExcel()
        {
            //CountSheetModel seachModel = null;
            //CountSheetInfo condition = null;
            DataTable exportDt = new DataTable();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            string PID = Request.QueryString["PID"];
            //string selectKey = Request.Form["selectKey"];
            try
            {
                //获取查询对象
                //seachModel = GetModel<CountSheetModel>();
                //condition = CopyToModel<CountSheetInfo, CountSheetModel>(seachModel);
                ////获取数据
                exportDt = wcfAgent.InvokeServiceFunction<DataTable>(QMAPP.ServicesAgent.StocktakingManage.StocktakingBLL_GetExportData.ToString(), PID);
                // if (selectKey != "")
                // {
                DataView dv = new DataView(exportDt);
                //  string strWhere = "";
                // string[] list = selectKey.Split(":".ToCharArray());
                // foreach (string id in list)
                //{
                //    strWhere += " PID='" + id + "' or";
                // }
                //  if (strWhere != "")
                //{
                //      strWhere = strWhere.Remove((strWhere.Length - 2), 2);
                //  }
                // dv.RowFilter = strWhere;
                exportDt = dv.ToTable();
                // }
                //导出
                QMFrameWork.WebUI.Util.IEFileTool efTool = new QMFrameWork.WebUI.Util.IEFileTool();
                return efTool.GetExcelFileResult("PanDetailExp", "PanDetailExp.xlsx", exportDt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion 

        #region 盘点完成

        [HttpPost]
        [HandleException]
        public ActionResult CompleteCompare()
        {
            string selectKey = Request.Form["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                result = wcfAgent.InvokeServiceFunction<DataResult<int>>("StocktakingBLL_CompleteCompare", selectKey);
                if (result.Result <= 0)
                {
                    SetMessage("操作失败!");
                }

                return List(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        #endregion

    }
}