using System;
using System.Collections.Generic;
using System.Web.Http;
using FactorySystemApi.Sap_Group;
using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.EnumModel;
using FactorySystemModel.RequestModel;
using FactorySystemModel.ResponseModel;
using FactorySystemModel.SqlSugarModel;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 任务
    /// </summary>
    [UserLoginFilter]
    public class TaskController : ApiController
    {
        private readonly TaskBll _taskBll = new TaskBll();

        /// <summary>
        /// 根据当前用户获取任务列表
        /// </summary>
        [HttpPost]
        public ApiResult GetPageList(TaskQuery tq)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (tq.FIsUser && Request.Properties["token"] is ApiAuthInfo user)
                {
                    tq.FUserID = user.FID.ToString();
                }
                apiResult.Data = new
                {
                    List = _taskBll.GetList(tq, out var totalNumber),
                    Total = totalNumber
                };
            }, apiResult, Request);
        }

        /// <summary>
        /// 物料组复核
        /// </summary>
        [HttpPost]
        public ApiResult ReviewMaterialGroup(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                apiResult.Data = _taskBll.ReviewMaterialGroup(inParam, user.FID);
            }, apiResult, Request);
        }

        /// <summary>
        /// 组编号申请
        /// </summary>
        [HttpPost]
        public ApiResult DockMaterialGroup(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = 0;
                List<TFS_ViewMaterial> viewList = _taskBll.GetDockGroupView(inParam);
                if (viewList.Count > 0)
                {
                    ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                    try
                    {
                        List<Sap_Group.dt_pp071_reqHEAD> itemList = new List<Sap_Group.dt_pp071_reqHEAD>();
                        foreach (TFS_ViewMaterial view in viewList)
                        {
                            TFS_Material material = BaseBll.GetTempModel<TFS_Material>(view.FMaterialID);
                            Sap_Group.dt_pp071_reqHEAD reqHead = new Sap_Group.dt_pp071_reqHEAD
                            {
                                WERKS = view.FFactoryCode,//工厂
                                DATUV = "20210101",//生效日期
                                MATNR = string.IsNullOrEmpty(view.FBaseMaterialCode) ? material.FCode : view.FBaseMaterialCode,//物料
                                PLNAL = "1",//组计数器
                                VERWE = "1",//用途
                                STATU = "4",//状态
                                LOSVN = "0",//从批量
                                LOSBS = "99999999",//到批量
                                KTEXT = material.FCraftPathDesc,//工艺路线描述  
                                ITEM = new Sap_Group.dt_pp071_reqHEADITEM[1]
                            };
                            bool is4 = view.FViewType == (int)Constant.ViewType.香基视图;
                            reqHead.ITEM[0] = new Sap_Group.dt_pp071_reqHEADITEM()
                            {
                                BMSCH = view.FViewType == (int)Constant.ViewType.成品视图 ? "100" : "100000", //基本数量
                                PLNME = view.FViewType == (int)Constant.ViewType.成品视图 ? "KG" : "G", //工序单位
                                VORNR = "0010", //工序编号
                                ARBPL = material.FWorkCenter, //工作中心
                                STEUS = "ZP01", //控制码
                                LTXA1 = material.FCraftDesc, //工序描述
                                VGW01 = is4 ? "0.01" : "1", //人工（直接）
                                VGE01 = "H", //人工直接工时单位
                                VGW02 = "", // 人工（间接）?
                                VGE02 = "", //人工间接工时单位?
                                VGW03 = "", //机器工时
                                VGE03 = "H", //机器工时单位
                                VGW04 = is4 ? "0.01" : "100", //电
                                VGE04 = "KWH", //电单位
                                VGW05 = "", //水?
                                VGE05 = "", //水单位?
                                VGW06 = is4 ? "0.01" : "100", //蒸汽
                                VGE06 = "TO", //蒸汽单位
                                VGW07 = is4 ? "0.01" : "100", //物耗仓储运输
                                VGE07 = "H", //物耗仓储运输单位
                                VGW08 = is4 ? "0.01" : "100", //其他
                                VGE08 = "H", //其他单位
                                VGW09 = "", //环保支出?
                                VGE09 = "", //环保支出单位?
                            };
                            itemList.Add(reqHead);
                        }
                        Sap_Group.si_pp071_mcs_senderService sapService = new Sap_Group.si_pp071_mcs_senderService()
                        {
                            Credentials = new System.Net.NetworkCredential()
                            {
                                UserName = AppSettingsHelper.GetAppSettingVal("Sap_UserName"),
                                Password = AppSettingsHelper.GetAppSettingVal("Sap_Password")
                            }
                        };
                        Sap_Group.dt_pp071_req reqDatas = new Sap_Group.dt_pp071_req()
                        {
                            SOURCESYS = "MCS",
                            TARGETSYS = "SAP",
                            UPDATETIME = DateTime.Now.ToString("yyyyMMddHHmmss"),
                            HEAD = itemList.ToArray()
                        };
                        Sap_Group.dt_pp071_resDATA[] resData = sapService.si_pp071_mcs_sender(reqDatas);
                        ExceptionHelper.AddSystemJournal(Request, reqDatas, resData);
                        for (int i = 0; i < viewList.Count; i++)
                        {
                            viewList[i].FGroupCode = (string.IsNullOrEmpty(resData[i].PLNNR) || resData[i].PLNNR == "null") ? "" : resData[i].PLNNR;
                        }
                        if (viewList.Find(s => string.IsNullOrEmpty(s.FGroupCode)) == null)
                        {
                            OperateLogBll.Add(2, viewList[0].FTeamID, (int)Constant.TaskType.组编号申请, "组编号申请对接成功", user.FID);
                            apiResult.Data = _taskBll.DockMaterialGroup(viewList, user.FID);
                        }
                        else
                        {
                            string errorMsg = "";
                            foreach (dt_pp071_resDATA res in resData)
                            {
                                errorMsg += res.MATNR + " ：" + res.MSGTX;
                            }
                            OperateLogBll.Add(2, viewList[0].FTeamID, (int)Constant.TaskType.组编号申请, "组编号申请对接失败：" + errorMsg + "。", user.FID);
                            apiResult.Data = 0;
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.WriteMessage("组编号申请对接失败：" + ex.Message, 1);
                        OperateLogBll.Add(2, viewList[0].FTeamID, (int)Constant.TaskType.组编号申请, "组编号申请对接失败:" + ex.Message, user.FID);
                    }
                }
            }, apiResult, Request, inParam);
        }


        /// <summary>
        /// 确认流程完成
        /// </summary>
        [HttpPost]
        public ApiResult SureTeamWork(Dictionary<string, object> inParam)
        {
            ApiResult apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                ApiAuthInfo user = Request.Properties["token"] as ApiAuthInfo;
                apiResult.Data = _taskBll.SureTeamWork(int.Parse(inParam["FTeamID"].ToString()));
            }, apiResult, Request);
        }
    }
}
