using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using QMAPP.FJC.Entity.Basic;
using QMFrameWork.WebUI.DataSource;
using QMAPP.ServicesAgent;
using QMAPP.Common.Web.Controllers;
using QMFrameWork.WebUI.Attribute;
using QMAPP.FJC.Entity.Operation;
using QMAPP.FJC.Web.Models.ProductPetrospect;
using QMAPP.FJC.Entity;
using QMAPP.Entity;
using QMFrameWork.Data;
using QMFrameWork.Common.Serialization;
using System.Data;
using QMAPP.FJC.Web.Models.Operation;
using QMAPP.FJC.Web;
using QMFrameWork.Common.ExcelOperation;
using QMFrameWork.Log;
using QMAPP.FJC.Entity.Injection;

namespace QMAPP.Web.Controllers
{
    ///</summary>
    /// 模块编号:
    /// 作    用:本体
    /// 作    者:王庆男
    /// 编写日期:2015年08月31日
    /// </summary>
    public class MainController : QController
    {
        #region 获取列表
        /// <summary>
        /// 加载列表
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult List(bool? callBack)
        {
            MainModel seachModel = new MainModel();
            seachModel.STARTCREATEDATE = DateTime.Now.Date.AddDays(-10).ToString("yyyy-MM-dd HH:mm:ss");
            seachModel.ENDCREATEDATE = DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
            seachModel.ImmediateSearch = false;
            if (callBack == true)
                  TryGetSelectBuffer<MainModel>(out seachModel);
            seachModel.rownumbers = false;
            seachModel.url = "/Main/GetList";
            return View("MainList", seachModel);
        }

        #region 加载投料列表

        /// <summary>
        /// 加载零件列表11111111111
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult GetProductList()
        {
            string pid = Request.Params["PID"];

            ServiceAgent wcfAgent = this.GetServiceAgent();
            List<Product> list = new List<Product>();
            MainProduct condition = new MainProduct();
            condition.MID = pid;
            #region wcf服务统一接口
            var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<Product>>>("MainProductBLL_GetListWithProduct", condition);

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

            List<object> objlist = new List<object>();
            foreach (var o in list)
            {
                objlist.Add(new
                {
                    PID = o.PID,
                    MATERIALCODE = o.MATERIAL_CODE,
                    PROCODE = o.PRODUCTCODE,
                    MATERIALNAME = o.MATERIAL_NAME,
                    MACHINENAME = o.MACHINENAME
                });
            }

            return Content(JsonConvertHelper.GetSerializes(objlist));
            #endregion
        }
        #endregion


        #region 加载投料列表
        /// <summary>
        /// 加载投料列表222222222222222222
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult GetProductInfectionList()
        {
            //用pid替代MAINCODE
            string pid = Request.Params["PID"];
            string materialBatch = Request.Params["MATERIALBATCH"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            List<InjectionRecorder> list = new List<InjectionRecorder>();
            InjectionRecorder condition = new InjectionRecorder();
            #region wcf服务统一接口
            var dataResult = wcfAgent.InvokeServiceFunction<DataResult<List<InjectionRecorder>>>(QMAPP.ServicesAgent.FeedInManage.MainBLL_GetProductInfectionList.ToString(), pid);

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

            List<object> objlist = new List<object>();
            foreach (var o in list)
            {
                objlist.Add(new
                {
                    PID = o.PID,
                    PPID = o.MPPID,
                    MATERIALNAME = o.MATERIALNAME,
                    MATERIALCODE = o.MATERIALCODE,
                    MATERIALTYPE = o.MATERIALTYPE,
                    MATERIALBATCH = o.MATERIALBATCH,
                    INJECTIONINDEX = o.INJECTIONINDEX,
                    INJECTIONTERMINAL = o.INJECTIONTERMINAL,
                    USEDWEIGHT = o.USEDWEIGHT
                });
            }

            return Content(JsonConvertHelper.GetSerializes(objlist));
            #endregion
        }
        #endregion

        

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="callBack">是否回调</param>
        /// <returns>列表</returns>
        [HandleException]
        public ActionResult GetList(bool? callBack)
        {
            MainModel seachModel = null;
            DataPage page = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            Main condition = null;
            try
            {
                //获取查询对象
                seachModel = GetModel<MainModel>();
                #region 获取缓存值
                if (callBack != null)
                {
                    TryGetSelectBuffer<MainModel>(out seachModel);
                }
                else
                {
                    //保存搜索条件
                    SetSelectBuffer<MainModel>(seachModel);
                }
                #endregion
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                condition = CopyToModel<Main, MainModel>(seachModel);
                condition.COMPLETEFLAG = EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString();

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

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

                DateGridResult<Main> result = new DateGridResult<Main>();
                result.Total = page.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<Main>>(page.Result.ToString());
                #endregion
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑载入
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult Edit()
        {
            MainModel model = new MainModel();
            string ID = Request.Params["PID"];
            Main Entity = new Main();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            try
            {
                if (string.IsNullOrEmpty(ID) == false)
                {
                    //修改获取原数据
                    Entity.PID = ID;
                    Entity = wcfAgent.InvokeServiceFunction<Main>(QMAPP.ServicesAgent.B9IPCService.MainBLL_Get.ToString(), Entity);
                    model = CopyToModel<MainModel, Main>(Entity);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult Save(MainModel saveModel)
        {
            Main Entity = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            int successYN;//是否保存成功
            try
            {
                Entity = CopyToModel<Main, MainModel>(saveModel);
                if (string.IsNullOrEmpty(Entity.PID) == true)
                {
                    //新增
                    successYN = wcfAgent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.B9IPCService.MainBLL_Insert.ToString(), Entity);
                    if (successYN == -1)
                    {
                        SetMessage("编号已存在,请换一个!");
                        return View("MainEdit", saveModel);
                    }
                }
                else
                {
                    //修改
                    successYN = wcfAgent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.B9IPCService.MainBLL_Update.ToString(), Entity);
                    if (successYN == -1)
                    {
                        SetMessage("编号已存在,请换一个!");
                        return View("MainEdit", saveModel);
                    }
                }
                return this.GetJsViewResult(string.Format("parent.List(1);parent.showTitle('{0}');parent.closeAppWindow1();", AppResource.SaveMessge));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 导出excel
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult ExportExcel()
        {
            MainModel seachModel = null;
            Main condition = null;
            DataTable exportDt = new DataTable();
            string selectKey = Request["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            try
            {
                //获取查询对象
                seachModel = GetModel<MainModel>();
                condition = CopyToModel<Main, MainModel>(seachModel);

                condition.TableName = "MainExp";

                //获取数据
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult<DataTable>>(QMAPP.ServicesAgent.B9IPCService.MainBLL_GetExportData.ToString(), condition);

                //通过返回dataResult判断
                if (dataResult.Ex != null)
                {
                    throw dataResult.Ex;
                }
                else if (dataResult.IsSuccess)
                {
                    exportDt = dataResult.Result;
                }
                else
                {
                    SetMessage(dataResult.Msg);
                    return List(true);
                }

                //根据所选信息进行导出
                if (!String.IsNullOrEmpty(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();
                }

                //导出
                IEExcelHelper ieExcelHelper = new IEExcelHelper();
                var sheetInfo = ieExcelHelper.GetMainInfo("MainExp");
                var fileName = System.Guid.NewGuid().ToString() + ".xlsx";
                ieExcelHelper.ExportExcel(sheetInfo, exportDt, QMAPP.Web.Common.ExcelOperationHelper.GetTempPath() + fileName, true);
                return Content(fileName);
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo { ErrorInfo = ex, Info = "导出excel", Tag = "本体查询" });
                SetMessage("导出excel失败");
                return List(true);
            }
        }

        /// <summary>
        /// 导出文件
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportFile()
        {
            String filePath = QMAPP.Web.Common.ExcelOperationHelper.GetTempPath();
            String fileName = Request["FileName"];
            QMAPP.Web.Common.ExcelOperationHelper.FileDownload(Response, filePath + fileName, "本体查询.xlsx");
            return Content("");
        }
        #endregion

        #region 下载模板
        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        public ActionResult GetTemplate()
        {
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "Temp/";
                string fileName = "Main.xls";
                return File(path + fileName, "application/vnd.ms-excel", Url.Encode("信息导入模板.xls"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult SaveInjection(MainModel saveModel)
        {
            InjectionRecorder condition = new InjectionRecorder();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            List<object> objlist = new List<object>();
            try
            {
                condition = CopyToModel<InjectionRecorder, MainModel>(saveModel);

                #region 修改
                var dataResult = wcfAgent.InvokeServiceFunction<DataResult>(QMAPP.ServicesAgent.FeedInManage.MainBLL_UpdateMaterial.ToString(), condition);

                //通过返回dataResult判断
                if (dataResult.Ex != null)
                {
                    throw dataResult.Ex;
                }
                else if (dataResult.IsSuccess)
                {
                    objlist.Add(new { isSuccess = true });
                    SetMessage(AppResource.SaveMessge);
                }
                else
                {
                    SetMessage(dataResult.Msg);
                }
                #endregion

                return Content(JsonConvertHelper.GetSerializes(objlist));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


    }
}