using System.Collections.Generic;
using System.Web.Http;
using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using FactorySystemModel.EnumModel;
using Aspose.Cells;
using System.Globalization;
using System.Linq;
using SqlSugar;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 视图接口
    /// </summary>
    [UserLoginFilter]
    public class ViewController : BaseController<TFS_MaterialInfo>
    {
        private readonly ViewBll _viewBll = new ViewBll();

        /// <summary>
        /// 根据协同ID获取物料视图
        /// </summary>
        [HttpPost]
        public ApiResult GetListByTeamId(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    int teamId = int.Parse(inParam["teamId"].ToString());
                    if (string.IsNullOrWhiteSpace(inParam["viewType"].ToString()))
                    {
                        apiResult.Data = new
                        {
                            columns = _viewBll.GetColumns(),
                            rows = _viewBll.GetListByTeamId2(teamId, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, !inParam.ContainsKey("FAllView")),
                            infos = _viewBll.GetMaterialInfoList(materialId, FGuaranteePeriod, FStorageConditions, user.FID),
                            types = _viewBll.GetMaterialTypeList()
                        };
                    }
                    else
                    {
                        int viewType = int.Parse(inParam["viewType"].ToString());
                        apiResult.Data = new
                        {
                            columns = _viewBll.GetColumns(),
                            rows = _viewBll.GetListByTeamId(teamId, viewType, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, !inParam.ContainsKey("FAllView")),
                            infos = _viewBll.GetMaterialInfoList(materialId, FGuaranteePeriod, FStorageConditions, user.FID),
                            types = _viewBll.GetMaterialTypeList()
                        };
                    }
                }
            }, apiResult, Request);
        }



        /// <summary>
        /// 根据替换试验号TeamID获取物料视图
        /// </summary>
        [HttpPost]
        public ApiResult GetListByHalfMaterialTeamId(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    int teamId = int.Parse(inParam["teamId"].ToString());
                    apiResult.Data = new
                    {
                        columns = _viewBll.GetColumns(),
                        rows = _viewBll.GetListByHalfMaterialTeamId(teamId, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, !inParam.ContainsKey("FAllView")),
                        infos = _viewBll.GetMaterialInfoList(materialId, FGuaranteePeriod, FStorageConditions, user.FID),
                        types = _viewBll.GetMaterialTypeList()
                    };
                }
            }, apiResult, Request);
        }




        /// <summary>
        /// 根据物料路线ID获取物料视图
        /// </summary>
        [HttpPost]
        public ApiResult GetMaterialViewsByTeamId(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    int teamId = int.Parse(inParam["teamId"].ToString());
                    int viewType = int.Parse(inParam["viewType"].ToString());
                    int teamType = int.Parse(inParam["teamType"].ToString());

                    apiResult.Data = new
                    {
                        columns = _viewBll.GetColumns(),
                        rows = _viewBll.GetMaterialViewsByTeamId(teamId, viewType, teamType, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, !inParam.ContainsKey("FAllView")),
                        infos = _viewBll.GetMaterialInfoList(materialId, FGuaranteePeriod, FStorageConditions, user.FID),
                        types = _viewBll.GetMaterialTypeList()
                    };

                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 根据协同ID获取基础表集合
        /// </summary>
        /// <param name="inParam"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMaterialInfoListByTeamId(Dictionary<string, object> inParam) 
        {
            var apiResult = new ApiResult();

            return ExceptionHelper.TryReturnException(() => {
                if (!string.IsNullOrWhiteSpace(inParam["tempId"].ToString()))
                {
                    
                    var data = _viewBll.EexcSql(int.Parse(inParam["tempId"].ToString()));
                    if (data != null) 
                    {
                        apiResult.Data = data;
                    }
                    else
                    {
                        apiResult.Error("未找到物料");
                    }
                }
                else 
                {
                    apiResult.Data = _viewBll.EexcSql();
                }
            
            }, apiResult, Request);
        }


        /// <summary>
        /// 保存视图编辑的内容
        /// </summary>
        [HttpPost]
        public ApiResult UpdateBatchById(List<Dictionary<string, object>> rows)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    apiResult.Data = _viewBll.UpdateBatchById(rows, user.FID);
                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 保存视图编辑的内容
        /// </summary>
        [HttpPost]
        public ApiResult UpdateBatchById2(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    inParam.TryGetValue("TFS_ViewMaterial", out object viewObj);
                    inParam.TryGetValue("TFS_Material", out object materialObj);
                    inParam.TryGetValue("TFS_MaterialInfo", out object infoObj);
                    List<Dictionary<string, object>> viewList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(viewObj));
                    List<Dictionary<string, object>> materialList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(materialObj));
                    List<Dictionary<string, object>> infoList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(infoObj));
                    int teamId = int.Parse(inParam["FTeamID"].ToString());
                    int viewType = int.Parse(inParam["FViewType"].ToString());
                    apiResult.Data = _viewBll.UpdateBatchById2(viewList, materialList, infoList, teamId, viewType, user.FID);

                    if (viewType == 10)
                    {
                        // 创建物料视图事项
                        TFS_FTeamwork teamwork = BaseBll.GetTempModel<TFS_FTeamwork>(teamId);
                        List<Dictionary<string, object>> vml = _viewBll.GetListByTeamId(teamId, viewType, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, true);
                        Dictionary<int, string> hasNewView = new Dictionary<int, string>();

                        if (vml != null)
                        {
                            foreach(Dictionary<string, object> row in vml)
                            {
                                int materialType = (int)(long)row["FViewType"];
                                string factoryId = row["FFactoryID"].ToString();

                                if (materialType == 2 || materialType == 3 || materialType == 4 || materialType == 5)
                                {
                                    if (hasNewView.ContainsKey(materialType))
                                    {
                                        hasNewView[materialType] = hasNewView[materialType] + factoryId + ",";
                                    }
                                    else
                                    {
                                        hasNewView.Add(materialType, factoryId + ",");
                                    }
                                }
                            }
                            TeamworkBll TeamworkBll = new TeamworkBll();
                            TeamworkBll.CreateMaterialTask(hasNewView, teamwork, user.FID);
                        }

                        //补充包材规格
                        BaseBll.CreateTaskData(teamId, user.FID, "14");
                        //成品视图
                        // 20230726 成品事项新增改到新增协同时创建
                        //BaseBll.CreateTaskData(teamwork.FID, user.FID, "3", teamwork.FCreateFactoryID + "," + teamwork.FProdFactoryID);
                        //成品视图物料组复核，有权限的所有
                        BaseBll.CreateTaskData(teamwork.FID, user.FID, "12");
                        teamwork = BaseBll.GetTempModel<TFS_FTeamwork>(teamId);
                        if (teamwork.FPackID == -1)
                        {
                            //新增新包材事项
                            BaseBll.CreateTaskData(teamId, user.FID, "9");
                            BaseBll.UpdateTeamProcess(teamId, (int)Constant.ProcessType.组装BOM包含新包材, 2, 1);
                        }
                        else
                        {
                            BaseBll.UpdateTeamProcess(teamId, (int)Constant.ProcessType.组装BOM包含新包材, 3, 2);
                        }
                        BaseBll.UpdateTeamProcess(teamwork.FID, (int)Constant.ProcessType.协同发起, 3, 2);
                        // 20230726 成品事项新增改到新增协同时创建
                        // BaseBll.UpdateTeamProcess(teamwork.FID, (int)Constant.ProcessType.成品视图, 2, 1);

                        SqlSugarClient db = AppSettingsHelper.GetSqlSugar();
                        //List<TFS_Material> TFS_Materials= db.Queryable<TFS_Material>().Where(m => m.FTestCode == teamwork.FTestCode).ToList();
                        // 新试验号时生成替代料事项
                        // teamwork的FBomJson字段不为空时判定为新试验号
                        if (!string.IsNullOrEmpty(teamwork.FBomJson) && teamwork.FBomJson.Length > 0) 
                        {
                            BaseBll.CreateTaskData(teamId, user.FID, "16");
                            BaseBll.UpdateTeamProcess(teamwork.FID, (int)Constant.ProcessType.替代品确认, 2, 1);
                        }
                    }
                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 保存视图编辑的内容
        /// </summary>
        [HttpPost]
        public ApiResult UpdateBatchById3(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    inParam.TryGetValue("TFS_ViewMaterial", out object viewObj);
                    inParam.TryGetValue("TFS_Material", out object materialObj);
                    inParam.TryGetValue("TFS_MaterialInfo", out object infoObj);
                    List<Dictionary<string, object>> viewList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(viewObj));
                    List<Dictionary<string, object>> materialList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(materialObj));
                    List<Dictionary<string, object>> infoList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(infoObj));
                    int teamId = int.Parse(inParam["FTeamID"].ToString());
                    int viewType = int.Parse(inParam["FViewType"].ToString());
                    apiResult.Data = _viewBll.UpdateBatchById3(viewList, materialList, infoList, teamId, viewType, user.FID);
                    List<int> ids = new List<int> { 2,3,4,5,10};
                    if (ids.Contains(viewType))
                    {
                        //// 创建物料视图事项
                        //TFS_HalfMaterialFTeamwork teamwork = BaseBll.GetTempModel<TFS_HalfMaterialFTeamwork>(teamId);
                        //List<Dictionary<string, object>> vml = _viewBll.GetHalfMaterialListByTeamId(teamId, viewType, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, true);
                        //Dictionary<int, string> hasNewView = new Dictionary<int, string>();

                        //if (vml != null)
                        //{
                        //    foreach (Dictionary<string, object> row in vml)
                        //    {
                        //        int materialType = (int)(long)row["FViewType"];
                        //        string factoryId = row["FFactoryID"].ToString();

                        //        if (ids.Contains(materialType))
                        //        {
                        //            if (hasNewView.ContainsKey(materialType))
                        //            {
                        //                hasNewView[materialType] = hasNewView[materialType] + factoryId + ",";
                        //            }
                        //            else
                        //            {
                        //                hasNewView.Add(materialType, factoryId + ",");
                        //            }
                        //        }
                        //    }
                        //    HalfMaterialTeamworkBll TeamworkBll = new HalfMaterialTeamworkBll();
                        //    TeamworkBll.CreateMaterialTask(hasNewView, teamwork, user.FID);
                        //}
                        HalfMaterialTaskBll halfMaterialTaskBll = new HalfMaterialTaskBll();
                        halfMaterialTaskBll.CloseHalfMaterialTask(teamId, user.FID, (int)Constant.HalfMaterialProcessType.物料分类);
                        BaseBll.CreateTaskData2(teamId, user.FID, "2");

                        BaseBll.UpdateTeamProcess2(teamId, (int)Constant.HalfMaterialProcessType.物料分类, 2, 2);
                        BaseBll.UpdateTeamProcess2(teamId, (int)Constant.HalfMaterialProcessType.物料编辑, 2, 1);
                        
                    }
                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 保存视图编辑的内容 更换试验号结束
        /// </summary>
        [HttpPost]
        public ApiResult UpdateBatchById4(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    inParam.TryGetValue("TFS_ViewMaterial", out object viewObj);
                    inParam.TryGetValue("TFS_Material", out object materialObj);
                    inParam.TryGetValue("TFS_MaterialInfo", out object infoObj);
                    List<Dictionary<string, object>> viewList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(viewObj));
                    List<Dictionary<string, object>> materialList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(materialObj));
                    List<Dictionary<string, object>> infoList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(infoObj));
                    int teamId = int.Parse(inParam["FTeamID"].ToString());
                    int viewType = int.Parse(inParam["FViewType"].ToString());
                    apiResult.Data = _viewBll.UpdateBatchById3(viewList, materialList, infoList, teamId, viewType, user.FID);
                    List<int> ids = new List<int> { 2, 3, 4, 5, 10 };
                    if (ids.Contains(viewType))
                    {
                        // 创建物料视图事项
                        TFS_HalfMaterialFTeamwork teamwork = BaseBll.GetTempModel<TFS_HalfMaterialFTeamwork>(teamId);

                        //BaseBll.UpdateTeamProcess2(teamwork.FID, (int)Constant.HalfMaterialProcessType.物料编辑, 2, 2);
                        HalfMaterialTaskBll halfMaterialTaskBll= new HalfMaterialTaskBll();

                        if (inParam["FType"].ToString() == "2")
                        {
                            BaseBll.UpdateTeamProcess2(teamwork.FID, (int)Constant.HalfMaterialProcessType.物料编辑, 2, 2);

                            TFS_HalfMaterialTask tFS_HalfMaterialTask = BaseBll.GetTempModel<TFS_HalfMaterialTask>(string.Format("FTeamID={0} AND FType=3", teamId));
                            halfMaterialTaskBll.CloseHalfMaterialTask2(teamId, user.FID, (int)Constant.HalfMaterialProcessType.物料编辑);
                            if (tFS_HalfMaterialTask == null) 
                            {
                                BaseBll.CreateTaskData2(teamwork.FID, user.FID, "3");
                            }

                        }
                        else if (inParam["FType"].ToString() == "3")
                        {
                            BaseBll.UpdateTeamProcess2(teamwork.FID, (int)Constant.HalfMaterialProcessType.物料确认, 2, 2);

                            halfMaterialTaskBll.CloseHalfMaterialTask(teamId, user.FID, (int)Constant.HalfMaterialProcessType.物料编辑);

                            halfMaterialTaskBll.CloseHalfMaterialTask(teamId, user.FID, (int)Constant.HalfMaterialProcessType.物料确认);

                            HalfMaterialTeamworkBll halfMaterialTeamworkBll = new HalfMaterialTeamworkBll();
                            halfMaterialTeamworkBll.ExecSql(string.Format("update TFS_HalfMaterialFTeamwork set FState=2 Where FID={0}", teamId));

                        }


                    }
                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 保存视图编辑的内容（物料新增条线）
        /// </summary>
        [HttpPost]
        public ApiResult UpdateMaterialViewById(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            BaseBll BaseBll = new BaseBll();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    inParam.TryGetValue("TFS_ViewMaterial", out object viewObj);
                    inParam.TryGetValue("TFS_Material", out object materialObj);
                    inParam.TryGetValue("TFS_MaterialInfo", out object infoObj);
                    List<Dictionary<string, object>> viewList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(viewObj));
                    List<Dictionary<string, object>> materialList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(materialObj));
                    List<Dictionary<string, object>> infoList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(infoObj));
                    int teamId = int.Parse(inParam["FTeamID"].ToString());
                    int viewType = int.Parse(inParam["FViewType"].ToString());
                    apiResult.Data = _viewBll.UpdateMaterialViewById(viewList, materialList, infoList, teamId, viewType, user.FID);

                    if (viewType == 10)
                    {
                        // 创建物料视图事项
                        TFS_FTeamwork teamwork = BaseBll.GetTempModel<TFS_FTeamwork>(teamId);
                        List<Dictionary<string, object>> vml = _viewBll.GetMaterialViewsByTeamId(teamId, viewType, 1, user.FID, out List<int> materialId, out string FGuaranteePeriod, out string FStorageConditions, !inParam.ContainsKey("FAllView"));
                        Dictionary<int, string> hasNewView = new Dictionary<int, string>();

                        if (vml != null)
                        {
                            foreach (Dictionary<string, object> row in vml)
                            {
                                int materialType = (int)(long)row["FViewType"];
                                string factoryId = row["FFactoryID"].ToString();

                                if (hasNewView.ContainsKey(materialType))
                                {
                                    hasNewView[materialType] = hasNewView[materialType] + factoryId + ",";
                                }
                                else
                                {
                                    hasNewView.Add(materialType, factoryId + ",");
                                }
                            }

                            hasNewView.OrderBy(s => s.Key);
                            string facoryIds = "";
                            foreach (var item in hasNewView)
                            {
                                //创建视图事项
                                string factorys = item.Value.Trim(',');
                                BaseBll.CreateTaskData(teamId, user.FID, "0", factorys);
                                facoryIds += factorys;
                            }
                        }
                        
                    }
                }
            }, apiResult, Request);
        }
    }
}
