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

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

        #region 编辑
        /// <summary>
        /// 编辑载入
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult Edit()
        {
            ProductInfoModel model = new ProductInfoModel();
            string ID = Request.Params["PID"];
            ProductInfo Entity = new ProductInfo();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<ProductInfo> result = new DataResult<ProductInfo>();
            try
            {
                if (string.IsNullOrEmpty(ID) == false)
                {
                    //修改获取原数据
                    Entity.PID = ID;
                    result = wcfAgent.InvokeServiceFunction<DataResult<ProductInfo>>(QMAPP.ServicesAgent.B9BasicService.ProductInfoBLL_Get.ToString(), Entity);
                    if (result.IsSuccess == false)
                    {
                        SetMessage(result.Msg);
                        return View("ProductInfoEdit", model);
                    }
                    model = CopyToModel<ProductInfoModel, ProductInfo>(result.Result);
                }
                return View("ProductInfoEdit", model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns>处理结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult Save(ProductInfoModel saveModel)
        {
            ProductInfo Entity = null;
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                Entity = CopyToModel<ProductInfo, ProductInfoModel>(saveModel);
                if (string.IsNullOrEmpty(Entity.PID) == true)
                {
                    //新增
                    result = wcfAgent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.B9BasicService.ProductInfoBLL_Insert.ToString(), Entity);
                    if (result.IsSuccess == false)
                    {
                        SetMessage("编号已存在,请换一个!");
                        return View("ProductInfoEdit", saveModel);
                    }
                }
                else
                {
                    //修改
                    result = wcfAgent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.B9BasicService.ProductInfoBLL_Update.ToString(), Entity);
                    if (result.IsSuccess == false)
                    {
                        SetMessage("编号已存在,请换一个!");
                        return View("ProductInfoEdit", 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 Delete(ProductInfo model)
        {
            string selectKey = Request.Form["selectKey"];
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<int> result = new DataResult<int>();
            try
            {
                result = wcfAgent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.B9BasicService.ProductInfoBLL_Delete.ToString(), selectKey);
                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return List(true);
                }
                SetMessage(AppResource.DeleteMessage);
                return List(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 导出excel
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        public ActionResult ExportExcel()
        {
            ProductInfoModel seachModel = null;
            ProductInfo condition = null;
            DataTable exportDt = new DataTable();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            string selectKey = Request.Form["selectKey"];
            try
            {
                //获取查询对象
                seachModel = GetModel<ProductInfoModel>();
                condition = CopyToModel<ProductInfo, ProductInfoModel>(seachModel);
                //获取数据
                exportDt = wcfAgent.InvokeServiceFunction<DataTable>(QMAPP.ServicesAgent.B9BasicService.ProductInfoBLL_GetExportData.ToString(), condition);
                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("ProductInfoExp", "ProductInfoExp.xlsx", exportDt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 导入excel
        /// <summary>
        /// 导入excel
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        public ActionResult ImportExcel()
        {
            DataTable dt = null;
            List<ProductInfo> list = new List<ProductInfo>();
            DataResult<ImportMessage> serviceResult = null;
            string fileName = Request.Form["fileName"];
            ServiceAgent wcfAgent = this.GetServiceAgent();

            //Area aramodel = new Area();
            Factory factorymodel = new Factory();
            ProductBasic productbasicmodel = new ProductBasic();

            try
            {
                dt = this.GetTableByExcel("ProductInfoImp", fileName, dt);
                //格式转换
                list = QMFrameWork.Common.Util.BindHelper.ConvertToList<ProductInfo>(dt).ToList();
                serviceResult = wcfAgent.InvokeServiceFunction<DataResult<ImportMessage>>(QMAPP.ServicesAgent.B9BasicService.ProductInfoBLL_GetImportData.ToString(), list, factorymodel, productbasicmodel);
                if (serviceResult.Ex != null)
                {
                    throw serviceResult.Ex;
                }
                if (serviceResult.Result.failureNum != 0)
                {
                    foreach (RowError error in serviceResult.Result.Errors)
                    {
                        dt.Rows[error.Key - 1]["InfoError"] = error.Value;
                    }
                    ImportMessageModel model = new ImportMessageModel();
                    model.InfoName = "ProductInfoImp";
                    model.ReturnUrl = "ProductInfo/List?callBack=true";
                    model.Message = serviceResult.Result;
                    model.ErrorDt = dt;
                    return new MessageOutputController().OutputImportMessage(model);
                }
                else
                {
                    SetMessage(serviceResult.Msg + ",如下:<br/>"
                    + "插入" + serviceResult.Result.insertNum + "条,"
                    + "更新" + serviceResult.Result.updateNum + "条"
                    );
                    return List(true);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                System.IO.File.Delete(MvcApplication.TempPath + fileName);
            }
        }
        #endregion

        #region 获取工厂信息下拉列表
        /// <summary>
        /// 获取工厂信息下拉列表
        /// </summary>
        /// <param name="AreaName"></param>
        /// <returns>结果</returns>
        public ContentResult GetFactoryList()
        {
            Factory info = new Factory();
            ComboboxResult model = new ComboboxResult();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<List<Factory>> result = new DataResult<List<Factory>>();
            //获取工厂信息
            result = wcfAgent.InvokeServiceFunction<DataResult<List<Factory>>>(QMAPP.ServicesAgent.B9BasicService.FactoryBLL_GetFactoryList.ToString(), info);
            model.Add(new ComboboxItem { ID = "", Text = new DictController().EmptyItemTitle });
            foreach (var item in result.Result)
            {
                model.Add(new ComboboxItem { ID = item.PID, Text = item.FACTORY_CODE + "/" + item.FACTORY_NAME });
            }
            return Content(model.ToString());
        }
        #endregion

        #region 获取零件类别下拉列表
        /// <summary>
        /// 获取零件类别下拉列表
        /// </summary>
        /// <param name="AreaName"></param>
        /// <returns>结果</returns>
        public ContentResult GetProductBasicList()
        {
            ProductBasic info = new ProductBasic();
            ComboboxResult model = new ComboboxResult();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            DataResult<List<ProductBasic>> result = new DataResult<List<ProductBasic>>();
            //获取零件信息
            result = wcfAgent.InvokeServiceFunction<DataResult<List<ProductBasic>>>(QMAPP.ServicesAgent.B9BasicService.ProductBasicBLL_GetProductBasicList.ToString(), info);
            model.Add(new ComboboxItem { ID = "", Text = new DictController().EmptyItemTitle });
            foreach (var item in result.Result)
            {
                model.Add(new ComboboxItem { ID = item.PID, Text = item.PRODUCTNAME });
            }
            return Content(model.ToString());
        }
        #endregion

    }
}