using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Service
{
    /// <summary>
    /// 出货管理
    /// </summary>
    public class OutProductApp : Repository<YB_OutProduct>
    {
        /// <summary>
        /// 出货列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<OutProductList>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<YB_OutProduct>();
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (param.queryParam != null && param.queryParam.Count > 0)
                {
                    List<IConditionalModel> conModels = new List<IConditionalModel>();
                    param.queryParam.ForEach(x =>
                    {
                        if (!string.IsNullOrEmpty(x.Value))
                        {
                            conModels.Add(new ConditionalModel()
                            {
                                FieldName = x.Name,
                                ConditionalType = (ConditionalType)x.Type,
                                FieldValue = x.Value.Trim()
                            });
                        }
                    });
                    if (conModels.Count > 0)
                    {
                        temquery = temquery.Where(conModels);
                    }
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                    .Select(x => new OutProductList
                    {
                        Id = x.Id,
                        Type = x.Type,
                        BusinessId = x.BusinessId,
                        CancelRemark = x.CancelRemark,
                        Cnt = x.Cnt,
                        Express = x.Express,
                        CreateTime = x.CreateTime,
                        ExpressAmount = x.ExpressAmount,
                        ExpressNo = x.ExpressNo,
                        PayType = x.PayType,
                        Recver = x.Recver,
                        RecverAdderess = x.RecverAdderess,
                        RecverPhone = x.RecverPhone,
                        RecverRemark = x.RecverRemark,
                        Sender = x.Sender,
                        RecvTime = x.RecvTime,
                        SenderAddress = x.SenderAddress,
                        SenderPhone = x.SenderPhone,
                        SenderRemark = x.SenderRemark,
                        SendTime = x.SendTime,
                        Status = x.Status
                    })
                    .Mapper((it, cache) =>
                    {
                        var allbus = cache.Get(list =>
                        {
                            var ids = list.Select(x => x.BusinessId).ToList();
                            return dbClient.Queryable<YB_Business>().Where(x => ids.Contains(x.Id)).ToList();
                        });
                        it.BusinessName = allbus.FirstOrDefault(x => x.Id == it.BusinessId)?.Name;

                        var allexp = cache.Get(list =>
                        {
                            var ids = list.Select(x => x.Express).ToList();
                            return dbClient.Queryable<YB_ExPress>().Where(x => ids.Contains(x.Id)).ToList();
                        });
                        it.ExpressName = allexp.FirstOrDefault(x => x.Id == it.Express)?.Name;
                    })
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<OutProductList>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }
        /// <summary>
        /// 物流列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_ExPress>> GetExpressListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<YB_ExPress>();
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (param.queryParam != null && param.queryParam.Count > 0)
                {
                    List<IConditionalModel> conModels = new List<IConditionalModel>();
                    param.queryParam.ForEach(x =>
                    {
                        if (!string.IsNullOrEmpty(x.Value))
                        {
                            conModels.Add(new ConditionalModel()
                            {
                                FieldName = x.Name,
                                ConditionalType = (ConditionalType)x.Type,
                                FieldValue = x.Value.Trim()
                            });
                        }
                    });
                    if (conModels.Count > 0)
                    {
                        temquery = temquery.Where(conModels);
                    }
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<YB_ExPress>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }
        /// <summary>
        /// 出货设备列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_OutProductDev>> GetDevListAsync(QueryParams param, int id)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<YB_OutProductDev>().Where(x => x.OrderId == id);
                var currentUser = OperatorProvider.Provider.GetCurrent();
                if (param.queryParam != null && param.queryParam.Count > 0)
                {
                    List<IConditionalModel> conModels = new List<IConditionalModel>();
                    param.queryParam.ForEach(x =>
                    {
                        if (!string.IsNullOrEmpty(x.Value))
                        {
                            conModels.Add(new ConditionalModel()
                            {
                                FieldName = x.Name,
                                ConditionalType = (ConditionalType)x.Type,
                                FieldValue = x.Value.Trim()
                            });
                        }
                    });
                    if (conModels.Count > 0)
                    {
                        temquery = temquery.Where(conModels);
                    }
                }
                var query = await temquery
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<YB_OutProductDev>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }

        /// <summary>
        /// 信息编辑
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(YB_OutProduct data)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                data.Recver = data.Recver.ToStr();
                data.Sender = data.Sender.ToStr();
                data.SenderAddress = data.SenderAddress.ToStr();
                data.SenderPhone = data.SenderPhone.ToStr();
                data.SenderRemark = data.SenderRemark.ToStr();
                data.SenderAddress = data.SenderAddress.ToStr();
                data.Recver = data.Recver.ToStr();
                data.RecverAdderess = data.RecverAdderess.ToStr();
                data.RecverPhone = data.RecverPhone.ToStr();
                data.RecverRemark = data.RecverRemark.ToStr();
                data.FilePath = data.FilePath.ToStr();
                data.FailPath = data.FailPath.ToStr();
                data.CancelRemark = data.CancelRemark.ToStr();
                if (data.Id > 0)
                {
                    if (await dbClient.Queryable<YB_OutProduct>().AnyAsync(x => x.Id == data.Id && x.Status == 5))
                    {
                        return new ResultInfo(ResultState.FAIL, "订单已取消,无法修改信息");
                    }
                    await dbClient.Updateable<YB_OutProduct>().SetColumns(x => new YB_OutProduct
                    {
                        Recver = data.Recver,
                        BusinessId = data.BusinessId,
                        Sender = data.Sender,
                        SenderAddress = data.SenderAddress,
                        SenderPhone = data.SenderPhone,
                        SenderRemark = data.SenderRemark,
                        RecverAdderess = data.RecverAdderess,
                        RecverPhone = data.RecverPhone,
                        RecverRemark = data.RecverRemark,
                        Type = data.Type,
                        SendTime = data.SendTime,
                        Cnt = data.Cnt,
                        Express = data.Express,
                        ExpressAmount = data.ExpressAmount,
                        ExpressNo = data.ExpressNo,
                        PayType = data.PayType
                    }).Where(x => x.Id == data.Id).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "修改成功", data.Id);
                }
                else
                {
                    data.CreateTime = DateTime.Now;
                    data.Status = (int)OutProductStatus.Created;
                    int id = await dbClient.Insertable(data).ExecuteReturnIdentityAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功", id);
                }
            }
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SetStatusAsync(int id, int status)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (!await dbClient.Queryable<YB_OutProduct>().AnyAsync(x => x.Id == id))
                {
                    return new ResultInfo(ResultState.FAIL, "记录未找到");
                }
                if (status == 1)
                {
                    await dbClient.Updateable<YB_OutProduct>().SetColumns(x => new YB_OutProduct
                    {
                        Status = status
                    }).Where(x => x.Id == id).ExecuteCommandAsync();
                }
                else if (status == 3)
                {
                    await dbClient.Updateable<YB_OutProduct>().SetColumns(x => new YB_OutProduct
                    {
                        Status = status,
                        SendTime = DateTime.Now
                    }).Where(x => x.Id == id).ExecuteCommandAsync();
                }
                else if (status == 4)
                {
                    await dbClient.Updateable<YB_OutProduct>().SetColumns(x => new YB_OutProduct
                    {
                        Status = status,
                        RecvTime = DateTime.Now
                    }).Where(x => x.Id == id).ExecuteCommandAsync();
                }
                return new ResultInfo(ResultState.SUCCESS, "状态修改成功");
            }
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> CancelAsync(int id, string remark)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (!await dbClient.Queryable<YB_OutProduct>().AnyAsync(x => x.Id == id))
                {
                    return new ResultInfo(ResultState.FAIL, "记录未找到");
                }
                remark = remark.ToStr();
                await dbClient.Updateable<YB_OutProduct>().SetColumns(x => new YB_OutProduct
                {
                    Status = 5,
                    CancelRemark = remark
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "取消成功");
            }
        }


        /// <summary>
        /// 处理csv文件
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="virualpath">虚拟路径</param>
        /// <param name="id">记录id</param>
        /// <returns></returns>
        public async Task<ResultInfo> HandlerFileAsync(string file, string virualpath, string savefolder, int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (await dbClient.Queryable<YB_OutProduct>().AnyAsync(x => x.Id == id && x.Status == 5))
                {
                    return new ResultInfo(ResultState.FAIL, "订单已取消,无法上传文件");
                }
                var dt = CSVFileHelper.OpenCSV(file);
                List<YB_OutProductDev> list = new List<YB_OutProductDev>();
                List<string> codes = new List<string>();
                string failpath = string.Empty;
                int totalcount = dt.Rows.Count;
                int successcount = 0;
                int failcount = 0;
                List<OutProductUploadFileDto> faillist = new List<OutProductUploadFileDto>();
                foreach (DataRow row in dt.Rows)
                {
                    var code = row["code"].ToString().ToStr();
                    if (string.IsNullOrEmpty(code))
                    {
                        faillist.Add(new OutProductUploadFileDto
                        {
                            code = "",
                            msg = "序列号为空"
                        });
                    }
                    else
                    {
                        var equ = await dbClient.Queryable<YB_Device>()
                            .Select(x => new YB_Device
                            {
                                Id = x.Id
                            })
                            .FirstAsync(x => x.FacCode == code);
                        if (equ == null)
                        {
                            faillist.Add(new OutProductUploadFileDto
                            {
                                code = code,
                                msg = "此序列号还未注册"
                            });
                        }
                        else
                        {
                            if (codes.Contains(code))
                            {
                                faillist.Add(new OutProductUploadFileDto
                                {
                                    code = code,
                                    msg = "序列号重复"
                                });
                            }
                            else
                            {
                                codes.Add(code);
                                list.Add(new YB_OutProductDev
                                {
                                    OrderId = id,
                                    DeviceCode = code,
                                    DeviceId = equ.Id
                                });
                            }
                        }
                    }
                }
                if (list.Count == 0)
                {
                    return new ResultInfo(ResultState.FAIL, "文件内容不可为空");
                }
                successcount = list.Count;
                failcount = totalcount - successcount;
                //插入记录表
                if (list.Count > 0)
                {
                    await dbClient.Deleteable<YB_OutProductDev>().Where(x => x.OrderId == id).ExecuteCommandAsync();
                    await dbClient.Insertable(list).ExecuteCommandAsync();
                }
                //如果有失败的则保存失败到文件
                if (failcount > 0)
                {
                    var files = faillist.ToDataTable<OutProductUploadFileDto>();
                    var rootname = $"/uploadfile/product/{DateTime.Now.ToString("yyyyMMdd")}";
                    var name = $"fail_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv";
                    var thumbnailPath = Path.Combine(savefolder, name + ".csv");
                    CSVFileHelper.SaveCSV(files, thumbnailPath);
                    failpath = rootname + thumbnailPath.Replace(savefolder, "").Replace(@"\", @"/");
                }
                await dbClient.Updateable<YB_OutProduct>().SetColumns(x => new YB_OutProduct
                {
                    FilePath = virualpath,
                    FailPath = failpath,
                    Cnt = successcount
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                var msg = $"成功记录{successcount}台设备";
                if (failcount > 0)
                {
                    msg = $"{msg},失败记录{failcount}台设备";
                }
                return new ResultInfo(ResultState.SUCCESS, msg, id);
            }
        }
        /// <summary>
        /// 物流信息编辑
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitExpressAsync(YB_ExPress data)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                data.Name = data.Name.ToStr();
                data.Contact = data.Contact.ToStr();
                data.Phone = data.Phone.ToStr();
                data.Remark = data.Remark.ToStr();
                if (data.Id > 0)
                {
                    await dbClient.Updateable<YB_ExPress>().SetColumns(x => new YB_ExPress
                    {
                        Name = data.Name,
                        Contact = data.Contact,
                        Phone = data.Phone,
                        Remark = data.Remark
                    }).Where(x => x.Id == data.Id).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "信息更新成功");
                }
                else
                {
                    data.CreateTime = DateTime.Now;
                    await dbClient.Insertable<YB_ExPress>(data).ExecuteCommandAsync();
                    return new ResultInfo(ResultState.SUCCESS, "添加成功");
                }
            }
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_OutProduct> DetailAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_OutProduct>().FirstAsync(x => x.Id == id);
            }
        }
        /// <summary>
        /// 物流详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_ExPress> DetailExpressAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_ExPress>().Where(x => x.Id == id).FirstAsync();
            }
        }
        /// <summary>
        /// 获取所有物流列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<YB_ExPress>> GetAllExpressAsync()
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_ExPress>().ToListAsync();
            }
        }
        /// <summary>
        /// 批量设置
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> BatchSetAsync(OutProductBatchSetDto data)
        {
            if (data.ids.Count == 0)
            {
                return new ResultInfo(ResultState.FAIL, "请先选择订单");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (data.type == 1)
                {
                    foreach (var item in data.ids)
                    {
                        if (await dbClient.Queryable<YB_OutProductDev>().AnyAsync(x => x.OrderId == item))
                        {
                            var info = await dbClient.Queryable<YB_OutProduct>()
                                .Where(x => x.Id == item)
                                .Select(x => new YB_OutProduct
                                {
                                    BusinessId = x.BusinessId
                                }).FirstAsync();
                            await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                            {
                                BusinessId = info.BusinessId,
                                ActiveTime = DateTime.Now,
                                Status = (int)DeviceStatus.Run
                            }).Where(x => SqlFunc.Subqueryable<YB_OutProductDev>().Where(e => e.OrderId == item && e.DeviceId == x.Id).Any()).ExecuteCommandAsync();
                        }
                    }
                    return new ResultInfo(ResultState.SUCCESS, "分配成功");
                }
                else
                {
                    foreach (var item in data.ids)
                    {
                        if (await dbClient.Queryable<YB_OutProductDev>().AnyAsync(x => x.OrderId == item))
                        {
                            await dbClient.Updateable<YB_Device>().SetColumns(x => new YB_Device
                            {
                                BusinessId = 0,
                                ActiveTime = null,
                                Status = (int)DeviceStatus.UnActive
                            }).Where(x => SqlFunc.Subqueryable<YB_OutProductDev>().Where(e => e.OrderId == item && e.DeviceId == x.Id).Any()).ExecuteCommandAsync();
                        }
                    }
                    return new ResultInfo(ResultState.SUCCESS, "回收成功");
                }
            }
        }
    }
}
