using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using RB_MES_API.Context;
using System.Data;
using RB_MES_API.Models;
using RB_MES_APICore.Context;
using RB_MES_API.Controllers.Cloud;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RB_MES_API.Models.Cloud;
using RB_MES_API.Models.Pangu;
using Nancy.Json;
using Kingdee.CDP.WebApi.SDK;
using Microsoft.IdentityModel.Tokens;
using RB_MES_APICore.Models.Request;
using RB_MES_APICore.Models.Responses;

namespace RB_MES_API.Controllers
{
    /// <summary>
    /// 用户首页
    /// </summary>
    public class HomeController : Controller
    {
        private readonly RBContext _context;
        private readonly MESContext _mesContext;
        private readonly IKDSqlHelper _kdsqlhelper;
        private readonly IChiledSelect _chiledSelect;
        private readonly IServiceScopeFactory _serviceScopeFactory;     //启动本地服务必须的注入

        /// <summary>
        /// 构造函数
        /// </summary>
        public HomeController(RBContext context, MESContext mesContext, IKDSqlHelper kdsqlhelper, IChiledSelect chiledSelect, IServiceScopeFactory serviceScopeFactory)
        {
            _context = context;
            _mesContext = mesContext;
            _kdsqlhelper = kdsqlhelper;
            _chiledSelect = chiledSelect;
            _serviceScopeFactory = serviceScopeFactory;
        }

        /// <summary>
        /// 验证用户密码
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task<string> UserPwd(string username, string pwd)
        {
            try
            {
                var sys = await _context.r_SystemProfiles!.Where(s => s.FCategoryID == 4).AsNoTracking().ToListAsync();
                var uname = sys.Where(s => s.FKey == "TokenUserName" && s.FValue == username);
                if (uname != null)
                {
                    var syspwd = sys.Where(s => s.FKey == "TokenPWD");
                    if (syspwd != null)
                    {
                        string md5pwd = syspwd.FirstOrDefault()!.FValue;
                        string md5eecrypt = AESHelp.Encrypt(pwd);
                        if (md5pwd != md5eecrypt)
                        {
                            return "密码不正确！";
                        }
                        else { return "OK"; }
                    }
                    else
                    {
                        return "系统参数配置不完整！";
                    }
                }
                else
                {
                    return "用户名不存在！";
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(string.Format("验证用户密码的UserPwd发生错误：{0}", ex.Message));
                return ex.Message;

            }
        }
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult Function(string? FFunctionName)
        {
            List<FunctionList> Function = _context.r_FunctionList
                .Where(a => a.FUsing == true).Where(s => s.FFunctionName == (FFunctionName ?? s.FFunctionName))
                .AsNoTracking().ToList();
            return View(Function);
        }

        public async Task<IActionResult> FunctionListsAdd()
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_FunctionList.Include(s => s.apigroup).Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> FunctionListsAdd([Bind("FGoupID,FFunctionName,FInterfaceType,FUrl,FDescription,FUsing")] FunctionList doctype)
        {
            if (!_context.r_FunctionList.Any(e => e.FFunctionName == doctype.FFunctionName && e.FDescription == doctype.FDescription))
            {
                _context.Add(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.Function), "Home");
        }

        public async Task<IActionResult> FunctionListsUpdate(int id)
        {
            FunctionList FunctionLis = _context.r_FunctionList!.Find(id)!;
            if (FunctionLis == null) { return View(); }
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = await _context.r_FunctionList!.Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToListAsync();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View(FunctionLis);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> FunctionListsUpdate(int id, [Bind("FID,FGoupID,FFunctionName,FInterfaceType,FUrl,FDescription,FUsing")] FunctionList doctype)
        {
            if (ModelState.IsValid)
            {
                //_context.Update(doctype);
                _context.r_FunctionList.Update(doctype);
                await _context.SaveChangesAsync();
            }
            else
            {
                FunctionList iDType = await _context.r_FunctionList.FindAsync(id);
                if (iDType != null)
                {
                    iDType.FGoupID = doctype.FGoupID;
                    iDType.FFunctionName = doctype.FFunctionName;
                    iDType.FInterfaceType = doctype.FInterfaceType;
                    iDType.FUrl = doctype.FUrl;
                    iDType.FDescription = doctype.FDescription;
                    iDType.FUsing = doctype.FUsing;
                    _context.r_FunctionList.Update(iDType);
                    await _context.SaveChangesAsync();
                }
            }
            return RedirectToAction(nameof(HomeController.Function), "Home");
        }
        public async Task<IActionResult> FunctionListsDelete(int id)
        {
            if (_context.r_FunctionList.Any(e => e.FID == id))
            {
                _context.r_FunctionList.Remove(_context.r_FunctionList.Find(id)!);

                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.Function), "Home");
        }


        public IActionResult RBLogs()
        {
            List<RBLog> RBLogs = _context.RBLog.AsNoTracking().ToList();
            return View(RBLogs);
        }


        public IActionResult FormIDTypes(string? FDocType)
        {
            List<FormIDType> FormID = (List<FormIDType>)_context.r_FormIDType.Include(s => s.functions)
                .Where(a => a.FUsing == true).Where(s => s.FDocType == (FDocType ?? s.FDocType))
                .AsNoTracking()
                .ToList();
            return View(FormID);

        }

        public async Task<IActionResult> FormIDTypesAdd()
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_FunctionList.Include(s => s.apigroup).Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> FormIDTypesAdd([Bind("FFunctionID,FActionName,FDocType,FDBName,FUsing,FIsHostService,FDescription")] FormIDType doctype)
        {
            if (!_context.r_FormIDType.Any(e => e.FFunctionID == doctype.FFunctionID && e.FDocType == doctype.FDocType))
            {
                _context.Add(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.FormIDTypes), "Home");
        }

        public async Task<IActionResult> FormIDTypesUpdate(int id)
        {
            FormIDType FormIDs = _context.r_FormIDType!.Find(id)!;
            if (FormIDs == null) { return View(); }
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = await _context.r_FunctionList!.Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToListAsync();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View(FormIDs);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> FormIDTypesUpdate(int id, [Bind("FID,FFunctionID,FActionName,FDocType,FDBName,FUsing,FIsHostService,FDescription")] FormIDType doctype)
        {
            if (ModelState.IsValid)
            {
                //_context.Update(doctype);
                _context.r_FormIDType.Update(doctype);
                await _context.SaveChangesAsync();
            }
            else
            {
                FormIDType iDType = await _context.r_FormIDType.FindAsync(id);
                if (iDType != null)
                {
                    iDType.FDescription = doctype.FDescription;
                    iDType.FFunctionID = doctype.FFunctionID;
                    iDType.FActionName = doctype.FActionName;
                    iDType.FDocType = doctype.FDocType;
                    iDType.FDBName = doctype.FDBName;
                    iDType.FUsing = doctype.FUsing;
                    iDType.FIsHostService = doctype.FIsHostService;
                    _context.r_FormIDType.Update(iDType);
                    await _context.SaveChangesAsync();
                }
            }
            return RedirectToAction(nameof(HomeController.FormIDTypes), "Home");
        }

        public async Task<IActionResult> FormIDTypesDelete(int id)
        {
            if (_context.r_FormIDType.Any(e => e.FID == id))
            {
                _context.r_FormIDType.Remove(_context.r_FormIDType.Find(id)!);

                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.FormIDTypes), "Home");
        }


        public IActionResult ReceiveStockBillTypes(string? ErpBillName)
        {
            List<ReceiveStockBillType> ReceiveStock = (List<ReceiveStockBillType>)_context.r_ReceiveStockBillTypes.Include(s => s.functions)
                 .Where(a => a.FROB == true).Where(s => s.ErpBillName == (ErpBillName ?? s.ErpBillName))
                .AsNoTracking().ToList();
            return View(ReceiveStock);
        }
        public IActionResult ReceiveStockBillTypesAdd()
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_FunctionList.Include(s => s.apigroup).Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ReceiveStockBillTypesAdd([Bind("FFunctionID,ErpBillTypeID,ErpBillName,FROB,FHeadTbName,FEntryTbName,FStatus,FDefaultUserid,FDefaultDepid")] ReceiveStockBillType doctype)
        {
            if (!_context.r_ReceiveStockBillTypes.Any(e => e.FFunctionID == doctype.FFunctionID && e.ErpBillName == doctype.ErpBillName))
            {
                _context.Add(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.ReceiveStockBillTypes), "Home");
        }

        public async Task<IActionResult> ReceiveStockBillTypesUpdate(int id)
        {
            ReceiveStockBillType ReceiveStockBill = _context.r_ReceiveStockBillTypes!.Find(id)!;
            if (ReceiveStockBill == null) { return View(); }
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = await _context.r_FunctionList!.Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToListAsync();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View(ReceiveStockBill);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ReceiveStockBillTypesUpdate(int id, [Bind("FID,FFunctionID,ErpBillTypeID,ErpBillName,FROB,FHeadTbName,FEntryTbName,FStatus,FDefaultUserid,FDefaultDepid")] ReceiveStockBillType doctype)
        {
            if (ModelState.IsValid)
            {
                //_context.Update(doctype);
                _context.r_ReceiveStockBillTypes.Update(doctype);
                await _context.SaveChangesAsync();
            }
            else
            {
                ReceiveStockBillType iDType = await _context.r_ReceiveStockBillTypes.FindAsync(id);
                if (iDType != null)
                {
                    iDType.FFunctionID = doctype.FFunctionID;
                    iDType.ErpBillTypeID = doctype.ErpBillTypeID;
                    iDType.ErpBillName = doctype.ErpBillName;
                    iDType.FROB = doctype.FROB;
                    iDType.FHeadTbName = doctype.FHeadTbName;
                    iDType.FEntryTbName = doctype.FEntryTbName;
                    iDType.FStatus = doctype.FStatus;
                    iDType.FDefaultUserid = doctype.FDefaultUserid;
                    iDType.FDefaultDepid = doctype.FDefaultDepid;
                    _context.r_ReceiveStockBillTypes.Update(iDType);
                    await _context.SaveChangesAsync();
                }
            }
            return RedirectToAction(nameof(HomeController.ReceiveStockBillTypes), "Home");
        }


        public async Task<IActionResult> ReceiveStockBillTypesDelete(int id)
        {
            if (_context.r_ReceiveStockBillTypes.Any(e => e.FID == id))
            {
                _context.r_ReceiveStockBillTypes.Remove(_context.r_ReceiveStockBillTypes.Find(id)!);

                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.ReceiveStockBillTypes), "Home");
        }

        public async Task<IActionResult> K3DefaultColValsAdd(int fid)
        {
            var fun = _context.r_ReceiveStockBillTypes.Include(s => s.functions).Where(s => s.FID == fid).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FERPBillName");
            ViewData["function"] = listItems;
            return View();
        }

        public IActionResult SelectJoinIDs(string? FDocType)
        {
            List<SelectJoinID> SelectJoin = (List<SelectJoinID>)_context.r_SelectJoinID.Include(s => s.functions)
                .Where(s => s.FDocType == (FDocType ?? s.FDocType))
                .AsNoTracking().ToList();
            return View(SelectJoin);
        }
        public async Task<IActionResult> SelectJoinIDsAdd()
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_FunctionList.Include(s => s.apigroup).Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SelectJoinIDsAdd([Bind("FFunctionID,FDocType,FOptcode")] SelectJoinID doctype)
        {
            if (!_context.r_SelectJoinID.Any(e => e.FFunctionID == doctype.FFunctionID && e.FDocType == doctype.FDocType))
            {
                _context.Add(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.SelectJoinIDs), "Home");
        }


        public async Task<IActionResult> SelectJoinIDsUpdate(int id)
        {

            SelectJoinID SelectJoin = _context.r_SelectJoinID!.Find(id)!;
            if (SelectJoin == null) { return View(); }
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = await _context.r_FunctionList!.Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToListAsync();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View(SelectJoin);

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SelectJoinIDsUpdate(int id, [Bind("FID,FFunctionID,FDocType,FOptcode")] SelectJoinID doctype)
        {
            if (ModelState.IsValid)
            {
                //_context.Update(doctype);
                _context.r_SelectJoinID.Update(doctype);
                await _context.SaveChangesAsync();
            }
            else
            {
                SelectJoinID iDType = await _context.r_SelectJoinID.FindAsync(id);
                if (iDType != null)
                {
                    iDType.FFunctionID = doctype.FFunctionID;
                    iDType.FDocType = doctype.FDocType;
                    iDType.FOptcode = doctype.FOptcode;
                    _context.r_SelectJoinID.Update(iDType);
                    await _context.SaveChangesAsync();
                }
            }
            return RedirectToAction(nameof(HomeController.SelectJoinIDs), "Home");
        }
        public async Task<IActionResult> SelectJoinIDsDelete(int id)
        {
            if (_context.r_SelectJoinID.Any(e => e.FID == id))
            {
                _context.r_SelectJoinID.Remove(_context.r_SelectJoinID.Find(id)!);

                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.SelectJoinIDs), "Home");
        }

        public IActionResult BillConverts(string? FSourceName)
        {
            List<BillConvert> Convert = (List<BillConvert>)_context.r_BillConvertes.Where(a => a.FNeedInput == true).Where(s => s.FSourceName == (FSourceName ?? s.FSourceName))
                .AsNoTracking().ToList();
            return View(Convert);
        }
        public async Task<IActionResult> BillConvertsAdd(int fid)
        {
            var fun = _context.r_ReceiveStockBillTypes.Include(s => s.functions).Where(s => s.FROB && s.functions.FID == fid).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FERPBillName");
            ViewData["function"] = listItems;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BillConvertsAdd([Bind("FReceiveID,FPageID,FSourceName,FK3FiledName,FNeedInput")] BillConvert doctype)
        {
            if (!_context.r_BillConvertes.Any(e => e.FReceiveID == doctype.FReceiveID && e.FSourceName == doctype.FSourceName))
            {
                _context.Add(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.BillConverts), "Home");
        }
        public async Task<IActionResult> BillConvertsUpdate(int id)
        {
            BillConvert? Converts = await _context.r_BillConvertes.FindAsync(id);
            return View(Converts);

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BillConvertsUpdate(int id, [Bind("FID,FReceiveID,FPageID,FSourceName,FK3FiledName,FNeedInput")] BillConvert doctype)
        {
            if (_context.r_BillConvertes.Any(e => e.FID == id))
            {
                _context.Update(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.BillConverts), "Home");
        }
        public async Task<IActionResult> BillConvertsDelete(int id)
        {
            if (_context.r_BillConvertes.Any(e => e.FID == id))
            {
                _context.r_BillConvertes.Remove(_context.r_BillConvertes.Find(id)!);

                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.BillConverts), "Home");
        }

        public IActionResult SColsAdd(int fid)
        {
            var fun = _context.r_SelectJoinID.Include(s => s.functions).Where(s => s.functions.FID == fid).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FDocType");
            ViewData["function"] = listItems;
            return View();
        }

        public IActionResult JoinTbsAdd()
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_SelectJoinID.Include(s => s.functions).Where(s => s.functions.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FDocType");
            ViewData["function"] = listItems;
            return View();
        }

        public IActionResult SelectClumnConverts(int id, string? FDesTableName)
        {
            List<SelectClumnConvert> SelectClumn = _context.r_ClumnConvert
                .Where(s => s.FDesTableName == (FDesTableName ?? s.FDesTableName))
                .AsEnumerable().ToList();
            return View(SelectClumn);
        }
        public IActionResult SelectClumnConvertsAdd()
        {
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_FunctionList.Include(s => s.apigroup).Where(s => s.FUsing == true && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SelectClumnConvertsAdd([Bind("FIndexID,FFunctionID,FDesTableName,FSourceName,FDesName,FKDCaption")] SelectClumnConvert doctype)
        {
            if (!_context.r_ClumnConvert.Any(e => e.FFunctionID == doctype.FFunctionID && e.FDesTableName == doctype.FDesTableName))
            {
                _context.Add(doctype);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.SelectClumnConverts), "Home");
        }
        public async Task<IActionResult> SelectClumnConvertsUpdate(int id)
        {
            SelectClumnConvert SelectClumn = await _context.r_ClumnConvert!.FindAsync(id)!;
            if (SelectClumn == null) { return View(); }
            string apiid = LocalStaticRequest.GetSystemProfile(1, "APIGrouID");
            var fun = _context.r_FunctionList!.Where(s => s.FUsing && s.apigroup.FID == int.Parse(apiid)).AsNoTracking().ToList();
            SelectList listItems = new SelectList(fun, "FID", "FFunctionName");
            ViewData["function"] = listItems;
            return View(SelectClumn);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SelectClumnConvertsUpdate(int id, [Bind("FID,FIndexID,FFunctionID,FDesTableName,FSourceName,FDesName,FKDCaption")] SelectClumnConvert doctype)
        {
            SelectClumnConvert iDType = await _context.r_ClumnConvert.FindAsync(id);
            if (iDType != null)
            {
                iDType.FIndexID = doctype.FIndexID;
                iDType.FFunctionID = doctype.FFunctionID;
                iDType.FDesTableName = doctype.FDesTableName;
                iDType.FSourceName = doctype.FSourceName;
                iDType.FDesName = doctype.FDesName;
                iDType.FKDCaption = doctype.FKDCaption;
                _context.r_ClumnConvert.Update(iDType);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.SelectClumnConverts), "Home");
        }
        public async Task<IActionResult> SelectClumnConvertsDelete(int id)
        {
            if (_context.r_ClumnConvert.Any(e => e.FID == id))
            {
                _context.r_ClumnConvert.Remove(_context.r_ClumnConvert.Find(id)!);

                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(HomeController.SelectClumnConverts), "Home");
        }


        //public async Task<IActionResult> Editdoctype(int id)
        //{
        //    SelectJoinID? selectJoin = await _context.r_SelectJoinID.FindAsync(id);
        //    return View(selectJoin);

        //}

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public async Task<IActionResult> Editdoctype(int id, [Bind("FID,FInterfaceID,FOptcode,FDocType,FDescription,FUsing")] SelectJoinID doctype)
        //{
        //    if (_context.r_SelectJoinID.Any(e => e.FID == id))
        //    {
        //        _context.Update(doctype);
        //        await _context.SaveChangesAsync();
        //    }
        //    return RedirectToAction(nameof(HomeController.Index), "Home");
        //}
        //[HttpPost]
        //[ValidateAntiForgeryToken]

        //public IActionResult SetOptcode([Bind("FID,FOptcode")] IList<SelectJoinList> selectJoin)
        //{
        //    int id = 0;
        //    Dictionary<string, object> fpairs = new Dictionary<string, object>();
        //    if (selectJoin != null)
        //    {
        //        bool isbr = false;
        //        foreach (SelectJoinList SJL in selectJoin)
        //        {
        //            foreach (string keys in SJL.FOptcode)
        //            {
        //                isbr = true;
        //                id = SJL.FID;
        //            }
        //            if (isbr) { break; }
        //        }
        //    }
        //    return RedirectToAction(nameof(HomeController._GetData), "GetApis", new { cid = id, pairs = fpairs });
        //    //return Task.FromResult(RedirectToAction(nameof(GetApisController._GetData), "GetApis", new { cid = id, pairs = fpairs }));
        //}

        //private Dictionary<string,object> NewOptcodeKeyValues(List<string> vs)
        //{

        //}
        public async Task<string> EditOptcode(int id, string Optcode)
        {
            SelectJoinID? selectJoin = await _context.r_SelectJoinID.FindAsync(id);
            if (selectJoin != null)
            {
                selectJoin.FOptcode = Optcode;
                _context.UpdateRange(selectJoin);
                await _context.SaveChangesAsync();
                return "OK";
            }
            else
            {
                return "当前接口或许已被 删除";
            }
        }
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        //public IActionResult Error()
        //{
        //    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        //}
        /// <summary>
        /// //页面上显示是否已有启动本地服务的标识！！！
        /// 按LocalStaticRequest.SendTime间隔从页面不停地访问、更新
        /// </summary>
        /// <returns></returns>
        public bool LocalServiceStatus()
        {
            return LocalStaticRequest.LocasServerStatus;
        }

        #region ERP手动推送到MES
        /// <summary>
        /// erp 与 mes 工单对照
        /// </summary>
        /// <param name="period">查询周期(yyyyMM)</param>
        /// <returns></returns>
        public IActionResult ERPAndMESComparison(int period = 0)
        {
            List<ERPMESMOXComparison> datas = new List<ERPMESMOXComparison>();
            period = period == 0 ? int.Parse(DateTime.Now.ToString("yyyyMM")) : period;

            var erpBills = new List<string>();
            var orgId = 100038;
            orgId = LocalStaticRequest.DefaultOrgID;
            var erpMoSql = $@"/*dialect*/
	SELECT t0.FID,t0e.FENTRYID,t0.FBILLNO,t0.FDOCUMENTSTATUS,t0e.FMATERIALID
		,t1.FNUMBER,t1_l.FNAME,t0e_a.FCONVEYDATE,t0e_a.FSTATUS 
		,ROW_NUMBER() OVER (ORDER BY t0.FID,t0e.FENTRYID) AS RN
	FROM T_PRD_MO t0
		INNER JOIN T_PRD_MOENTRY t0e on t0e.FID = t0.FID
		INNER JOIN T_PRD_MOENTRY_A t0e_a on t0e.FENTRYID = t0e_a.FENTRYID
		INNER JOIN T_BD_MATERIAL t1 on t1.FMATERIALID = t0e.FMATERIALID
		INNER JOIN T_BD_MATERIAL_L t1_l on t1_l.FMATERIALID = t0e.FMATERIALID AND t1_l.FLOCALEID = 2052
	WHERE 1=1
		AND t0.FDOCUMENTSTATUS = 'C'
        AND t0.FPRDORGID = {orgId}
		AND CONVERT(int,CONVERT(varchar(6) ,t0e_a.FCONVEYDATE,112)) = {period}
        AND t0e_a.FSTATUS = 3
";

            LogHelper.WriteLog($"ERP查询数据库语句:{erpMoSql}");
            var resMsg = string.Empty;
            var pageDs = _kdsqlhelper.GetDataSet(CommandType.Text, erpMoSql, null, ref resMsg, true);

            var dt = pageDs.Tables[0];
            var dtRows = dt.Rows;
            foreach (DataRow row in dt.Rows)
            {
                var billNo = row["FBILLNO"].ToString();
                if (billNo == null)
                    continue;

                erpBills.Add(billNo);
                datas.Add(new ERPMESMOXComparison
                {
                    ERP_MO = billNo,
                    MATERIAL_NAME = row["FNAME"].ToString(),
                    MATERIAL_NUMBER = row["FNUMBER"].ToString(),
                    FDOCUMENTSTATUS = "下达",
                    PROD_ID = row["FNUMBER"].ToString(),
                    CONVEYDATE = row["FCONVEYDATE"].ToString()
                });
            }


            if (erpBills.Count == 0)
                return View(datas);

            var mesBillNo = new List<string>();

            var sql = _mesContext.TB_PP_WPLANS.Where(w => erpBills.Contains(w.ERP_MO)).ToQueryString();

            LogHelper.WriteLog($"MES查询数据库语句:{sql}");
            try
            {
                var mesData = _mesContext.TB_PP_WPLANS.Where(w => erpBills.Contains(w.ERP_MO))
                    .AsNoTracking().ToList();
                if (mesData.Count > 0)
                {
                    mesBillNo = mesData.Select(x => x.ERP_MO).ToList();
                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                LogHelper.WriteLog(string.Format("查询数据库：{0}，\n原因是：{1}", sql, ex.Message));

                return View(new List<ERPMESMOXComparison>());
            }

            var result = datas.Where(w => !mesBillNo.Contains(w.ERP_MO)).ToList();

            return View(result);
        }

        /// <summary>
        /// 批量推送
        /// </summary>
        /// <param name="putData"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ERPAndMESXomparisonMesPuts(string putData)
        {
            //返回信息
            var resultData = new ResultData<List<ResultBillNoMsg>>();

            try
            {

                var dataJson = JsonConvert.DeserializeObject<List<ERPMoInfoEntity>>(putData);
                var resMsgD = string.Empty;
                foreach (var item in dataJson)
                {
                    var mo = item.erpNo;
                    var resBillData = new ResultBillNoMsg();
                    resBillData.BillNo = mo;

                    resultData.Data.Add(resBillData);
                    
                    var conveyDate = item.conveyDate;
                    var mesData = _mesContext.TB_PP_WPLANS.Where(w => w.ERP_MO == mo).AsNoTracking().ToList().FirstOrDefault();
                    if (mesData != null)
                    {
                        resBillData.Code = -1;
                        resBillData.Message = "重复推送，已存在于MES系统中。";
                    }
                    else
                    {
                        try
                        {
                            string resMsg = string.Empty;
                            DoERPPutToMESMO(mo, conveyDate, ref resMsg);
                            if (!resMsg.IsNullOrEmpty())
                            {
                                resBillData.Code = -1;
                                resBillData.Message = resMsg;
                            }
                            else
                            {
                                resBillData.Code = 0;
                                resBillData.Message = "推送成功。";
                            }
                        }
                        catch (Exception ex)
                        {
                            resBillData.Code = -1;
                            resBillData.Message = ex.Message;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                resultData.Code = -1;
                resultData.Message = ex.Message;
            }
            finally
            {

            }

            return new JsonResult(resultData);
        }

        /// <summary>
        /// 执行手动推送
        /// </summary>
        /// <param name="mo"></param>
        /// <param name="conveyDate"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ERPAndMESXomparisonMesPut(string mo, string conveyDate)
        {
            try
            {
                var mesData = _mesContext.TB_PP_WPLANS.Where(w => w.ERP_MO == mo).AsNoTracking().ToList().FirstOrDefault();
                if (mesData != null)
                {
                    throw new Exception($"工单编号：{mo}，已在MES系统中。");
                }

                string resMsg = string.Empty;
                DoERPPutToMESMO(mo, conveyDate, ref resMsg);
                if (!resMsg.IsNullOrEmpty())
                    throw new Exception(resMsg);
            }
            catch (Exception ex)
            {
                return new JsonResult(new { code = -1, resMsg = ex.Message });
            }

            return new JsonResult(new { code = 0, resMsg = "" });
        }

        /// <summary>
        /// 执行推送
        /// </summary>
        /// <param name="mo"></param>
        /// <param name="conveyDate"></param>
        /// <param name="resMsg"></param>
        private void DoERPPutToMESMO(string mo, string conveyDate, ref string resMsg)
        {
            string tbjson = string.Empty;
            using var scope = _serviceScopeFactory.CreateScope();
            try
            {
                IShareController myScopedService = scope.ServiceProvider.GetRequiredService<IShareController>();
                List<CloudBillQuery> queryJsons = myScopedService.GetAPIList<CloudBillQuery>().Result;

                var formTypeId = 9;
                var docType = "TB_PP_WPLAN";
                var query = queryJsons.FirstOrDefault(s => s.GetFormID.FDocType == docType);

                if (query != null)
                {
                    string sql = query.FFieldKeys.Replace("@defaultorgid", LocalStaticRequest.DefaultOrgID.ToString());
                    if (!sql.IsNullOrEmpty())
                    {
                        string param = query.FFiledString.Replace("@defaultorgid", LocalStaticRequest.DefaultOrgID.ToString()).Replace("@defaultorgno", LocalStaticRequest.DefaultOrg);

                        var isDateVal = DateTime.TryParse(conveyDate, out DateTime dateVal);
                        string[] strings = param.Split(',');
                        foreach (string s in strings)
                        {
                            string[] cs = s.Split('=');
                            string key = cs[0];
                            string value = cs[1].Replace("GETDATE", dateVal.ToShortDateString()).Replace("@defaultorgid", LocalStaticRequest.DefaultOrgID.ToString());
                            sql = sql.Replace(key, value);
                        }

                        sql = sql.Replace("null", $"'{mo}'");
                    }

                    string costomsql = ApiSettingsHelper.GetConfig("CustomRequestRemoteSql");
                    if (costomsql.ToUpper() == "Y")
                    {
                        string result = _chiledSelect.GetCustomReaderAsync(sql, "ExecuteDataSet").Result;
                        try
                        {
                            if (string.IsNullOrWhiteSpace(result))
                                throw new Exception($"工单编号:{mo},查询数据为空!");

                            //先将返回数据格式化
                            JObject jobj = (JObject)JsonConvert.DeserializeObject(result);
                            tbjson = JsonConvert.SerializeObject(jobj["Table"]);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog(string.Format(docType + "在自定义SQL查询结果集过程中GetCustomRequestTBAsync发生错误：\r\n{0}", ex.Message));
                        }
                    }
                    else
                    {
                        string mess = string.Empty;
                        DataSet dataSet = _kdsqlhelper.GetDataSet(CommandType.Text, sql, null, ref mess, true);
                        if (mess != null || dataSet == null)
                        {
                            LogHelper.WriteLog(string.Format(docType + "在自定义SQL查询结果集过程中GetCustomRequestTBAsync发生错误：\r\n{0}", mess));
                        }
                        else if (dataSet.Tables.Count != 0)
                        {
                            DataTable dataTable = dataSet.Tables[0];
                            tbjson = JsonConvert.SerializeObject(dataTable);
                        }
                    }

                    if (tbjson.IsNullOrEmpty())
                        throw new Exception($"工单编号:{mo},查询数据为空!");

                    try
                    {
                        JArray array = (JArray)JsonConvert.DeserializeObject(tbjson);
                        if (array == null || array.Count == 0) { scope.Dispose(); return; };
                        PanguPostBill mes = new PanguPostBill()
                        {
                            DocType = docType,
                            DataSet = myScopedService.GetClassList(array)
                        };
                        string json = JsonConvert.SerializeObject(mes);
                        //推送给MES
                        IKDCloudHttpClient myhttpclient = scope.ServiceProvider.GetRequiredService<IKDCloudHttpClient>();
                        PanguBreakJson mesjson = myhttpclient.PushMesData(json).Result;
                        if (mesjson.Status)
                        {
                            LogHelper.WriteLog(string.Format("推送【{0}】成功：{1}", docType, json), docType);
                        }
                        else
                        {
                            resMsg = string.Format("PushBackgroundService的GetSelfDBbaseAsync方法推送【{0}】失败：{1}\n原始数据：{2}", docType, mesjson.Message, json);
                            LogHelper.WriteLog(resMsg, docType);
                        }
                    }
                    catch (Exception ex)
                    {
                        resMsg = ex.Message;
                        LogHelper.WriteLog(string.Format("PushBackgroundService推送【{0}】动态GetSelfDBbaseAsync方法出错：{1}", docType, ex.Message), docType);
                    }
                }

            }
            catch (Exception ex)
            {
                resMsg = ex.Message;
                LogHelper.WriteLog($"ERP工单推送MES错误，\n原因是：{ex.Message}");
            }
            finally
            {
                if (scope != null)
                    scope.Dispose();
            }

        }
        #endregion


    }
}