using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TouchSocket.Core;
using WCS.BLL.DbModels;
using WCS.BLL.Services.IService;
using WCS.DAL;
using WCS.DAL.Db;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.User;

namespace WCS.BLL.Services.Service
{

    /// <summary>
    /// 需要生成序列号保证不重复的方法
    /// </summary>
    public class GenerateService : IGenerateService
    {
        public static object matFlag = new object();

        public static object stockTakingFlag = new object();
        public async Task<ResponseCommon<List<MatInfo>>> generateMatInfo(GenerateMatInfoRequest request)
        {
            //校验是否被禁用
            var matBaseInfo = await DbHelp.db.Queryable<MatBaseInfo>()
                                             .Where(t => t.Id == request.MatBaseInfo.Id)
                                             .FirstAsync();
            if (matBaseInfo == null)
            {
                return new ResponseCommon<List<MatInfo>>()
                {
                    Code = 201,
                    Message = $"生成失败：该物料基础信息不存在",
                    Data = null
                };
            }
            else if (matBaseInfo.IsEnable == false)
            {
                return new ResponseCommon<List<MatInfo>>()
                {
                    Code = 201,
                    Message = $"生成失败：该物料已被禁用",
                    Data = null
                };
            }
            return new ResponseCommon<List<MatInfo>>()
            {
                Code = 201,
                Message = $"生成失败：该物料已被禁用",
                Data = null
            };
            ////生成条码
            //lock (matFlag)
            //{
            //    try
            //    {
            //        DbHelp.db.BeginTran();
            //        var startNumber = ++matBaseInfo.SerialNumber;
            //        var matInfoList = new List<MatInfo>();
            //        for (var i = 0; i < request.TotalCount; i++)
            //        {
            //            var matInfo = new MatInfo()
            //            {
            //                MatSn = GetMatSn(matBaseInfo, startNumber + i),
            //                MatCode = matBaseInfo.MatCode,
            //                MatName = matBaseInfo.MatName,
            //                MatBatch = request.MatBatch,
            //                MatSpec = matBaseInfo.MatSpec,
            //                MatUnit = matBaseInfo.MatUnit,
            //                MatSupplier = matBaseInfo.MatSupplier,

            //                MatCustomer = matBaseInfo.MatCustomer,
            //                MatQty = request.MatQty,
            //                ModifyUser = request.UserName
            //            };
            //            matInfo.Id = DbHelp.db.Insertable(matInfo).ExecuteReturnIdentity();
            //            matInfoList.Add(matInfo);
            //        }

            //        matBaseInfo.SerialNumber = startNumber + request.TotalCount;
            //        DbHelp.db.Updateable(matBaseInfo).ExecuteCommand();
            //        DbHelp.db.CommitTran();
            //        return new ResponseCommon<List<MatInfo>>()
            //        {
            //            Code = 200,
            //            Message = "success",
            //            Data = matInfoList
            //        };
            //    }
            //    catch (Exception ex)
            //    {
            //        DbHelp.db.RollbackTran();
            //        return new ResponseCommon<List<MatInfo>>()
            //        {
            //            Code = 201,
            //            Message = $"生成失败：{ex.Message}",
            //            Data = null
            //        };
            //    }
            //}
        }

        private string GetMatSn(MatBaseInfo matBaseInfo, int serialNumber)
        {
            //var gongshi = "=A1&\"-\"&A2&A3";
            //Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            //keyValuePairs.Add("A1", matBaseInfo.MatCode);
            //keyValuePairs.Add("A2", string.IsNullOrEmpty(matBaseInfo.MatBatch) ? "" : matBaseInfo.MatBatch);
            //keyValuePairs.Add("A3", serialNumber.ToString().PadLeft(6, '0'));
            //var matSn = PnHelp.Jx(gongshi, keyValuePairs);
            return string.Empty;
        }

        public async Task<string> generateStockTakingNumber()
        {
            lock (stockTakingFlag)
            {
                var serialNumber = GetSerialNumber(DocumentTypeEnum.盘点单据);
                return "PD" + DateTime.Now.ToString("yyyyMMdd") + serialNumber.ToString().PadLeft(4, '0');
            }
        }

        public async Task<string> generateOutOrderNumber()
        {
            lock (stockTakingFlag)
            {
                var serialNumber = GetSerialNumber(DocumentTypeEnum.出库单据);
                return "CK" + DateTime.Now.ToString("yyyyMMdd") + serialNumber.ToString().PadLeft(4, '0');
            }
        }

        public async Task<string> generateMXPDOutOrderNumber()
        {
            lock (stockTakingFlag)
            {
                var serialNumber = GetSerialNumber(DocumentTypeEnum.出库单据);
                return "PDOUT" + DateTime.Now.ToString("yyyyMMdd") + serialNumber.ToString().PadLeft(4, '0');
            }
        }

        public int GetSerialNumber(DocumentTypeEnum documentType)
        {
            var documentSerialNumber = DbHelp.db.Queryable<DocumentSerialNumber>()
                                                     .Where(t => t.DocumentType == documentType)
                                                     .First();
            if (documentSerialNumber != null)
            {
                //如果日期不是当天
                if (documentSerialNumber.UpdateDate.Date != DateTime.Now.Date)
                {
                    documentSerialNumber.CurrentSerialNumber = 0;
                    documentSerialNumber.UpdateDate = DateTime.Now;
                }
                var serialNumber = ++documentSerialNumber.CurrentSerialNumber;
                DbHelp.db.Updateable(documentSerialNumber).ExecuteCommand();
                return serialNumber;
            }
            else
            {
                return 0;
            }
        }

        public async Task<ResponseBase> JinChuanGenerateMatInfo(JinChuanGenerateMatInfoRequest request)
        {
            try
            {
                //第一步 查询
                var matBaseInfo = await DbHelp.db.Queryable<MatBaseInfo>().Where(t => t.MatCode == request.MatCode).FirstAsync();
                if (matBaseInfo != null)
                {
                    return new ResponseBase<MatBaseInfo>()
                    {
                        Code = 200,
                        Message = "Success",
                        Data = matBaseInfo
                    };
                }
                else
                {
                    //不存在 则先创建
                    matBaseInfo = new MatBaseInfo()
                    {
                        MatCode = request.MatCode,
                        MatName = string.Empty,
                    };
                    matBaseInfo.Id = DbHelp.db.Insertable(matBaseInfo).ExecuteReturnIdentity();
                    return new ResponseBase<MatBaseInfo>()
                    {
                        Code = 200,
                        Message = "Success",
                        Data = matBaseInfo
                    };
                }
            }
            catch (Exception ex)
            {
                return new ResponseBase<MatBaseInfo>()
                {
                    Code = 300,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        public async Task<ResponseBase> JinChuanCommitMatInfo(JinChuanCommitMatInfoRequest request)
        {
            try
            {
                //
                if (request.TotalPan <= 0 && request.TotalPan >= 500)
                {
                    return new ResponseBase<MatInfo>()
                    {
                        Code = 201,
                        Message = "操作失败：物料盘数请输入1-500",
                        Data = null
                    };
                }

                //第二步 查询基础物料
                var matBaseInfo = await DbHelp.db.Queryable<MatBaseInfo>().Where(t => t.Id == request.MatId).FirstAsync();
                if (matBaseInfo != null)
                {
                    //存在此物料的情况下 判断当前的数量
                    //if (request.CurrentSerilNumber != matBaseInfo.SerialNumber + 1)
                    //{
                    //    return new ResponseBase<MatInfo>()
                    //    {
                    //        Code = 201,
                    //        Message = "操作失败：当前物料流水号冲突！请重新扫码！",
                    //        Data = null
                    //    };
                    //}
                    //流水号不冲突
                    //else
                    {
                        var matInfoList = new List<MatInfo>();

                        try
                        {
                            DbHelp.db.BeginTran();
                            for (int i = 0; i < request.TotalPan; i++)
                            {
                                //保存matBaseInfo
                                //matBaseInfo.SerialNumber++;

                                //保存条码信息
                                var matInfo = new MatInfo()
                                {
                                    MatSn = request.CurrentMatSn[i],
                                    MatCode = matBaseInfo.MatCode,
                                    MatName = matBaseInfo.MatName,
                                    MatBatch = request.MatBatch,
                                    MatSpec = matBaseInfo.MatSpec,
                                    MatUnit = matBaseInfo.MatUnit,
                                    MatSupplier = matBaseInfo.MatSupplier,
                                    MatCustomer = matBaseInfo.MatCustomer,
                                    MatQty = request.MatQty,
                                    ModifyUser = request.UserName
                                };
                                matInfo.Id = DbHelp.db.Insertable(matInfo).ExecuteReturnIdentity();
                                matInfoList.Add(matInfo);
                            }
                            //await DbHelp.db.Insertable(matInfoList).ExecuteCommandAsync();
                            await DbHelp.db.Updateable(matBaseInfo).ExecuteCommandAsync();
                            DbHelp.db.CommitTran();
                        }
                        catch (Exception ex)
                        {
                            DbHelp.db.RollbackTran();
                            return new ResponseBase<List<MatInfo>> ()
                            {
                                Code = 300,
                                Message = $"失败：{ex.Message}",
                                Data = matInfoList
                            };
                        }
                        return new ResponseBase<List<MatInfo>>()
                        {
                            Code = 200,
                            Message = "Success",
                            Data = matInfoList
                        };
                    }

                }
                else
                {
                    return new ResponseBase<MatInfo>()
                    {
                        Code = 201,
                        Message = "操作失败：不存在此物料,请重试！",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new ResponseBase<MatInfo>()
                {
                    Code = 300,
                    Message = ex.Message,
                    Data = null
                };
            }
        }
    }
}
