using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.EnumModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web.Http;
using FactorySystemModel.RequestModel;
using System.Reflection;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using System.Linq;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 协同接口
    /// </summary>
    [UserLoginFilter]
    public class MaterialTeamworkController : ApiController {
        /// <summary>
        /// 数据处理层
        /// </summary>
        public readonly BaseBll BaseBll = new BaseBll();
        /// <summary>
        /// 数据处理层-路线处理
        /// </summary>
        private readonly MaterialTeamworkBll MaterialTeamworkBll = new MaterialTeamworkBll();
        /// <summary>
        /// 数据处理层-任务处理
        /// </summary>
        private readonly MaterialTaskBll MaterialTaskBll = new MaterialTaskBll();
        /// <summary>
        /// 事项操作日志
        /// </summary>
        private readonly OperateLogBll OperateLogBll = new OperateLogBll();
        /// <summary>
        /// 初始化
        /// </summary>

        private readonly BaseController<TFS_FMaterialTeamwork> baseController = new BaseController<TFS_FMaterialTeamwork>();

        public MaterialTeamworkController()
        {
        }

        #region 物料新增
        /// <summary>
        /// 新增物料路线
        /// </summary>
        [HttpPost]
        public ApiResult CreateMaterial(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                TFS_Factory factory = BaseBll.GetTempModel<TFS_Factory>(int.Parse(inParam["FCreateFactoryID"].ToString()));
                Dictionary<string, object> result = new Dictionary<string, object>();

                inParam.Remove("FID");

                string materialName = inParam["FMaterialName"].ToString();

                TFS_Material existMaterial = BaseBll.GetTempModel<TFS_Material>("FName='" + materialName + "'");

                if (existMaterial != null)
                {
                    result.Add("TaskId", -8);
                }
                else
                {
                    inParam.TryGetValue("FState", out object state);
                    if (null == state)
                    {
                        inParam["FState"] = state = 1;
                    }

                    if (inParam.ContainsKey("FAddUser"))
                    {
                        inParam["FAddUser"] = user.FID;
                    }
                    else
                    {
                        inParam.Add("FAddUser", user.FID);
                    }

                    if (inParam.ContainsKey("FAddDate"))
                    {
                        inParam["FAddDate"] = DateTime.Now;
                    }
                    else
                    {
                        inParam.Add("FAddDate", DateTime.Now);
                    }

                    if (inParam.ContainsKey("FEditUser"))
                    {
                        inParam["FEditUser"] = user.FID;
                    }
                    else
                    {
                        inParam.Add("FEditUser", user.FID);
                    }

                    if (inParam.ContainsKey("FEditDate"))
                    {
                        inParam["FEditDate"] = DateTime.Now;
                    }
                    else
                    {
                        inParam.Add("FEditDate", DateTime.Now);
                    }

                    if (inParam.ContainsKey("FCreateFactoryID"))
                    {
                        inParam.Remove("FCreateFactoryID");
                    }
                    inParam.Add("FCreateFactoryID", factory.FID);
                    inParam.Add("FCreateFactoryCode", factory.FCode);
                    inParam.Add("FCreateFactoryType", factory.FType);
                    if (factory.FType != (int)Constant.FactoryType.单工厂)
                    {
                        TFS_Factory prodFactory = BaseBll.GetTempModel<TFS_Factory>(factory.FFactoryID);
                        inParam.Add("FProdFactoryID", prodFactory.FID);
                        inParam.Add("FProdFactoryCode", prodFactory.FCode);
                    }
                    else
                    {
                        inParam.Add("FProdFactoryID", factory.FID);
                        inParam.Add("FProdFactoryCode", factory.FCode);
                    }

                    inParam.Add("FTeamworkType", 1);

                    // 获取具备相应权限的用户
                    List<TUser> users = MaterialTaskBll.GetTaskUsers(0, "10", factory.FID);

                    // 如果没有获取到用户，则不创建路线、任务、物料和视图
                    if (users != null && users.Count > 0)
                    {
                        int teamId = BaseBll.InsertDataModel(inParam, "TFS_FMaterialTeamwork");
                        result.Add("TeamId", teamId);

                        if (teamId > 0)
                        {
                            inParam.Add("FID", teamId);

                            if (state.ToString().Contains("1"))
                            {
                                TFS_FMaterialTeamwork teamwork = BaseBll.GetTempModel<TFS_FMaterialTeamwork>(teamId);

                                // 创建物料和物料视图
                                Dictionary<string, object> materialInfo = CreateMaterialData(inParam, factory, teamwork);

                                if (materialInfo.ContainsKey("FMaterialCode") && !string.IsNullOrEmpty(materialInfo["FMaterialCode"].ToString()))
                                {
                                    teamwork.FMaterialCode = materialInfo["FMaterialCode"].ToString();
                                    MaterialTeamworkBll.UpdateMaterialTeamwork(teamwork);
                                }

                                foreach (string key in materialInfo.Keys)
                                {
                                    result.Add(key, materialInfo[key]);
                                }

                                // 创建物料分类任务
                                int taskId = MaterialTaskBll.CreateMaterialTask(teamId, 1, user.FID, 0, factory.FID, users);
                                result.Add("TaskId", taskId);

                                OperateLogBll.Add(3, teamwork.FID, 17, "物料新增路线创建成功", user.FID);
                            }
                        }
                    }
                    else
                    {
                        result.Add("TaskId", -9);
                    }
                }

                apiResult.Data = result;
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// 查询物料路线
        /// </summary>
        [HttpPost]
        public ApiResult GetPageList(MaterialTeamworkQuery mtq)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (mtq.FIsUser && Request.Properties["token"] is ApiAuthInfo user)
                {
                    mtq.FUserID = user.FID;
                }

                List<object> powerList = MaterialTeamworkBll.GetViewPower(mtq.FUserID);
                List<MaterialTeamworkRow> list = MaterialTeamworkBll.GetList(mtq, out var totalNumber);
                int total = totalNumber;

                if (list != null && list.Count > 0)
                {
                    foreach(MaterialTeamworkRow row in list)
                    {
                        row.FIsShowView = false;
                        row.FIsDownloadView = false;

                        int factoryId = row.FCreateFactoryID;
                        List<object> viewPowers = powerList.FindAll(p => ((IDictionary<string, object>)p)["FFactoryID"].ToString().Equals(factoryId.ToString()) && ((IDictionary<string, object>)p)["FFunctionID"].ToString().Equals("1")).ToList();
                        List<object> operationPowers = powerList.FindAll(p => ((IDictionary<string, object>)p)["FFactoryID"].ToString().Equals(factoryId.ToString()) && ((IDictionary<string, object>)p)["FFunctionID"].ToString().Equals("6")).ToList();

                        if (viewPowers != null && viewPowers.Count > 0) row.FIsShowView = true;
                        if (operationPowers != null && operationPowers.Count > 0) row.FIsDownloadView = true;
                    }
                }

                apiResult.Data = new
                {
                    List = list,
                    Total = total
                };
            }, 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 teamWorkType = int.Parse(inParam["teamWorkType"].ToString());
                    int teamType = int.Parse(inParam["teamType"].ToString());

                    apiResult.Data = new
                    {
                        columns = MaterialTeamworkBll.GetColumns(),
                        rows = MaterialTeamworkBll.GetMaterialViewsByTeamId(teamId, teamWorkType, teamType, user.FID, true, out List<int> materialId),
                        infos = MaterialTeamworkBll.GetMaterialInfoList(materialId, user.FID),
                        types = MaterialTeamworkBll.GetMaterialTypeList(),
                        viewCols = MaterialTeamworkBll.GetViewColumns()
                    };

                }
            }, apiResult, Request, inParam);
        }

        /// <summary>
        /// 更新物料
        /// </summary>
        [HttpPost]
        public ApiResult UpdateMaterial(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            int step = -1;
            Dictionary<string, object> result = new Dictionary<string, object>();

            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 teamworkType = int.Parse(inParam["FTeamworkType"].ToString());
                    int taskType = int.Parse(inParam["FTaskType"].ToString());

                    string viewType = GetViewType(viewList);

                    // 更新视图
                    int materialType = MaterialTeamworkBll.UpdateMaterialViewById(viewList, user.FID, teamId, teamworkType);
                    // 更新物料
                    string materialCode = MaterialTeamworkBll.UpdateMaterialById(materialList, user.FID, teamId, teamworkType);
                    // 更新物料信息
                    MaterialTeamworkBll.UpdateMaterialInfoById(infoList, user.FID, teamId, teamworkType);

                    TFS_FMaterialTeamwork teamwork = MaterialTeamworkBll.GetMaterialTeamworkById(teamId);
                    teamwork.FMaterialType = materialType.ToString();
                    teamwork.FMaterialCode = materialCode.ToString();

                    if (materialList != null)
                    {
                        int mindex = materialList.Count - 1;

                        teamwork.FMaterialName = materialList[mindex]["FName"].ToString();
                    }

                    MaterialTeamworkBll.UpdateMaterialTeamwork(teamwork);

                    List<TFS_FMaterialTask> tasks = MaterialTaskBll.GetMaterialTasks(teamId);

                    TFS_FMaterialTask task = null;

                    if (taskType == 2)
                    {
                        TFS_FMaterialTask currentTask = tasks.Find(t => t.FType == 2);
                        // 结束物料确认任务
                        MaterialTaskBll.CloseAllMaterialTask(teamId, user.FID);
                        // 结束物料路线
                        MaterialTeamworkBll.CloseMaterialTeamwork(teamId, user.FID);

                        result.Add("TaskId", currentTask.FID);
                    }
                    else if(taskType == 1)
                    {
                        TFS_FMaterialTask currentTask = tasks.Find(t => t.FType == 1);
                        List<TUser> users = MaterialTaskBll.GetTaskUsers(2, viewType, currentTask.FFactoryID);

                        if (users != null && users.Count > 0)
                        {
                            // 结束物料编辑任务
                            MaterialTaskBll.CloseMaterialTask(teamId, user.FID, 1);
                            TFS_FMaterialTask nextTask = tasks.Find(t => t.FType == 2);

                            if (nextTask == null)
                            {
                                // 创建物料确认任务
                                int taskId = MaterialTaskBll.CreateMaterialTask(teamId, teamworkType, user.FID, 2, currentTask.FFactoryID, users);
                                result.Add("TaskId", taskId);
                            }
                            else
                            {
                                result.Add("TaskId", nextTask.FID);
                            }
                        }
                        else
                        {
                            result.Add("TaskId", -9);
                        }
                        
                    }
                    else if (taskType == 0)
                    {
                        TFS_FMaterialTask currentTask = tasks.Find(t => t.FType == 0);
                        List<TUser> users = MaterialTaskBll.GetTaskUsers(1, viewType, currentTask.FFactoryID);

                        if (users != null && users.Count > 0)
                        {
                            // 结束物料分类任务
                            MaterialTaskBll.CloseMaterialTask(teamId, user.FID, 0);
                            TFS_FMaterialTask nextTask = tasks.Find(t => t.FType == 1);

                            if (nextTask == null)
                            {
                                // 创建物料编辑任务
                                int taskId = MaterialTaskBll.CreateMaterialTask(teamId, teamworkType, user.FID, 1, currentTask.FFactoryID, users);
                                result.Add("TaskId", taskId);
                            }
                            else
                            {
                                result.Add("TaskId", nextTask.FID);
                            }                            
                        }
                        else
                        {
                            result.Add("TaskId", -9);
                        }
                    }

                    result.Add("TeamId", teamId);
                    apiResult.Data = result;

                }
            }, apiResult, Request, inParam);
            
        }
        
        private Dictionary<string, object> CreateMaterialData(Dictionary<string, object> inParam, TFS_Factory factory, TFS_FMaterialTeamwork teamwork)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            // 创建物料（物料表新增数据）
            TFS_Material material = new TFS_Material();
            material.FName = inParam["FMaterialName"].ToString(); // 物料名称
            material.FDesc = inParam["FMaterialName"].ToString(); // 物料描述
            material.FMaterialGroup = inParam["FMaterialGroup"].ToString(); // 物料组
            material.FBaseUnit = inParam["FWeightUnit"].ToString(); // 计量单位
            material.FFactoryID = factory.FFactoryID; // 工厂
            material.FFactoryCode = factory.FCode; // 工厂标识
            material.FTestCode = inParam.ContainsKey("FTestCode") ? inParam["FTestCode"].ToString() : ""; // 试验号

            // 需要获取MDM编码逻辑，在页面勾选了需要获取MDM编码时，调用获取MDM编码接口
            // 此处直接调用BaseController的GetMdmCode方法，inParam作为方法的输入参数
            // 必须要传递FWeightUnit，FTestCode，FMaterialGroup/FGroup，FSaleCode/FName，FType/FMaterialType五个参数
            // 其中FMaterialType传入固定值ZMAT，FTestCode非必填，其他参数必填
            // 此处FWeightUnit，FTestCode，FMaterialGroup，添加FMaterialType为ZMAT已有，添加FName为FMaterialName
            bool FIsRaw = (bool)inParam["FIsRaw"];
            if (FIsRaw)
            {
                // 添加物料名称属性
                Dictionary<string, object> temp = new Dictionary<string, object>
                {
                    { "FName", inParam["FMaterialName"] },
                    { "FGroup", inParam["FMaterialGroup"] },
                    { "FWeightUnit", inParam["FWeightUnit"] },
                    { "FType", "ZMAT" }
                };
                if (!string.IsNullOrEmpty(material.FTestCode))
                {
                    temp.Add("FTestCode", material.FTestCode);
                }

                string FCode = baseController.GetMdmCode(temp);
                material.FCode = FCode;
                result.Add("FMaterialCode", FCode);
            }
            else
            {
                string FCode = inParam["FMaterialCode"].ToString();
                material.FCode = FCode;
            }

            int materialId = MaterialTeamworkBll.InsertMaterial(material);

            result.Add("MaterialId", materialId);

            // 创建物料视图
            TFS_ViewMaterial viewMaterial = new TFS_ViewMaterial();
            viewMaterial.FTeamID = teamwork.FID; // 路线ID
            viewMaterial.FMaterialID = materialId; // 物料ID
            viewMaterial.FFactoryID = teamwork.FCreateFactoryID; // 工厂ID
            viewMaterial.FFactoryCode = teamwork.FCreateFactoryCode; // 工厂Code
            viewMaterial.FAddDate = DateTime.Now; // 创建日期
            viewMaterial.FTeamType = 1; // 路线类型
            viewMaterial.FBaseMaterialDesc = material.FName; // 物料描述
            viewMaterial.FBaseMaterialCode = material.FCode; // 物料号
            viewMaterial.FBaseTestCode = material.FTestCode; // 试验号
            viewMaterial.FBaseMaterialGroup = material.FMaterialGroup; // 物料组
            viewMaterial.FBaseBasicMeter = material.FBaseUnit; // 基本计量

            int vmId = MaterialTeamworkBll.InsertMaterialView(viewMaterial);
            result.Add("ViewId", vmId);

            // 创建委托工厂视图
            if (!teamwork.FCreateFactoryID.Equals(teamwork.FProdFactoryID))
            {
                viewMaterial = new TFS_ViewMaterial();
                viewMaterial.FTeamID = teamwork.FID; // 路线ID
                viewMaterial.FMaterialID = materialId; // 物料ID
                viewMaterial.FFactoryID = teamwork.FProdFactoryID; // 工厂ID
                viewMaterial.FFactoryCode = teamwork.FProdFactoryCode; // 工厂Code
                viewMaterial.FAddDate = DateTime.Now; // 创建日期
                viewMaterial.FTeamType = 1; // 路线类型
                viewMaterial.FBaseMaterialDesc = material.FName; // 物料描述
                viewMaterial.FBaseMaterialCode = material.FCode; // 物料号
                viewMaterial.FBaseTestCode = material.FTestCode; // 试验号
                viewMaterial.FBaseMaterialGroup = material.FMaterialGroup; // 物料组
                viewMaterial.FBaseBasicMeter = material.FBaseUnit; // 基本计量

                int prodVmId = MaterialTeamworkBll.InsertMaterialView(viewMaterial);
                result.Add("ProdViewId", prodVmId);
            }

            return result;
        }
        #endregion

        #region 物料修改
        /// <summary>
        /// 物料修改路线
        /// </summary>
        [HttpPost]
        public ApiResult ModifyMaterial(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            Dictionary<string, int> result = new Dictionary<string, int>();
            Dictionary<string, object> teamworkParam = new Dictionary<string, object>();

            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;                
                TFS_Factory prodFactory = null;
                int factoryId = int.Parse(inParam["FCreateFactoryID"].ToString());
                int materialId = int.Parse(inParam["FMaterialId"].ToString());

                // 根据FID获取工厂和物料
                TFS_Factory factory = BaseBll.GetTempModel<TFS_Factory>(factoryId);
                TFS_Material material = BaseBll.GetTempModel<TFS_Material>(materialId);

                // 获取当前工厂视图
                TFS_ViewMaterial view = MaterialTeamworkBll.GetMaterialViewsByFactoryAndMaterial(factoryId, materialId);
                TFS_ViewMaterial prodView = null;

                // 当前物料和模式没有对应视图，则创建视图
                if (view == null)
                {
                    view = new TFS_ViewMaterial();
                    view.FMaterialID = materialId; // 物料ID
                    view.FAddDate = DateTime.Now; // 创建日期
                    view.FTeamType = 1; // 路线类型
                    view.FFactoryID = factory.FID; // 工厂ID
                    view.FFactoryCode = factory.FCode; // 工厂Code

                    int vmId = MaterialTeamworkBll.InsertMaterialView(view);
                    view.FID = vmId;
                    result.Add("ViewId", vmId);
                }

                string productType = view.FMRP1ProductType;
                string materialName = material.FName;
                string vType = GetViewType(productType, materialName);

                List<TUser> users = MaterialTaskBll.GetTaskUsers(1, vType, factory.FID);

                if (users == null || users.Count > 0)
                {
                    // 设置物料修改路线
                    teamworkParam.Add("FTeamworkType", 2); // 路线类型-修改
                    teamworkParam.Add("FState", 1); // 路线状态-进行中
                    teamworkParam.Add("FMaterialCode", material.FCode); // 物料编号
                    teamworkParam.Add("FMaterialName", material.FName); // 物料描述
                    teamworkParam.Add("FTestCode", material.FTestCode); // 试验号
                    teamworkParam.Add("FMaterialType", material.FType); // 物料类型（产品分类）：TBasicCode.FType=32
                    teamworkParam.Add("FMaterialGroup", material.FMaterialGroup); // 物料组：TDataCode.FType=2
                    teamworkParam.Add("FWeightUnit", material.FBaseUnit); // 计量单位
                    teamworkParam.Add("FAddUser", user.FID); // 创建用户
                    teamworkParam.Add("FAddDate", DateTime.Now); // 创建时间
                    teamworkParam.Add("FEditUser", user.FID); // 修改用户
                    teamworkParam.Add("FEditDate", DateTime.Now); // 修改时间
                    teamworkParam.Add("FCreateFactoryID", factory.FID); // 工厂ID
                    teamworkParam.Add("FCreateFactoryCode", factory.FCode); // 工厂Code 
                    teamworkParam.Add("FCreateFactoryType", factory.FType); // 工厂类型

                    // 如果当前模式是委托，获取委托工厂
                    if (factory.FType == 1)
                    {
                        int prodFactoryId = factory.FFactoryID;
                        prodFactory = BaseBll.GetTempModel<TFS_Factory>(prodFactoryId);

                        teamworkParam.Add("FProdFactoryID", prodFactory.FID); // 委托工厂ID
                        teamworkParam.Add("FProdFactoryCode", prodFactory.FCode); // 委托工厂Code

                        prodView = MaterialTeamworkBll.GetMaterialViewsByFactoryAndMaterial(prodFactoryId, materialId);

                        // 新增委托工厂视图
                        if (prodView == null)
                        {
                            prodView = Clone(view);
                            prodView.FFactoryID = prodFactoryId;
                            prodView.FFactoryCode = prodFactory.FCode;
                            prodView.FAddDate = DateTime.Now;

                            // 插入视图
                            int prodVmId = MaterialTeamworkBll.InsertMaterialView(prodView);
                            prodView.FID = prodVmId;

                            result.Add("ProdViewId", prodVmId);
                        }
                    }

                    // 创建物料修改路线
                    int teamId = BaseBll.InsertDataModel(teamworkParam, "TFS_FMaterialTeamwork");
                    result.Add("TeamId", teamId);

                    // 更新视图
                    view.FMdfMaterialTeamID = teamId;
                    view.FTeamType = 1;
                    MaterialTeamworkBll.UpdateMaterialView(view);

                    if (prodView != null)
                    {
                        prodView.FMdfMaterialTeamID = teamId;
                        prodView.FTeamType = 1;
                        MaterialTeamworkBll.UpdateMaterialView(prodView);
                    }

                    // 创建物料修改事项
                    int taskId = MaterialTaskBll.CreateMaterialTask(teamId, 2, user.FID, 1, factory.FID, users);
                    result.Add("TaskId", taskId);

                    OperateLogBll.Add(3, teamId, 18, "物料修改路线创建成功", user.FID);
                }
                else
                {
                    result.Add("TaskId", -9);
                }                

                apiResult.Data = result;

            }, apiResult, Request);
        }

        /// <summary>
        /// 根据工厂和物料名查找物料
        /// </summary>
        [HttpPost]
        public ApiResult SearchMaterialsByFactory(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();

            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                Dictionary<string, object> result = new Dictionary<string, object>();

                string searchName = inParam["FSearchName"].ToString();
                int pageNumber = 0;
                int pageSize = 0;

                int.TryParse(inParam["FPageIndex"].ToString(), out pageNumber);
                int.TryParse(inParam["FPageSize"].ToString(), out pageSize);

                List<TFS_Material> materials = MaterialTeamworkBll.SearchMaterialsByFactory(searchName, pageNumber, pageSize, out var totalNumber);
                result["List"] = materials;
                result["Total"] = totalNumber;
                apiResult.Data = result;

            }, apiResult, Request);
        }

        private Dictionary<string, int> CreateProdMaterialData(TFS_ViewMaterial createViewMaterial, TFS_FMaterialTeamwork teamwork)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();

            createViewMaterial.FFactoryID = teamwork.FProdFactoryID;
            createViewMaterial.FFactoryCode = teamwork.FProdFactoryCode; // 工厂Code

            result.Add("ViewId", createViewMaterial.FID);

            int prodVmId = MaterialTeamworkBll.InsertMaterialView(createViewMaterial);
            result.Add("ProdViewId", prodVmId);

            return result;
        }

        private string GetViewType(List<Dictionary<string, object>> viewList)
        {
            string vType = null;

            if (viewList != null && viewList.Count > 0)
            {
                Dictionary<string, object> view = viewList[0];
                // 成品视图
                if (view.ContainsKey("FMRP1ProductType") && "10".Equals(view["FMRP1ProductType"].ToString()))
                {
                    vType = "1";
                }
                // 半成品视图
                else if (view.ContainsKey("FMRP1ProductType") && "20".Equals(view["FMRP1ProductType"].ToString()))
                {
                    vType = "2";
                }
                // 中间品视图
                else if (view.ContainsKey("FMRP1ProductType") && "30".Equals(view["FMRP1ProductType"].ToString()))
                {
                    vType = "3";

                    // 香基视图
                    if (view.ContainsKey("FBaseMaterialDesc") && view["FBaseMaterialDesc"].ToString().Contains("香基"))
                    {
                        vType = "4";
                    }
                }
                // 原料视图
                else if (view.ContainsKey("FMRP1ProductType") && "40".Equals(view["FMRP1ProductType"].ToString()))
                {
                    vType = "5";
                }
            }

            return vType;
        }

        private string GetViewType(string viewType, string materialName)
        {
            string vType = null;

            // 成品视图
            if ("10".Equals(viewType))
            {
                vType = "1";
            }
            // 半成品视图
            else if ("20".Equals(viewType))
            {
                vType = "2";
            }
            // 中间品视图
            else if ("30".Equals(viewType))
            {
                vType = "3";

                // 香基视图
                if (materialName.Contains("香基"))
                {
                    vType = "4";
                }
            }
            // 原料视图
            else if ("40".Equals(viewType))
            {
                vType = "5";
            }

            return vType;
        }

        #endregion

        public T Clone<T>(T obj) where T : class
        {
            // 如果对象是 null，则返回 null
            if (obj == null)
            {
                return null;
            }

            Type type = obj.GetType();

            // 如果对象是字符串或值类型，则直接返回副本
            if (type.IsPrimitive || type == typeof(string))
            {
                return obj;
            }

            // 如果对象是数组，则创建一个新的数组并复制元素
            if (type.IsArray)
            {
                Array sourceArray = obj as Array;
                Array destinationArray = sourceArray.Clone() as Array;
                for (int i = 0; i < sourceArray.Length; i++)
                {
                    destinationArray.SetValue(Clone(sourceArray.GetValue(i)), i);
                }
                return destinationArray as T;
            }

            // 否则，创建一个新对象并复制属性值
            object result = Activator.CreateInstance(type);
            foreach (FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                object fieldValue = field.GetValue(obj);
                field.SetValue(result, Clone(fieldValue));
            }
            foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (!property.CanWrite || !property.CanRead)
                {
                    continue;
                }
                object propertyValue = property.GetValue(obj);
                property.SetValue(result, Clone(propertyValue), null);
            }
            return result as T;
        }

        /// <summary>
        /// 下载SAP视图
        /// </summary>
        [HttpPost]
        public ApiResult DownMateialViewSAP(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();

            return ExceptionHelper.TryReturnException(() =>
            {
                if (inParam.ContainsKey("teamId") && inParam.ContainsKey("teamWorkType"))
                {
                    inParam.TryGetValue("teamId", out object teamworkId);
                    inParam.TryGetValue("teamWorkType", out object teamworkType);
                    inParam.TryGetValue("materialName", out object materialName);

                    string basePath = AppDomain.CurrentDomain.BaseDirectory.Trim('\\');
                    string savePath = basePath + string.Format("\\File\\Temp\\{0}_{1}\\", inParam["teamId"], "ViewSAP");
                    if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                    string tempPath = savePath.Replace("\\File\\Temp\\", "\\File\\View\\");
                    if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                    savePath += ".xlsx";

                    bool hasFinish = inParam.ContainsKey("FFinish");
                    if (hasFinish) savePath = savePath.Replace("\\File\\Temp\\", "\\File\\View\\");
                    if (!File.Exists(savePath) || !hasFinish)
                    {
                        CreateExeclFileSAP(materialName.ToString() + "_SAP视图", savePath, teamworkId.ToString(), teamworkType.ToString());
                    }

                    string url = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, "") + savePath.Replace(basePath, "").Replace("\\", "/").Replace(".xlsx", materialName.ToString() + "_SAP视图.xlsx");
                    apiResult.Data = url;
                }
                else
                {
                    apiResult.Error("视图信息获取失败");
                }

            }, apiResult, Request);
        }

        /// <summary>
        /// 下载视图
        /// </summary>
        [HttpPost]
        public ApiResult DownMateialView(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();

            return ExceptionHelper.TryReturnException(() =>
            {
                if (inParam.ContainsKey("teamId") && inParam.ContainsKey("teamWorkType") && inParam.ContainsKey("materialName"))
                {

                    inParam.TryGetValue("teamId", out object teamworkId);
                    inParam.TryGetValue("teamWorkType", out object teamworkType);
                    inParam.TryGetValue("materialName", out object materialName);

                    string basePath = AppDomain.CurrentDomain.BaseDirectory.Trim('\\');
                    string savePath = basePath + string.Format("\\File\\Temp\\{0}_{1}\\", inParam["teamId"], "View");
                    if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                    string tempPath = savePath.Replace("\\File\\Temp\\", "\\File\\View\\");
                    if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                    savePath += ".xlsx";

                    bool hasFinish = inParam.ContainsKey("FFinish");
                    if (hasFinish) savePath = savePath.Replace("\\File\\Temp\\", "\\File\\View\\");
                    if (!File.Exists(savePath) || !hasFinish)
                    {
                        CreateExeclFile(materialName.ToString() + "_全部视图", savePath, teamworkId.ToString(), teamworkType.ToString());
                    }

                    string url = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, "") + savePath.Replace(basePath, "").Replace("\\", "/").Replace(".xlsx", materialName.ToString() + "_全部视图.xlsx");
                    apiResult.Data = url;
                }
                else
                {
                    apiResult.Error("视图信息获取失败");
                }

            }, apiResult, Request);
        }

        private void CreateExeclFileSAP(string fType, string savePath, string teamworkId, string teamworkType)
        {
            DataTable dataList = new DataTable();

            dataList = MaterialTeamworkBll.GetViewMaterialSAP(teamworkId, teamworkType);
            NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath.Replace(".xlsx", fType + ".xlsx"));
        }

        private void CreateExeclFile(string fType, string savePath, string teamworkId, string teamworkType)
        {
            DataTable dataList = null;
            List<TFS_ViewMaterial> viewList = null;

            int teamId;
            int teamType;

            int.TryParse(teamworkId, out teamId);
            int.TryParse(teamworkType, out teamType);

            viewList = MaterialTeamworkBll.GetViewMaterialByTeamId(teamId, teamType);
            if (viewList != null && viewList.Count > 0)
            {
                int materialId = viewList[0].FMaterialID;
                if (teamType == 3) 
                {
                    List<int> materialIds = viewList.Select(m => m.FMaterialID).ToList();
                    string ids = string.Join(",", materialIds);
                    dataList = MaterialTeamworkBll.GetViewMaterial(ids.ToString());
                    NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath.Replace(".xlsx", fType + ".xlsx"));
                }
                else 
                {
                    dataList = MaterialTeamworkBll.GetViewMaterial(materialId.ToString());
                    NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath.Replace(".xlsx", fType + ".xlsx"));
                }
                
            }
            
        }


    }
}
