using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.EnumModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.Http;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 包材接口
    /// </summary>
    [UserLoginFilter]
    public class PackageController : BaseController<TFS_PackageMain>
    {
        private readonly PackageBll PackageBll = new PackageBll();
        /// <summary>
        /// 初始化
        /// </summary>
        public PackageController()
        {
            //设置可新增、修改字段
            InsertField = UpdateField = "FFactory,FCode,FSpecs,FSize,FNetWeight,FGrossWeight,FEditUser,FEditDate";
        }

        /// <summary>
        /// 获取子项集合
        /// </summary>
        [HttpPost]
        public ApiResult GetPackageChildList(Dictionary<string, object> pageParam)
        {
            return GetTPageList<TFS_PackageChild>(pageParam);
        }

        /// <summary>
        /// 删除子项信息
        /// </summary>
        [HttpPost]
        public ApiResult DeletePackageChild(Dictionary<string, object> deleteParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = BaseBll.DeleteDataById(deleteParam, "TFS_PackageChild");
            }, apiResult, Request, deleteParam);
        }

        /// <summary>
        /// 不补充包材信息
        /// </summary>
        [HttpPost]
        public ApiResult NoSupplyPackageChild(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = PackageBll.NoSupplyPackageChild(inParam);
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// 获取包材信息
        /// </summary>
        [HttpPost]
        public ApiResult GetPackageInfo(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                inParam.TryGetValue("FTeamID", out object objTeamId);
                apiResult.Data = PackageBll.GetPackageInfo(int.Parse(objTeamId.ToString()));
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// 操作包材信息（包含主子）
        /// </summary>
        [HttpPost]
        public ApiResult UpdatePackageData(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            int mainId = -1;
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                if (inParam.ContainsKey("FEditUser")) inParam.Remove("FEditUser");
                inParam.Add("FEditUser", user.FID);

                // 20230404 需求变更：增加包材新增、修改入口（自包材清单）
                if (inParam.ContainsKey("FOperateType"))
                {
                    mainId = UpdatePackage(inParam);
                }
                else
                {
                    // 20230422 新增逻辑
                    // 包规存在则不允许添加包材
                    string fcode = inParam["FCode"].ToString();
                    TFS_PackageMain package = PackageBll.GetPackageByFCode(fcode);

                    if (package != null)
                    {
                        mainId = -2;
                    }
                    else
                    {
                        mainId = PackageBll.UpdatePackageData(inParam);
                        if (mainId > 0 && inParam.TryGetValue("FChild", out object childStr))
                        {
                            List<TFS_PackageChild> childList = JsonConvert.DeserializeObject<List<TFS_PackageChild>>(childStr.ToString());
                            if (childList.Count > 0)
                            {
                                if (childList[0].FID <= 0)
                                {
                                    inParam.Remove("FID");
                                    inParam.Add("FID", mainId);
                                    PackageBll.InsertChildData(inParam, childList);
                                }
                                //当都有子项代码的时候则完成
                                if (childList.Find(s => string.IsNullOrEmpty(s.FCode)) == null)
                                {
                                    PackageBll.TaskCompleted(inParam);
                                }
                            }
                        }
                    }                    
                }
                
                apiResult.Data = mainId;
            }, apiResult, Request, inParam);
        }

        /**
         * 20230404 需求变更
         * 增加包材新增、修改入口（自包材清单）
         * 此部分功能和协同无关
         * 从包材清单进入时，会带入FOperateType参数，且值为1
         * **/
        private int UpdatePackage(Dictionary<string, object> inParam)
        {
            object oOperateType;
            string sOperateType;
            int mainId = -1;

            inParam.TryGetValue("FOperateType", out oOperateType);
            sOperateType = oOperateType.ToString();

            if ("1".Equals(sOperateType))
            {
                // 20230422 新增逻辑
                // 包规存在则不允许添加包材
                string fcode = inParam["FCode"].ToString();
                TFS_PackageMain package = PackageBll.GetPackageByFCode(fcode);

                if (package != null && !inParam.ContainsKey("FID"))
                {
                    return -2;
                }

                mainId = PackageBll.UpdatePackage(inParam);
                inParam.Remove("FID");
                inParam.Add("FID", mainId);

                if (mainId > 0 && inParam.TryGetValue("FChild", out object childStr))
                {
                    List<TFS_PackageChild> childList = JsonConvert.DeserializeObject<List<TFS_PackageChild>>(childStr.ToString());
                    List<TFS_PackageChild> oldChildren = null;
                    List<TFS_PackageChild> newChildren = null;

                    if (childList.Count > 0)
                    {
                        // 将子项列表拆分成新旧两个列表
                        // 当FID > 0时，判断为已存在的子项
                        oldChildren = childList.Where(o => o.FID > 0).ToList();
                        // 当FID <= 0时，判断为新的子项
                        newChildren = childList.Where(n => n.FID <= 0).ToList();

                        if (oldChildren != null && oldChildren.Count > 0)
                        {
                            PackageBll.UpdatePackageChild(inParam, oldChildren);
                        }

                        if (newChildren != null && newChildren.Count > 0)
                        {
                            PackageBll.InsertPackageChild(inParam, newChildren);
                        }
                    }
                }
            }

            return mainId;
        }

        /// <summary>
        /// 对接子项代码
        /// </summary>
        [HttpPost]
        public ApiResult DockMDMCode(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = -1;
                List<TFS_PackageChild> childList = JsonConvert.DeserializeObject<List<TFS_PackageChild>>(inParam["FList"].ToString());
                if (childList != null && childList.Count > 0)
                {
                    var tempList2 = childList.Where(s => s.FMaterialID > 0).ToList();
                    childList = childList.Where(s => s.FMaterialID < 0).ToList();
                    foreach (var item in childList)
                    {
                        Dictionary<string, object> temp = new Dictionary<string, object>();
                        temp.Add("FName", item.FName);
                        temp.Add("FGroup", item.FGroup);
                        temp.Add("FWeightUnit", item.FUnit);
                        temp.Add("FType", "ZMAT");
                        item.FCode = GetMdmCode(temp);
                    }
                    foreach (var item in tempList2)
                    {
                        Dictionary<string, object> temp = new Dictionary<string, object>();
                        temp.Add("FName", item.FName);
                        temp.Add("FGroup", item.FGroup);
                        temp.Add("FWeightUnit", item.FUnit);
                        temp.Add("FType", "ZMAT");
                        item.FCode = item.FCode;
                    }
                    childList = childList.Where(s => s.FMaterialID < 0 && !string.IsNullOrEmpty(s.FCode)).ToList();
                    tempList2 = tempList2.Where(s => s.FMaterialID > 0 && !string.IsNullOrEmpty(s.FCode)).ToList();
                    if (childList != null && childList.Count > 0)
                    {
                        ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                        apiResult.Data = PackageBll.DockChildCode(inParam, childList, user.FID);
                    }
                    else if (tempList2 != null && tempList2.Count > 0)
                    {
                        ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                        apiResult.Data = PackageBll.DockChildCode(inParam, tempList2, user.FID);
                    }
                    else
                    {
                        apiResult.CustomError((int)Constant.ApiResultCode.失败, "对接失败，请稍后再试");
                    }
                }
            }, apiResult, Request, inParam);
        }


        /// <summary>
        /// 模板上传处理（重构父方法）
        /// </summary>
        protected override object CheckUploadFile(List<string> fileList, int funcType, int userId)
        {
            if (funcType == 1)
            {
                GetPackageFromFile(fileList, out List<TFS_PackageMain> mainList, out List<TFS_PackageChild> childList);
                return PackageBll.InsertBatchPackageData(mainList, childList, userId);
            }
            return fileList;
        }

        /// <summary>
        /// 梳理包材导入文件
        /// </summary>
        private void GetPackageFromFile(List<string> fileList, out List<TFS_PackageMain> mainList, out List<TFS_PackageChild> childList)
        {
            mainList = new List<TFS_PackageMain>();
            childList = new List<TFS_PackageChild>();
            List<PropertyInfo> mainProp = typeof(TFS_PackageMain).GetTypeInfo().GetProperties().ToList();
            List<PropertyInfo> childProp = typeof(TFS_PackageChild).GetTypeInfo().GetProperties().ToList();
            List<TFS_FieldInfo> fieldList = BaseBll.GetFileInfoList((int)Constant.FieldInfoType.包材信息模板导入);

            PropertyInfo temp = null;
            foreach (string filePath in fileList)
            {
                DataTable dt = NPOIHelper.ImportExceltoDt(filePath);
                List<string> items = new List<string>();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    items.Add(dt.Columns[i].ColumnName);
                }
                foreach (DataRow dr in dt.Rows)
                {
                    TFS_PackageMain main = new TFS_PackageMain();
                    TFS_PackageChild child = new TFS_PackageChild();
                    foreach (TFS_FieldInfo field in fieldList)
                    {
                        string value = GetValueByName(dr, items, field.FFieldName, field.FDefault);
                        string[] temps = field.FColumnFIeld.Split('.');
                        if ((temp = mainProp.Find(s => s.Name.Equals(temps.Last()))) != null)
                        {
                            if (temps.Length == 1 || temps[0] == "TFS_PackageMain")
                            {
                                temp.SetValue(main, value);
                            }
                        }
                        if ((temp = childProp.Find(s => s.Name.Equals(temps.Last()))) != null)
                        {
                            if (temps.Length == 1 || temps[0] == "TFS_PackageChild")
                            {
                                temp.SetValue(child, value);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(main.FCode))
                    {
                        mainList.Add(main);
                        childList.Add(child);
                    }
                }
            }
        }
    }
}
