using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.Operation;
using Kingdee.BOS.Core.DynamicForm.OperationWebService;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Interaction;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement;
using Kingdee.BOS.Core.Metadata.ConvertElement.ServiceArgs;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.Metadata.Operation;
using Kingdee.BOS.Core.Validation;
using Kingdee.BOS.FileServer.Core;
using Kingdee.BOS.FileServer.Core.Object;
using Kingdee.BOS.FileServer.ProxyService;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.ServiceHelper.FileServer;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.ServicesStub;
using Newtonsoft.Json.Linq;
using static Kingdee.BOS.Core.Enums.BOSEnums;

namespace LQKJ.WebApi.Stub
{
    //自定义webapi接口
    public class CustomWebApiService : AbstractWebApiBusinessService
    {

        public string dbid = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["Dbid"].Value;
        public string username = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["username"].Value;
        public string password = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["password"].Value;
        public string url = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["url"].Value;
        
        public CustomWebApiService(KDServiceContext context)
            : base(context)
        {
            //
        }
       
        //执行sql并返回查询结果  sql脚本
        public SQLResult ExecutDataSet(string sql)
        {
            SQLResult sQLResult = new SQLResult();
            if (string.IsNullOrWhiteSpace(sql))
            {
                sQLResult.code = "500";
                sQLResult.msg = "参数为空，请传正确的参数！";
                return sQLResult;
            }
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }


            if (context == null)
            {
                sQLResult.code = "500";
                sQLResult.msg = "请重新登录！";
                return sQLResult;
            }
            sQLResult.code = "200";
            //sql = DESHelper.Decrypt(sql, "MES&&DES");
            try
            {
                sQLResult.data = DBServiceHelper.ExecuteDataSet(context, sql);
            }
            catch (Exception ex)
            {
                sQLResult.code = "500";
                sQLResult.msg = ex.Message;
            }
            return sQLResult;
        }

        /**
         * 登录
         */
        private Context Login()
        {
            AuthService authService = new AuthService(this.KDContext);
            var loginResult = authService.ValidateUser(dbid, username, password);
            if (loginResult.IsSuccessByAPI)
            {
                return loginResult.Context;
            }
            return null;
        }

        //执行sql并返回查询结果 返回字典集合
        public SQLResult ExecuteDynamicObject(string sql)
        {
            SQLResult sQLResult = new SQLResult();
            if (string.IsNullOrWhiteSpace(sql))
            {
                sQLResult.code = "0001";
                sQLResult.msg = "参数为空，请传正确的参数！";
                return sQLResult;
            }
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }

            if (context == null)
            {
                sQLResult.code = "0010";
                sQLResult.msg = "请重新登录！";
                return sQLResult;
            }
            sQLResult.code = "200";
            //sql = DESHelper.Decrypt(sql, "MES&&DES");
            try
            {
                sQLResult.data = DBServiceHelper.ExecuteDynamicObject(context, sql);
            }
            catch (Exception ex)
            {
                sQLResult.code = "0001";
                sQLResult.msg = ex.Message;
            }
            return sQLResult;
        }
        /// <summary>
        /// 返回一个DataTable对象
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable ExecuteDataTable(string sql)
        {
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }
            DataTable dataTable = DBServiceHelper.ExecuteDataSet(context, sql).Tables[0];
            return dataTable;
        }
        public int Execute(string sql)
        {
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }
            int result= DBServiceHelper.Execute(context, sql);
            return result;
        }

        public List<FileProperty> FilePath(string courseNumber)
        {
           
            List<FileProperty> listPath = new List<FileProperty>();
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }
            string url = FileServerHelper.GetAppSiteOuterNetUrl(context, HttpContext.Current.Request);
            string sqlSelect = $"select FFILEID,FATTACHMENTNAME from T_BAS_ATTACHMENT where FBILLTYPE = 'LQKJ_Course' and FBILLNO='{courseNumber}'";
            DataTable dataTable = ExecuteDataTable(sqlSelect);
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                FileProperty fileProperty = new FileProperty();
                string fileUrl = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}",dataTable.Rows[i]["FFILEID"].ToString(), context.UserToken);//文件就算一样路径不可能一样
                string name = dataTable.Rows[i]["FATTACHMENTNAME"].ToString();
                fileProperty.url = fileUrl;fileProperty.name = name;
                listPath.Add(fileProperty);
            }
            return listPath;
        }
        public string[] GetFilename(string FileId)
        {

            string sql = $"select FFILENAME from T_BAS_FILESERVERFILEINFO where FFILEID = '{FileId}'";
            DataTable dt = ExecuteDataTable(sql);
            string[] strs = new string[2];
            Context context = this.KDContext.Session.AppContext;
            if (dt != null && dt.Rows.Count > 0)
            {
                if (context == null && !string.IsNullOrWhiteSpace(dbid))
                {
                    if (context == null && !string.IsNullOrWhiteSpace(dbid))
                    {
                        context = Login();
                    }
                }
                strs[0] = dt.Rows[0][0].ToString();//文件名
                strs[1] = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", FileId, context.UserToken);//文件就算一样路径不可能一样
                return strs;
            }
            else
            {
                strs[0] = "";
                strs[1] = "";
                return strs;
            }
        }
        /// <summary>
        /// 执行批量Sql语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public SQLResult ExecutBatch(string sql)
        {
            SQLResult sQLResult = new SQLResult();
            if (string.IsNullOrWhiteSpace(sql))
            {
                sQLResult.code = "0001";
                sQLResult.msg = "参数为空，请传正确的参数！";
                return sQLResult;
            }
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }

            if (context == null)
            {
                sQLResult.code = "0010";
                sQLResult.msg = "请重新登录！";
                return sQLResult;
            }
            sQLResult.code = "200";
            sql = DESHelper.Decrypt(sql, "MES&&DES");
            var sqls = sql.Split(';').ToList();
            try
            {
                sQLResult.data = DBServiceHelper.ExecuteBatch(context, sqls);
            }
            catch (Exception ex)
            {
                sQLResult.code = "0001";
                sQLResult.msg = ex.Message;
            }
            return sQLResult;
        }

        /**
         * 获取同步数据
         */
        public SQLResult GetSyncData()
        {
            SQLResult sQLResult = new SQLResult();
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }


            if (context == null)
            {
                sQLResult.code = "0010";
                sQLResult.msg = "请重新登录！";
                return sQLResult;
            }

            sQLResult.code = "200";
            if (SyncStaticParam.CurTime.AddMinutes(1) < DateTime.Now)
            {
                if (SyncStaticParam.DCSyncInfoDic.ContainsKey(context.DBId))
                {
                    if (!SyncStaticParam.DCSyncInfoDic[context.DBId]) return sQLResult;
                }
            }
            string sql = "select FID fid, F_LQKJ_SyncDataId dataid, F_LQKJ_SyncDataEntryId entryid, F_LQKJ_Syncbill sformid, F_LQKJ_operationinnercode operation from LQKJ_t_IMSSync where F_LQKJ_SyncCheck = '0'";
            try
            {
                sQLResult.data = DBServiceHelper.ExecuteDynamicObject(context, sql);
                SyncStaticParam.DCSyncInfoDic[context.DBId] = false;
            }
            catch (Exception ex)
            {
                sQLResult.code = "0001";
                sQLResult.msg = ex.Message;
            }
            return sQLResult;
        }


        /**
         * 获取同步数据
         */
        public SQLResult updateSyncData(SyncDataStatusInfo[] syncDataStatusInfos)
        {
            SQLResult sQLResult = new SQLResult();
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }


            if (context == null)
            {
                sQLResult.code = "0010";
                sQLResult.msg = "请重新登录！";
                return sQLResult;
            }

            sQLResult.code = "200";
            try
            {
                List<string> sqls = new List<string>();
                foreach (SyncDataStatusInfo syncDataStatusInfo in syncDataStatusInfos)
                {
                    string curSql = "update LQKJ_t_IMSSync set F_LQKJ_SyncCheck = " + syncDataStatusInfo.Status + ", F_LQKJ_MESSAGE = '" + syncDataStatusInfo.Message + "', F_LQKJ_SyndDatetime = GETDATE() where FID ='" + syncDataStatusInfo.SyncId + "'";
                    sqls.Add(curSql);

                    if (syncDataStatusInfo.Status > 1)
                    {
                        SyncStaticParam.DCSyncResultDic[syncDataStatusInfo.SyncId] = syncDataStatusInfo.Status == 2;
                        SyncStaticParam.DCSyncMessageDic[syncDataStatusInfo.SyncId] = syncDataStatusInfo.Message;
                    }
                }
                DBServiceHelper.ExecuteBatch(context, sqls);

                string sql = "select FID fid, F_LQKJ_SyncDataId dataid, F_LQKJ_SyncDataEntryId entryid, F_LQKJ_Syncbill sformid, F_LQKJ_operationinnercode operation from LQKJ_t_IMSSync where F_LQKJ_SyncCheck = '0'";
                var results = DBServiceHelper.ExecuteDynamicObject(context, sql);
                if (results.Count == 0)
                {
                    SyncStaticParam.DCSyncInfoDic[context.DBId] = false;
                }
                else
                {
                    SyncStaticParam.DCSyncInfoDic[context.DBId] = true;
                }
            }
            catch (Exception ex)
            {
                sQLResult.code = "0001";
                sQLResult.msg = ex.Message;
                Logger.Error("CustomWebApiService.updateSyncData", sQLResult.msg, ex);
            }
            return sQLResult;
        }

        private IBillView CreateBillView(Context context, string formId, JSONObject model, out bool isToAudit)
        {
            //读取物料的元数据
            FormMetadata meta = MetaDataServiceHelper.Load(context, formId) as FormMetadata;
            Form form = meta.BusinessInfo.GetForm();
            //创建用于引入数据的单据view
            Type type = Type.GetType("Kingdee.BOS.Web.Bill.BillView,Kingdee.BOS.Web");
            var billView = (IDynamicFormViewService)Activator.CreateInstance(type);
            //开始初始化billView：
            //创建视图加载参数对象，指定各种参数，如FormId, 视图(LayoutId)等
            BillOpenParameter openParam = CreateOpenParameter(context, meta, model, out isToAudit);
            //动态领域模型服务提供类，通过此类，构建MVC实例
            var provider = form.GetFormServiceProvider();
            billView.Initialize(openParam, provider);
            return billView as IBillView;
        }

        private BillOpenParameter CreateOpenParameter(Context context, FormMetadata meta, JSONObject model, out bool isToAudit)
        {
            Form form = meta.BusinessInfo.GetForm();
            //指定FormId, LayoutId
            BillOpenParameter openParam = new BillOpenParameter(form.Id, meta.GetLayoutInfo().Id);
            //数据库上下文
            openParam.Context = context;
            //本单据模型使用的MVC框架
            openParam.ServiceName = form.FormServiceName;
            //随机产生一个不重复的PageId，作为视图的标识
            openParam.PageId = Guid.NewGuid().ToString();
            //元数据
            openParam.FormMetaData = meta;
            //界面状态：新增 (修改、查看)
            object pkValue;
            if (!model.TryGetValue(form.PkFieldName, out pkValue))
            {
                openParam.Status = OperationStatus.ADDNEW;
                isToAudit = true;
            }
            else
            {
                openParam.Status = OperationStatus.EDIT;
                isToAudit = false;
                //单据主键：本案例演示新建物料，不需要设置主键
                openParam.PkValue = pkValue;
            }
            //界面创建目的：普通无特殊目的 （为工作流、为下推、为复制等）
            openParam.CreateFrom = CreateFrom.Default;
            var plugs = form.CreateFormPlugIns();
            openParam.SetCustomParameter(FormConst.PlugIns, plugs);
            PreOpenFormEventArgs args = new PreOpenFormEventArgs(context, openParam);
            foreach (var plug in plugs)
            { //触发插件PreOpenForm事件，供插件确认是否允许打开界面
                plug.PreOpenForm(args);
            }
            return openParam;
        }

        /// <summary>
        /// 下推并保存
        /// </summary>
        /// <returns></returns>
        public List<Result> PushAndSave(PushAndSaveArgs pushAndSaveArgs)
        {
            List<Result> result = new List<Result>();
            //lock (SyncStaticParam.lockObject)
            {
                foreach (JSONObject curModel in pushAndSaveArgs.Model)
                {
                    result.Add(PushAndSave(pushAndSaveArgs, curModel));
                }
            }
            return result;
        }


        private Result PushAndSave(PushAndSaveArgs pushAndSaveArgs, JSONObject curModel)
        {
            var isAutoSubmit = pushAndSaveArgs.isAutoSubmit;
            Result result = new Result();
            if (pushAndSaveArgs == null)
            {
                result.code = "0001";
                result.msg = "参数为空，请传正确的参数！";
                return result;
            }
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }

            if (context == null)
            {
                result.code = "0010";
                result.msg = "请重新登录！";
                return result;
            }
            result.performances.Add(new Performance() { stage = "开始", pointTime = DateTime.Now });
            HashSet<long> useOrgIds = new HashSet<long>();
            if (curModel.ContainsKey("FUseOrgId"))
            {
                String useOrgIdStr = curModel.GetString("FUseOrgId");
                String[] useOrgIdStrs = useOrgIdStr.Split(',');
                if (useOrgIdStrs.Length > 0)
                {
                    string sql = $"select FOrgId from T_ORG_ORGANIZATIONS where FNumber in ('{string.Join("','", useOrgIdStrs)}')";
                    Logger.Info("useorg_SQL", sql);
                    using (IDataReader reader = DBUtils.ExecuteReader(context, sql))
                    {
                        while (reader.Read())
                        {
                            object orgId = reader["FOrgId"];
                            if (orgId == null) continue;

                            useOrgIds.Add(Convert.ToInt64(orgId));
                        }
                    }
                }
                curModel.Remove("FUseOrgId");
            }

            context.ServiceType = WebType.WebService;

            List<ListSelectedRow> listSelectedRows = new List<ListSelectedRow>();
            DynamicObject dynamicObject;

            FormMetadata billFormMetadata = null;
            try
            {
                billFormMetadata = MetaDataServiceHelper.Load(context, pushAndSaveArgs.FormId) as FormMetadata;
            }
            catch (KDException ex)
            {
                result.code = "0001";
                result.msg = $"单据唯一标识{pushAndSaveArgs.FormId}参数不正确！";
                return result;
            }

            bool isToAudit;
            bool cleanEntry = false;
            IBillView billView = CreateBillView(context, pushAndSaveArgs.FormId, curModel, out isToAudit);
            bool IsNew = pushAndSaveArgs.SrcIds == null || pushAndSaveArgs.SrcIds.Count == 0;
            if (IsNew)
            {
                cleanEntry = true;

                result.performances.Add(new Performance() { stage = "加载数据开始", pointTime = DateTime.Now });
                //构建一个IBillView实例
                ((IDynamicFormViewService)billView).LoadData();

                dynamicObject = billView.Model.DataObject;
                result.performances.Add(new Performance() { stage = "加载数据完成", pointTime = DateTime.Now });
            }
            else
            {
                result.performances.Add(new Performance() { stage = "开始下推", pointTime = DateTime.Now });
                foreach (string srcId in pushAndSaveArgs.SrcIds)
                {
                    listSelectedRows.Add(new ListSelectedRow("0", srcId, pushAndSaveArgs.SrcIds.IndexOf(srcId), pushAndSaveArgs.SrcFormId) { EntryEntityKey = pushAndSaveArgs.SrcEntryKey });
                }

                var convertRules = ConvertServiceHelper.GetConvertRules(context, pushAndSaveArgs.SrcFormId, pushAndSaveArgs.FormId);
                ConvertRuleElement convertRuleElement2 = convertRules.Where(rule => rule.Id == pushAndSaveArgs.ConvertRule).FirstOrDefault();

                if (convertRuleElement2 == null)
                {
                    result.code = "0001";
                    result.msg = $"源单({pushAndSaveArgs.SrcFormId})、目标单({pushAndSaveArgs.FormId})和单据转换({pushAndSaveArgs.ConvertRule})，其中有一个参数不正确！";
                    return result;
                }
                PushArgs serviceArgs = new PushArgs(convertRuleElement2, listSelectedRows.ToArray())
                {
                    TargetBillTypeId = "",//billtype
                                          //TargetOrgId ="1",
                                          //CustomParams = customParams,
                                          //EntryUpperLimitValue = retInfo.EntryUpperLimitValue
                };
                var pushOption = OperateOption.Create();
                pushOption.SetVariableValue("SelectByBillId", false);
                pushOption.SetVariableValue("ConvertType", "ManualPush");
                ConvertOperationResult innerConvertOperationResult = null;
                try
                {
                    var EntryName = "";
                    var EntryKey = "";
                    foreach (var item in curModel)
                    {
                        Element element1;
                        Element element = billView.BillBusinessInfo.GetElement(item.Key.Trim());
                        if (7 == 0 || element != null)
                        {
                            element1 = element;
                        }
                        int num = item.Key.Trim().IndexOf("#");
                        if (num > -1)
                        {
                            string key = item.Key.Trim().Substring(num + 2);
                            element = billView.BillBusinessInfo.GetElement(key);
                        }
                        element1 = element;
                        if (element == null) continue;

                        if (element is EntryEntity)
                        {
                            EntryName = (element1 as EntryEntity).EntryName;
                            EntryKey = (element1 as EntryEntity).Key;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    innerConvertOperationResult = ConvertServiceHelper.Push(context, serviceArgs, pushOption);
                    Dictionary<string, int> HSsrcId = new Dictionary<string, int>();
                    List<string> SrcIdlist = pushAndSaveArgs.SrcIds;
                    var DataEntities = innerConvertOperationResult.TargetDataEntities;
                    if (!EntryName.IsNullOrEmptyOrWhiteSpace())
                    {
                        foreach (var item in DataEntities)
                        {
                            var Entitys = item.DataEntity[EntryName] as DynamicObjectCollection;
                            foreach (var Entity in Entitys)
                            {
                                var LinkSId = (Entity[EntryKey + "_Link"] as DynamicObjectCollection)[0]["SId"].ToString();
                                if (HSsrcId.ContainsKey(LinkSId))
                                {
                                    HSsrcId[LinkSId] = HSsrcId[LinkSId] + 1;
                                }
                                else
                                {
                                    HSsrcId.Add(LinkSId, 1);
                                }
                            }
                        }
                        string NotInId = "";
                        if (HSsrcId.Count > 0)
                        {
                            foreach (var Id in SrcIdlist)
                            {
                                if (!HSsrcId.ContainsKey(Id))
                                {
                                    NotInId += Id + ",";
                                }
                                else
                                {
                                    if (HSsrcId[Id] == 0)
                                    {
                                        NotInId += Id + ",";
                                    }
                                    else
                                    {
                                        HSsrcId[Id] = HSsrcId[Id] - 1;
                                    }
                                }
                            }
                        }
                        if (NotInId != "")
                        {
                            result.msg = $"同步失败，源单分录主键{NotInId} 未下推成功!";
                            result.code = "0001";
                            return result;
                        }
                    }


                }
                catch (KDException ex)
                {
                    if (ex.Code == "BF")
                    {
                        result.msg = $"源单分录主键{pushAndSaveArgs.SrcEntryKey}配置不正确!";
                    }
                    else
                    {
                        result.msg = ex.Message;
                    }
                    result.code = "0001";
                    return result;
                }

                if (!innerConvertOperationResult.IsSuccess)
                {
                    GenMessages(result, innerConvertOperationResult, "下推");
                    return result;
                }

                var dynamicObjects = ((from p in innerConvertOperationResult.TargetDataEntities
                                       select p.DataEntity).ToArray<DynamicObject>());
                dynamicObject = dynamicObjects[0];
                billView.Model.DataObject = dynamicObject;

                result.performances.Add(new Performance() { stage = "结束下推", pointTime = DateTime.Now });
            }
            Save save = new Save();
            save.IsNew = IsNew;
            save.cleanEntry = cleanEntry;
            save.Context = context;
            save.BillView = billView;
            save.Initialize(new WebServiceContext(billView, null, null, new FormOperation()));
            try
            {
                result.performances.Add(new Performance() { stage = "开始字段映射", pointTime = DateTime.Now });
                save.Map(curModel, dynamicObject);
                result.performances.Add(new Performance() { stage = "完成字段映射", pointTime = DateTime.Now });
            }
            catch (KDException ex)
            {
                result.msg = ex.Message;
                result.code = "0001";
                billView.CommitNetworkCtrl();
                return result;
            }
            billView.CommitNetworkCtrl();

            if (pushAndSaveArgs.IsInTransaction)
            {
                using (SessionScope scope = new SessionScope())
                {
                    using (KDTransactionScope ts = new KDTransactionScope(TransactionScopeOption.Required))
                    {
                        result = SaveAndAudit(context, result, billView, billFormMetadata, isToAudit, isAutoSubmit, useOrgIds);
                        if (result.code == "200")
                        {
                            ts.Complete();
                        }
                        return result;
                    }
                }
            }
            else
            {
                return SaveAndAudit(context, result, billView, billFormMetadata, isToAudit, isAutoSubmit, useOrgIds);
            }
        }

        /// <summary>
        /// 保存提交审核
        /// </summary>
        /// <param name="billView"></param>
        private Result SaveAndAudit(Context context, Result result, IBillView billView, FormMetadata billFormMetadata, bool isToAudit, Ismode isAutoSubmit, HashSet<long> useOrgIds)
        {
            //0暂存
            //1保存
            //2保存提交
            //3保存提交审核
            OperateOption option = OperateOption.Create();
            option.SetNotShowConfirmInfo(true);
            option.SetIgnoreWarning(true);
            option.SetIgnoreInteractionFlag(true);
            List<object> successIds = new List<object>();
            //IOperationResult saveResult = billView.Model.Save(option);

            IOperationResult saveResult = Kingdee.BOS.ServiceHelper.BusinessDataServiceHelper.Save(context, billView.BillBusinessInfo, new DynamicObject[] { billView.Model.DataObject });

            //1保存
            //2保存提交
            //3保存提交审核
            if (isAutoSubmit == Ismode.save || isAutoSubmit == Ismode.submit || isAutoSubmit == Ismode.auto)
            {
                LoadSuccessIds(successIds, saveResult);
                GenMessages(result, saveResult, "保存", !isToAudit);
                if (successIds.Count == 0) return result;
                if (!isToAudit && result.code == "200")
                {
                    result.msg = result.msg.Replace("保存", "同步");
                }
                if (isAutoSubmit == Ismode.save && result.code == "200"&& result.resultData.Count == 0)
                {
                    GenMessages(result, saveResult, "保存", true);
                    //result.msg = "同步成功";
                }
            }
            if (isAutoSubmit == Ismode.submit || isAutoSubmit == Ismode.auto)
            {
                IOperationResult submitResult = BusinessDataServiceHelper.Submit(context, billFormMetadata.BusinessInfo, successIds.ToArray(), FormOperationEnum.Submit.ToString());
                LoadSuccessIds(successIds, submitResult);
                GenMessages(result, submitResult, "提交");
                if (successIds.Count == 0) return result;
                if (isAutoSubmit == Ismode.submit && result.code == "200" && result.resultData.Count == 0)
                {
                    GenMessages(result, saveResult, "提交", true);
                   // result.msg = "同步成功";
                }
            }

            if (isAutoSubmit == Ismode.auto)
            {
                IOperationResult auditResult = BusinessDataServiceHelper.Audit(context, billFormMetadata.BusinessInfo, successIds.ToArray(), OperateOption.Create());
                LoadSuccessIds(successIds, auditResult);
                GenMessages(result, auditResult, "审核", true);
                if (result.code == "200" && result.resultData.Count == 0)
                {
                    GenMessages(result, saveResult, "审核", true);
                }
                if (result.code == "200")
                {
                    result.msg = result.msg.Replace("审核", "同步");
                }

                string createOrgFieldKey = billView.Model.BillBusinessInfo.GetForm().CreateOrgFieldKey;
                if (successIds.Count > 0 && useOrgIds.Count > 0 && !String.IsNullOrWhiteSpace(createOrgFieldKey))
                {
                    DynamicObject createOrg = billView.Model.GetValue(createOrgFieldKey) as DynamicObject;
                    if (createOrg != null)
                    {
                        foreach (long useOrgId in useOrgIds)
                        {
                            AllocateParameter allocateParameter = new AllocateParameter(billFormMetadata.BusinessInfo, "", (long)createOrg["Id"], Enu_AllocateType.Allocate, "Allocate");
                            allocateParameter.AllocateUserId = context.UserId;
                            allocateParameter.AutoSubmitAndAudit = true;
                            allocateParameter.DestOrgId = useOrgId;
                            allocateParameter.DestOrgName = "使用组织";
                            allocateParameter.PkId = successIds;
                            IOperationResult allocateResult = BusinessDataServiceHelper.Allocate(context, allocateParameter);
                            GenMessages(result, allocateResult, "分配", true);
                            if (result.code == "200" && result.resultData.Count == 0)
                            {
                                GenMessages(result, allocateResult, "分配", true);
                            }
                            if (result.code == "200")
                            {
                                result.msg = result.msg.Replace("分配", "同步");
                            }
                        }
                    }
                }
            }


            return result;
        }


        /// <summary>
        /// HTTP下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>xia
        /// <returns></returns>
        public Result HttpDownloadFile(HttpArgs http)
        {
            string FileId;
            long FileSize;
            string lx;
            HttpWebRequest request = WebRequest.Create(http.url) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Result result = new Result();
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }


            if (context == null)
            {
                result.code = "0010";
                result.msg = "请重新登录！";
                return result;
            }

            Stream responseStream = response.GetResponseStream();
            string name = HttpUtility.UrlDecode(response.GetResponseHeader("YXD-fileName").ToString(), System.Text.Encoding.UTF8);
            string fpath = PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH, name);
            //创建本地文件写入流
            string type = response.ContentType;
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            using (Stream stream = new FileStream(fpath, FileMode.OpenOrCreate))
            {
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                    result.code = "200";
                    result.msg = "下载成功";
                }
                result.code = "0001";
                result.msg = "下载失败文件大小为0";
            }
            UpDownloadService uploadService = new UpDownloadService();
            var fileName = Path.GetFileName(fpath);
            FileUploadResult uploadResult = null;
            using (FileStream fileStream = new FileStream(fpath, FileMode.Open, FileAccess.Read))
            {
                TFileInfo tFileInfo = new TFileInfo()
                {
                    CTX = context,
                    FileName = fileName,
                    Stream = fileStream,
                    Last = true,
                };
                uploadResult = uploadService.Upload(tFileInfo);
            }
            if (uploadResult != null && uploadResult.Success)
            {
                FileId = uploadResult.FileId;
                FileSize = uploadResult.FileSize;
                if (type == "application/pdf")
                {
                    lx = ".pdf";
                }
                else
                {
                    lx = ".xlsx";
                }
                FileAddDatabase(context, http.id, name, FileId, FileSize, lx);
                result.code = "200";
                result.msg = "上传成功";
                System.IO.File.Delete(fpath);
            }
            else
            {
                result.code = "0001";
                result.msg = "上传失败";
            }
            response.Close();
            responseStream.Close();
            return result;
        }

        //id,attachmentName,BillNo,creTime
        public void FileAddDatabase(Context context, string id, string attachmentName, string FileId, long FileSize, string lx)
        {
            string selectAttachmentSql = string.Format(@"select * from T_BAS_ATTACHMENT  where FBILLTYPE='SVM_ComparePrice' and FINTERID={0} and FATTACHMENTNAME='{1}'", id, attachmentName);
            DataTable dt = DBServiceHelper.ExecuteDataSet(context, selectAttachmentSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                string updateAttachmentSql = string.Format(@"update T_BAS_ATTACHMENT set FFILEID='{0}'  where FBILLTYPE='SVM_ComparePrice' and FINTERID={1} and FATTACHMENTNAME='{2}'", FileId, id, attachmentName);
                DBServiceHelper.Execute(context, updateAttachmentSql);
            }
            else
            {
                var meta = MetaDataServiceHelper.GetFormMetaData(context, "BOS_Attachment");
                DynamicObject dynamicdata = meta.BusinessInfo.GetDynamicObjectType().CreateInstance() as DynamicObject;
                string Sql = string.Format(@"select * from LQKJ_t_WorkorderHead where FID = '{0}'", id);
                DataTable dt1 = DBServiceHelper.ExecuteDataSet(context, Sql).Tables[0];
                dynamicdata["BillType"] = "LQKJ_WorkOrder";
                dynamicdata["InterID"] = id;
                dynamicdata["EntryKey"] = "";
                dynamicdata["AttachmentName"] = attachmentName;
                dynamicdata["BillNo"] = dt1.Rows[0]["FBillNo"].ToString();
                dynamicdata["CreateTime"] = dt1.Rows[0]["F_LQKJ_CreateDate"].ToString();
                dynamicdata["CreateMen_Id"] = dt1.Rows[0]["F_LQKJ_CreatorId"].ToString();
                dynamicdata["AttachmentSize"] = FileSize;
                dynamicdata["FBillStatus"] = "A";
                dynamicdata["EntryInterID"] = -1;
                dynamicdata["AliasFileName"] = attachmentName;
                dynamicdata["ExtName"] = lx;
                dynamicdata["FileId"] = FileId;
                dynamicdata["FileStorage"] = 1;
                dynamicdata["IsAllowDownLoad"] = 0;
                dynamicdata["SourceId"] = 0;
                BusinessDataServiceHelper.Save(context, meta.BusinessInfo, dynamicdata);
            }
        }

        /// <summary>
        /// 根据结果生成返回消息
        /// </summary>
        /// <param name="curResult"></param>
        /// <param name="result"></param>
        /// <param name="type"></param>
        private void GenMessages(Result curResult, IOperationResult result, string type, bool isRecordSuccess = false)
        {
            var isSuccess = GenMessage(curResult, result, isRecordSuccess);
            curResult.performances.Add(new Performance() { stage = type, pointTime = DateTime.Now });
            curResult.code = isSuccess ? "200" : "0001";
            curResult.msg = type + (isSuccess ? "成功" : "失败");
            if (curResult.resultData.Count > 0)
            {
                curResult.msg = curResult.resultData[0].msg;
            }
        }

        /// <summary>
        /// 根据结果生成返回消息明细
        /// </summary>
        /// <param name="curResult"></param>
        /// <param name="result"></param>
        private bool GenMessage(Result curResult, IOperationResult result, bool isRecordSuccess)
        {
            bool isSuccess = true;
            if (result.ValidationErrors != null)
            {
                foreach (ValidationErrorInfo errorInfo in result.ValidationErrors)
                {
                    string messageStr = errorInfo.Message.ToString();
                    ResultData resultData = new ResultData();
                    resultData.msg = messageStr;
                    curResult.resultData.Add(resultData);
                    isSuccess = false;
                }
            }
            if (result.OperateResult != null)
            {
                foreach (OperateResult opResult in result.OperateResult)
                {
                    if (opResult.SuccessStatus && isRecordSuccess)
                    {
                        if (string.IsNullOrWhiteSpace(opResult.Number)) continue;

                        ResultData resultData = new ResultData();
                        resultData.code = opResult.Number;
                        resultData.id = opResult.PKValue == null ? "" : opResult.PKValue.ToString();
                        resultData.msg = opResult.Message;
                        curResult.resultData.Add(resultData);
                    }
                    else if (!opResult.SuccessStatus)
                    {
                        ResultData resultData = new ResultData();
                        resultData.code = opResult.Number;
                        resultData.id = opResult.PKValue == null ? "" : opResult.PKValue.ToString();
                        resultData.msg = opResult.Message;
                        curResult.resultData.Add(resultData);
                        isSuccess = false;
                    }
                }
            }

            if (result.InteractionContext != null)
            {
                string messageStr = result.InteractionContext.SimpleMessage;
                ResultData resultData = new ResultData();
                resultData.msg = messageStr;
                curResult.resultData.Add(resultData);
                isSuccess = false;
            }
            return isSuccess;
        }


        /// <summary>
        /// 加载成功的ID
        /// </summary>
        /// <param name="successIds"></param>
        /// <param name="result"></param>
        private void LoadSuccessIds(List<object> successIds, IOperationResult result)
        {
            successIds.Clear();
            if (result.OperateResult != null)
            {
                foreach (var operateResult in result.OperateResult)
                {
                    if (operateResult.SuccessStatus)
                    {
                        successIds.Add(operateResult.PKValue);
                    }
                }
            }
        }
        public List<JObject> ImagePath(List<string> listPath)
        {
            K3CloudApiClient Client = apiClient();
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }
            List<JObject> imagePath = new List<JObject>();
            //string url = FileServerHelper.GetAppSiteOuterNetUrl(context, HttpContext.Current.Request);
            if (listPath.Count > 0)
            {
                for(int i = 0; i < listPath.Count; i++)
                {
                    JObject Json = new JObject();
                    var  data = "{ \"FileName\": \"photo666.jpg\",\"IsLast\": true,\"SendByte\": \"" + listPath[i] + "\"}";
                    var result = JObject.Parse(Client.UploadFile(data));
                    var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
                    if ((bool)Sueccess)
                    {
                        var File = result["Result"]["FileId"].ToString();//图片上传后的FileId
                        string fileUrl = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", File, context.UserToken);//文件就算一样路径不可能一样
                        Json.Add("FileId", File);
                        Json.Add("Url", fileUrl);
                        imagePath.Add(Json);
                    }
                }
            }
            return imagePath;
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="listPath"></param>
        /// <returns></returns>
        public JObject FilePath(string Base64string, string FileName)
        {
            K3CloudApiClient Client = apiClient();
            Context context = this.KDContext.Session.AppContext;
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }
            //string url = FileServerHelper.GetAppSiteOuterNetUrl(context, HttpContext.Current.Request);
            var data = "{ \"FileName\": \""+FileName+"\",\"IsLast\": true,\"SendByte\": \"" + Base64string + "\"}";
            var result = JObject.Parse(Client.UploadFile(data));
            var Sueccess = result["Result"]["ResponseStatus"]["IsSuccess"];
            JObject Json = new JObject();
            if ((bool)Sueccess)
            {
                var File = result["Result"]["FileId"].ToString();//图片上传后的FileId
                string fileUrl = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", File, context.UserToken);//文件就算一样路径不可能一样
                Json.Add("FileId", File);
                Json.Add("Url", fileUrl);
                return Json;
            }
            else
            {
                return null;
            }
        }
        public string UserToken()
        {
            Context context = this.KDContext.Session.AppContext;
            
            if (context == null && !string.IsNullOrWhiteSpace(dbid))
            {
                context = Login();
            }
            return context.UserToken;
        }
        private K3CloudApiClient apiClient()
        {
            K3CloudApiClient Client = new K3CloudApiClient(url);
            var loginResult = Client.ValidateLogin(dbid, username, password, 2052);
            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            if (resultType == 1)
            {
                return Client;
            }
            throw new Exception("登陆失败");
        }
    }
}


