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;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 物料分类接口
    /// </summary>
    [UserLoginFilter]
    public class MaterialTypeController : BaseController<TFS_MaterialType>
    {
        /// <summary>
        /// 数据处理层
        /// </summary>
        public readonly MaterialTypeBll MaterialTypeBll = new MaterialTypeBll();
        /// <summary>
        /// 初始化
        /// </summary>
        public MaterialTypeController()
        {

        }

        /// <summary>
        /// 获取信息数据
        /// </summary>
        [HttpPost]
        public ApiResult GetInfoData(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (inParam.ContainsKey("FDataID"))
                {
                    int dataId = int.Parse(inParam["FDataID"].ToString());
                    int dataType = int.Parse(inParam["FType"].ToString());
                    string sqlWhere = string.Format("FDataID={0} and FType={1}", dataId, dataType);
                    apiResult.Data = BaseBll.GetTempModel<TFS_MaterialInfo>(sqlWhere);
                }
                else if (inParam.ContainsKey("FType")) 
                {
                    int dataType = int.Parse(inParam["FType"].ToString());
                    string sqlWhere = string.Format(" FType={0}", dataType);
                    apiResult.Data = BaseBll.GetTempModel<TFS_MaterialInfo>(sqlWhere);
                }
              
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// 修改信息数据
        /// </summary>
        [HttpPost]
        public ApiResult ChangeInfoData(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                inParam.Remove("FAddUser");
                inParam.Remove("FAddDate");
                inParam.Remove("FEditUser");
                inParam.Remove("FEditDate");
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                if (inParam.ContainsKey("FID"))
                {
                    inParam.Add("FEditUser", user.FID);
                    inParam.Add("FEditDate", DateTime.Now);
                    apiResult.Data = BaseBll.UpdateDataModel(inParam, "TFS_MaterialInfo");
                }
                else
                {
                    inParam.Add("FEditUser", user.FID);
                    inParam.Add("FAddDate", DateTime.Now);
                    apiResult.Data = BaseBll.InsertDataModel(inParam, "TFS_MaterialInfo");
                }
            }, apiResult, Request, inParam);
        }


        /// <summary>
        /// 模板上传处理（重构父方法）
        /// </summary>
        protected override object CheckUploadFile(List<string> fileList, int funcType, int userId)
        {
            if (funcType == 1)
            {
                GetMaterialTypeFromFile(fileList, out List<TFS_MaterialInfo> mainList, out List<PropertyInfo> mainProp);
                return MaterialTypeBll.InsertBatchMaterialTypeData(mainList, mainProp, userId);
            }
            return fileList;
        }

        /// <summary>
        /// 获取分类信息
        /// </summary>
        private void GetMaterialTypeFromFile(List<string> fileList, out List<TFS_MaterialInfo> mainList, out List<PropertyInfo> mainProp)
        {
            mainList = new List<TFS_MaterialInfo>();
            List<TFS_FieldInfo> fieldList = BaseBll.GetFileInfoList((int)Constant.FieldInfoType.物料信息补充模板导入);
            mainProp = typeof(TFS_MaterialInfo).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_MaterialInfo main = new TFS_MaterialInfo();
                    foreach (TFS_FieldInfo field in fieldList)
                    {
                        string value = GetValueByName(dr, items, field.FFieldName, field.FDefault);
                        if ((temp = mainProp.Find(s => s.Name.Equals(field.FColumnFIeld))) != null) temp.SetValue(main, value);
                    }
                    {
                        //一二级分类处理
                        if (string.IsNullOrEmpty(main.FQualityTest2)) main.FQualityTest2 = "";
                        TFS_FieldInfo type1 = fieldList.Find(s => s.FColumnFIeld == "FTypeName1");
                        string name = type1 != null ? GetValueByName(dr, items, type1.FFieldName, type1.FDefault) : "";
                        if (string.IsNullOrEmpty(name)) continue;
                        main.FQualityTest2 += "&$&||&$&" + name;

                        type1 = fieldList.Find(s => s.FColumnFIeld == "FTypeName2");
                        name = type1 != null ? GetValueByName(dr, items, type1.FFieldName, type1.FDefault) : "";
                        if (string.IsNullOrEmpty(name)) continue;
                        main.FQualityTest2 += "&$&||&$&" + name;
                    }
                    mainList.Add(main);
                }
            }
        }
    }
}