using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using FactorySystemModel.EnumModel;
using FactorySystemModel.RequestModel;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 配方接口
    /// </summary>
    [UserLoginFilter]
    public class FormulaController : BaseController<TFS_Formula>
    {
        /// <summary>
        /// 数据处理层
        /// </summary>
        public readonly FormulaBll FormulaBll = new FormulaBll();
        /// <summary>
        /// 初始化
        /// </summary>
        public FormulaController()
        {
            //设置可修改字段
            UpdateField = "";
        }

        /// <summary>
        /// 更具试验号获取配方视图
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFormulaByFTestCode(Dictionary<string,object> data) 
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = FormulaBll.GetFormulaByFTestCode(data["code"].ToString());
            }, apiResult, Request);
        }
        /// <summary>
        /// 获取配方集合
        /// </summary>
        [HttpPost]
        public ApiResult GetFormulaList()
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = FormulaBll.GetFormulaList();
            }, apiResult, Request);
        }


        /// <summary>
        /// 分业请求
        /// </summary>
        [HttpPost]
        public ApiResult GetFormulaPageList(FormulaQuery fq)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = new
                {
                    List = FormulaBll.GetList(fq, out var totalNumber),
                    Total = totalNumber
                };
            }, apiResult, Request);
        }

        /// <summary>
        /// 对接配方数据（对方写入）
        /// </summary>
        [HttpPost]
        public ApiResult DockingRecipeData(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            apiResult.Data = 0;
            return ExceptionHelper.TryReturnException(() =>
            {
                if (inParam == null)
                {
                    apiResult.Error("未接收到参数");
                }
                else
                {

                    if (inParam.ContainsKey("SP")&&!inParam.ContainsKey("FPlmCode")) 
                    {
                        inParam.Add("FPlmCode", inParam["SP"].ToString());
                    }
                  
                    if (inParam.ContainsKey("SP_VERSION")&& !inParam.ContainsKey("FVersionCode")) 
                    {
                        //inParam.Add("FVersionCode", inParam["SP_VERSION"].ToString());

                        // 20230530 格式化传入的版本号
                        string sVersion = inParam["SP_VERSION"].ToString();
                        double dVersion;

                        bool isVersionNum = double.TryParse(sVersion, out dVersion);

                        if (isVersionNum)
                        {
                            sVersion = string.Format("{0:F4}", dVersion);
                        }

                        inParam.Add("FVersionCode", sVersion);
                    }
                   
                    if (inParam.ContainsKey("SP_VALUE")&&!inParam.ContainsKey("FTestCode")) 
                    {
                        inParam.Add("FTestCode", inParam["SP_VALUE"].ToString());
                    }

                    List<TFS_FieldInfo> fieldList = BaseBll.GetFileInfoList((int)Constant.FieldInfoType.配方模板导入);
                    TFS_Formula formula = new TFS_Formula();
                    List<PropertyInfo> propertys = formula.GetType().GetProperties().ToList();
                    foreach (var field in fieldList)
                    {
                        PropertyInfo temp = propertys.Find(s => s.Name == field.FColumnFIeld);
                        if (temp != null) temp.SetValue(formula, GetValueByName(inParam, field.FFieldName, field.FDefault));
                    }


                    if (inParam.ContainsKey("SP_AUTHOR")) 
                    {
                        formula.FConversionPersonnel = inParam["SP_AUTHOR"].ToString();
                    }
                    if (string.IsNullOrEmpty(formula.FPlmCode))
                    {
                        apiResult.Error("FPlmCode不能为空");
                    }
                    else if (string.IsNullOrEmpty(formula.FVersionCode))
                    {
                        apiResult.Error("FVersionCode不能为空");
                    }
                    else if (string.IsNullOrEmpty(formula.FName))
                    {
                        apiResult.Error("FName不能为空");
                    }
                    else if (string.IsNullOrEmpty(formula.FType))
                    {
                        apiResult.Error("FType不能为空");
                    }
                    /**
                     * 20230401 新增
                     * 接口新增：
                     * 转规格人员 FConversionPersonnel
                     * BOM版本号 FBomVersionCode
                     * **/
                    else if (string.IsNullOrEmpty(formula.FConversionPersonnel))
                    {
                        apiResult.Error("FConversionPersonnel不能为空");
                    }
                    else
                    {
                        int userId = -1;
                        if (Request.Properties.ContainsKey("token"))
                        {
                            userId = Request.Properties["token"] is ApiAuthInfo user ? user.FID : userId;
                            apiResult.Data = FormulaBll.DockingRecipeData(new List<TFS_Formula>() { formula }, userId);
                        }
                        else
                        {
                            apiResult.Error("token信息不存在");
                        }
                    }
                }
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// （对接）SAP配方同步
        /// </summary>
        [HttpPost]
        public ApiResult DockSapFormula()
        {
            ApiResult apiResult = new ApiResult
            {
                Data = 0
            };
            int result = 0;
            return ExceptionHelper.TryReturnException(() =>
            {
                Sap_Formula.dt_pp062_reqDATA[] reqDatas = new Sap_Formula.dt_pp062_reqDATA[1] {
                    new Sap_Formula.dt_pp062_reqDATA()
                    {
                        SOURCESYS = "MCS",
                        TARGETSYS = "SAP"
                    }
                };
                List<TFS_Factory> factoryList = FactoryBll.GetFactoryList();
                if (factoryList.Count > 0)
                {
                    ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                    Sap_Formula.si_pp062_bc_senderService sapService = new Sap_Formula.si_pp062_bc_senderService()
                    {
                        Credentials = new System.Net.NetworkCredential()
                        {
                            UserName = AppSettingsHelper.GetAppSettingVal("Sap_UserName"),
                            Password = AppSettingsHelper.GetAppSettingVal("Sap_Password")
                        }
                    };
                    foreach (TFS_Factory factory in factoryList)
                    {
                        reqDatas[0].UPDATETIME = DateTime.Now.ToString("yyyyMMddHHmmss");
                        reqDatas[0].WERKS = factory.FCode;
                        try
                        {
                            Sap_Formula.dt_pp062_res resData = sapService.si_pp062_bc_sender(reqDatas);
                            ExceptionHelper.AddSystemJournal(Request, reqDatas, resData);
                            List<TFS_Formula> formulaList = new List<TFS_Formula>();
                            if (resData != null && resData.DATA != null && resData.DATA.Length > 0)
                            {
                                foreach (var item in resData.DATA)
                                {
                                    formulaList.Add(new TFS_Formula()
                                    {
                                        FFactoryID = factory.FID,
                                        FFactoryCode = factory.FCode,
                                        FName = string.IsNullOrEmpty(item.MAKTX) ? "" : item.MAKTX,
                                        FTestCode = string.IsNullOrEmpty(item.MATNR) ? "" : item.MATNR,
                                        FAddDate = DateTime.Now,
                                        FEditUser = user.FID
                                    });
                                }
                            }
                            if (formulaList.Count > 0) result += FormulaBll.DockSapFormula(formulaList);
                        }
                        catch (Exception ex)
                        {
                            ExceptionHelper.AddSystemJournal(Request, reqDatas, ex.Message);
                        }
                    }
                }
                apiResult.Data = result;
            }, apiResult, Request, null);
        }

        #region 内部方法

        /// <summary>
        /// 模板上传处理（重构父方法）
        /// </summary>
        protected override object CheckUploadFile(List<string> fileList, int funcType, int userId)
        {
            if (funcType <= 1)
            {
                List<TFS_Formula> formulas = new List<TFS_Formula>();
                List<TFS_FieldInfo> fieldList = BaseBll.GetFileInfoList((int)Constant.FieldInfoType.配方模板导入);
                List<PropertyInfo> formulaProp = typeof(TFS_Formula).GetTypeInfo().GetProperties().ToList();
                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_Formula formula = new TFS_Formula();
                        foreach (var field in fieldList)
                        {
                            if ((temp = formulaProp.Find(s => s.Name.Equals(field.FColumnFIeld))) != null)
                            {
                                temp.SetValue(formula, GetValueByName(dr, items, field.FFieldName, field.FDefault));
                            }
                        }
                        formulas.Add(formula);
                    }
                }
                return FormulaBll.DockingRecipeData(formulas, userId);
            }
            return fileList;
        }

        #endregion
    }
}
