using Ant.Data;
using Ant.ORM;
using Ant.SuperSocket.Common;
using Ant.Service.Common;
using Ant.Service.Common.Enums;
using MES.Production.Entity;
using MES.Production.Entity.Entity;
using MES.Production.Entity.Enum;
using MES.Production.Entity.Extensions;
using MES.Production.Entity.ResponseMod.DeviceMgt;
using Ant.Service.Mongodb;
using ChangFa.Machinery.WebPage.Controllers;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using JsonHelper = Ant.Service.Common.JsonHelper;

namespace ChangFa.Machinery.WebPage.Areas.SysManage.Controllers
{
    public class DeviceMgtController : BaseController
    {
        /// <summary>
        /// 设备列表
        /// </summary>
        /// <returns></returns>
        /// 
        [UserAuthorize(ModuleAlias = "DeviceMgtInfo", OperaAction = "View")]
        public ActionResult Index()
        {
            try
            {

                #region 加载列表
                using (Ant.ORM.AntORM orm = new Ant.ORM.AntORM())
                {
                    orm.db = Ant.Data.DataAccessFactory.CreateDataConnection("CyclingItem");
                    Ant.ORM.RequestModel request = new Ant.ORM.RequestModel();
                    request.newSt = new Ant.ORM.SqlNote() { Author = "smj", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "DeviceMgtController-Index" };

                    var query = orm.Queryable<SYS_Device>().Where(p => p.IsDelete == 0);

                    // 检索条件
                    query = query.WhereIf(!string.IsNullOrEmpty(keywords), p => p.Name.Contains(keywords));
                    // 分页查询
                    var skipLimit = PageCollection.GetSkipLimit(base.page, base.pagesize);
                    // 具体查询
                    var list = query.OrderByDesc(o => o.ModifyDT).Skip(skipLimit.Item1).Top(skipLimit.Item2).ToList(request);
                    // 查出总数
                    var total = query.Count();

                    List<SYS_Device> devices = list.ResultModel;

                    var result = devices?.Select(device => new DeviceMgtIndexDto()
                    {
                        Id = device.Id,
                        Name = device.Name,
                        Code = device.Code,
                        Address = device.Address
                    }).ToList();

                    #region 查询出设备的部品和打包盒信息

                    var deviceIds = devices?.Select(p => p.Id).ToList();
                    if (deviceIds?.Count() > 0)
                    {
                        // 查询设备打包盒信息
                        var devicePacking = orm.Queryable<YW_DevicePacking>().Where(p => deviceIds.Contains(p.DeviceId));
                        var packing = orm.Queryable<YW_Packing>();
                        //连表查询
                        var ss1 = devicePacking.InnerJoin(packing, (dp, p) => dp.PackingId == p.Id).Select((dp, p) => new DeviceMgtIndexDto
                        {
                            Id = dp.DeviceId,
                            DevicePackingId = dp.Id,
                            PackingId = p.Id,
                            PackingName = p.Name,
                            PackingCapacity = dp.Capacity,
                            PackingStock = dp.Stock
                        }).ToList(request);
                        List<DeviceMgtIndexDto> pcakings = ss1?.ResultModel;

                        // 查询设备商品信息
                        var deviceProduct = orm.Queryable<YW_DeviceProduct>().Where(p => deviceIds.Contains(p.DeviceId));
                        var product = orm.Queryable<YW_Product>();
                        //连表查询
                        List<DeviceMgtIndexDto> products = deviceProduct.InnerJoin(product, (dp, p) => dp.ProductId == p.Id).Select((dp, p) => new DeviceMgtIndexDto
                        {
                            Id = dp.DeviceId,
                            DeviceProductId = dp.Id,
                            ProductId = p.Id,
                            ProductName = p.Name,
                            ProductPrice = dp.Price,
                            ProductStock = dp.Stock
                        }).ToList(request)?.ResultModel;

                        result?.ForEach(item =>
                        {
                            var currentPacking = pcakings?.FirstOrDefault(p => p.Id == item.Id);
                            if (currentPacking != null)
                            {
                                item.DevicePackingId = currentPacking.DevicePackingId;
                                item.PackingId = currentPacking.PackingId;
                                item.PackingName = currentPacking.PackingName;
                                item.PackingCapacity = currentPacking.PackingCapacity;
                                item.PackingStock = currentPacking.PackingStock;
                            }

                            var currentProduct = products?.FirstOrDefault(p => p.Id == item.Id);
                            if (currentProduct != null)
                            {
                                item.DeviceProductId = currentProduct.DeviceProductId;
                                item.ProductId = currentProduct.ProductId;
                                item.ProductName = currentProduct.ProductName;
                                item.ProductPrice = currentProduct.ProductPrice;
                                item.ProductStock = currentProduct.ProductStock;
                            }
                        });
                    }
                    #endregion

                    var resultDto = new PageInfo(base.page, base.pagesize, total, result);

                    ViewBag.Search = base.keywords;
                    return View(resultDto);
                }
                #endregion

            }
            catch (Exception e)
            {
                WriteLog(enumOperator.Select, "加载设备列表:", e);
                throw e.InnerException;
            }
        }

        // GET: SysManage/Device
        public ActionResult DeviceManage()
        {
            PageInfo pageInfo = new PageInfo(base.page, base.pagesize, 0, JsonConverter.JsonClass(new List<DeviceManage>()));
            using (AntORM orm = new AntORM())
            {
                orm.db = DataAccessFactory.CreateDataConnection("CyclingItem");
                RequestModel res = new RequestModel();
                res.newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "查询菜单的单个实体方法" };
                int pageno = (page - 1) * pagesize;

                var q = orm.Queryable<DeviceManage>();
                if (!keywords.IsEmpty())
                {
                    q = q.Where(p => p.IMEI.Contains(keywords));
                }
                var result = q.OrderByDesc(p => p.LastOnlineTime).Skip(pageno).Top(pagesize).ToList(res);
                if (result.IsSuccess)
                {
                    result.RecordNum = q.Count();
                }
                else
                {
                    result = new ResponseModel();
                    result.RecordNum = 0;
                    result.ResultModel = new List<DeviceManage>();
                }
                pageInfo = new PageInfo(base.page, base.pagesize, result.RecordNum, JsonConverter.JsonClass(result.ResultModel));
            }
            ViewBag.Search = base.keywords;
            return View(pageInfo);
        }


    }
}